Addition of Vectors?

Question: How do you explain in general the addition of any two vectors geometrically without reference to any coordinate system?
Comment: You're sticking a vector parallel to $\mathbf{B}$ to the end of $\mathbf{A}$, and then considering the vector with initial point that of $\mathbf{A}$ and terminal point that of (the copy of) $\mathbf{B}$.
Comment: I think paralleogram law of addition can help.
Answer: It is sufficient to check wikipedia (http://en.wikipedia.org/wiki/Parallelogram_law):
Answer: If the starting point of $\vec{A}$ and $\vec{B}$ are coincident, $\vec{A} + \vec{B}$ is the vector from that common starting point to the far corner of the parallellogram which has as two of its sides $\vec{A}$ and $\vec{B}$.
There is no need for a coordinate system in this definition.  The coordinate system comes about when you start saying things like $\vec{A} = <2,3>$.  ($2$ what?  $3$ what?)
Comment: you don't prove definitions. You can prove that two definitions are equivalent, or prove that something you've defined satisfies some other nice properties you wanted (e.g. prove that this geometric definition of addition is commutative, associative). But it makes no sense to ask for a proof of a definition.
Comment: Actually i did not intend to ask the question "How do you explain the addition of vectors geometrically without reference to any coordinate system?" taking into consideration the example that goes along with it. I have edited the question. Please take a look.
Comment: My answer still addresses your question. You introduce a coordinate system precisely when you start talking about components of the vector. There is none before that. A parallelogram is a parallelogram regardless of the coordinate system, or even where there is one or not.
Comment: As you said that "A⃗ +B⃗  is the vector from that common starting point to the far corner of the parallellogram which has as two of its sides A⃗  and B⃗ " . Is there any way to prove that sum of the vectors is indeed the diagonal of the parallelogram whose  adjacent sides are the 2 vectors that are being added.
Comment: That's one way that vector addition can be defined.  There's no need for a coordinate system if it's defined this way.  Or ... vector addition can be defined in terms of the componentwise sum of ordered pairs.  That works too, and in *that* cases there's no need for a graphical analog.
Comment: "That's one way that vector addition can be defined."
How was this definition arrived at or is there any method to prove it?
Comment: Sorry for framing the question in wrong way. But the first part of the question "How was this definition arrived at" was still valid. I think @celtschk has provided us with the correct answer.
Answer: Another way is to remember that vectors describe translations, that is moving without rotating. The arrow just shows for a single point where that point ends up after the movement. The addition of the two vectors is just the result of doing both translations one after another; the resulting translation can then again be described by an arrow that starts at an arbitrary point, and ends where that point ends up after doing that combined movement.
This method has the advantage that it doesn't matter whether the arrows start at the same point, and that it is obvious that it doesn't matter where the arrow starts; all arrows with the same length and direction describe the same vector, because they describe the same translation.
Also from this, one naturally gets the common description of vector addition by starting the second arrow at the end of the first one; the natural explanation being "this point is moved to there by the first translation, and then further to over there by the second translation; the sum arrow goes from the starting point directly to the final end point".
Comment: your answer has made it clear for me. Thank you :)

Addition of Vectors?


8 - How to programmatically add terms to an existing Node

Question: After loading a node with Node::load with an existing taxonomy field abc do I add a new term and save? Something like?
  $term = Term::load(123);
  $node->get('abc')->appendItem($term );

Comment: I think `$node->get('abc')->appendItem(['target_id' => 123]);` would work
Comment: Strange - it seems that my approach also work... still checking.
Comment: Yes, that is correct. The code to set the value of reference entries is very tolerant and accepts the full array with target_id and/or entity keys, a skalar with the id and an object of the term, which is then used to retrieve the id and store it in the database. But it does not make sense in your case to load the term and pass it, when later it is only used to get the id.
Answer: This is the correct long form, as in the comment of mradcliffe:
$node->get('abc')->appendItem(['target_id' => 123]);

You don't need to load the term, use the term id.
You can use shorter versions:
$node->abc->appendItem(['target_id' => 123]);
$node->abc[] = ['target_id' => 123];
$node->abc[] = '123';

Comment: @Rob, yes, you have to loop over the field values. You don't need to use getIterator() though, because the array interface works like a normal array and you can put the field object directly in a foreach loop
Comment: For the last short form, is it really '123' as a string?
Comment: Is this documented somewhere officially? I tried to look this up on Drupal.org but without success
Comment: You can use both, string and int. There are magic functions in the object to use the itemlist as array and the fields in the shortened version.
Comment: Will this ignore duplicates? I'm prepareing an import script and an worried it will corrupt something if I run `$node->abc[] = '123';` multiple times during testing
Comment: You have to check yourself for duplicates, drupal does not do this.
Comment: How to check for duplicates? ItemList seems to not have a function to get item with value, so I think the only way would be to use ItemList::filter() or ItemList::getIterator() and loop over, then removeItem() if found.
Answer: Just check the following code, its a dummy code need to be test
use \Drupal\node\Entity\Node;

$node = Node::create([
      'type'        => 'article',
      'title'       => 'Druplicon test',
    ]);
    $node->set('myterm_field', 'NEW TERM');
    $node->save();

Comment: I don't think that entity reference fields are set using a string value.


Windows cannot set folder security by user group

Question: I have create a new user group [Group A] in Windows Server, create a new user [User 1] as member of [Group A].
If I set a folder security to [Allow] by user [User 1], the setting will work, [User 1] can access the folder.
If I set the folder security to [Allow] by user group [Group A], the setting not work, [User 1] cannot access the folder even [User 1] is member of [Group A]
What I expect is I should able to set folder security by [User Group] instead of setting by [User]
Any steps I missing or wrong?
Thanks in advance
Answer: The User must log off and log on again, otherwise the new group membership will not be effective.
Comment: or the user can run `klist purge` to delete existing Kerberos tickets. These get recreated when the user reauthenticates to stuff in the background - no logoff required.
Comment: @TrixM You can do that in a lab or for testing purposes but I wouldn't recommend doing that in production. Weird behavior can occur until you log off/on again, see the documentation.
Comment: Yes, I know. I have seen the doco, quite a lot in 20+ years.. But it's quick and easy and works nearly all the time. Definitely not a substitute for logging off regularly to keep things fresh, but for a quick check it's fine. Thus the comment and not a full answer. Also, it doesn't *hurt* anything in a production environment. If it doesn't seem to help, then the fallback is simply logging off/on again.
Comment: Thanks all for your advice. My mistake, I just **disconnect** rather than **sign out** from server. The folder security work after I sign out and sign in again.


How to pass remote server ip as header in haproxy tcp tunnel with accept-proxy enabled?

Question: I need to a variable for haproxy that is the actual remote ip while still using accept-proxy, like http-response set-header Upstream-Server %[req.real_ip]. %[src] does not work and sends the client ip from the proxy protocol if accept-proxy is active.
I have a setup like this:

haproxy load balancers
haproxy ddos protection servers
nginx proxying to PHP web applications

1 accepts public Internet HTTP/S connections and mode tcp forwards them.
2 accept-proxy these connections, terminates ssl crt, and then applies anti-bot logic.
3 is the final destination and web application.
This is a pretty complicated setup so occasionally there are hiccups in the configuration which are hard to diagnose because of the number of moving parts. I need nginx to know the IPs of 1 and 2 so it can send that to the actual web application for debugging.
Answer: Very obtuse but this works.
tcp-request must appear before any http-request to not cause warnings. tcp-request connection is the only scope in which src is not changed by the accept-proxy directive in bind. Thus,
frontend http-in
        bind :443 ssl crt /etc/ssl/mycert accept-proxy
        option forwardfor

        tcp-request connection set-var(sess.last_server_ip) src
        http-request add-header X-Forwarding-Frontend %[var(sess.last_server_ip)]

This will add the header X-Forwarding-Frontend with the value of the server that haproxy received the proxy protocol request from. It must be set as a variable this way, because src has a different value in every other context when not as an argument for tcp-request connection.


Emgu CV memory leaks on loading more than 1000 training images

Question: i just dont know what to do within this method LoadFaceRecognition,
this method load the training images smoothly when it have less than 800 training images but as soon as I add  images the loading of data stops executing and memory consumption expands. Please help me with this
training imgaes are the Grayscale images
this is LoadFaceRecognition,
private bool LoadFaceRecognition(string Training_Folder, string TrainedFaces) {

  if (File.Exists(Training_Folder + TrainedFaces + "/TrainedLabels.xml"))
    {
        try
        {
            Names_List_Faces.Clear();
            trainingImages_Faces.Clear();
            FileStream filestream = File.OpenRead(Training_Folder + TrainedFaces + "/TrainedLabels.xml");

            long filelength = filestream.Length;
            byte[] xmlBytes = new byte[filelength];
            filestream.Read(xmlBytes, 0, (int)filelength);
            filestream.Close();

            MemoryStream xmlStream = new MemoryStream(xmlBytes);
            XmlReader xmlreader = XmlTextReader.Create(xmlStream);

            while (xmlreader.Read())
            {
                if (xmlreader.IsStartElement())
                {
                    switch (xmlreader.Name)
                    {
                        case "NAME":
                            if (xmlreader.Read())
                            {
                                //Names_List_ID.Add(Names_List.Count); //0, 1, 2, 3....
                                Names_List_Faces.Add(xmlreader.Value.Trim());
                                NumLabels_Faces += 1;
                            }
                            break;
                        case "FILE":
                            if (xmlreader.Read())
                            {
                                //PROBLEM HERE IF TRAININGG MOVED
                                trainingImages_Faces.Add(new Image<Gray, byte>(Training_Folder + "/TrainedFaces//" + xmlreader.Value.Trim()));

                            }
                            break;
                    }
                }
            }
            ContTrain_Faces = NumLabels_Faces;
            if (trainingImages_Faces.ToArray().Length != 0)
            {
                recognizer_Faces = new EORecognizer(trainingImages_Faces.ToArray(), Names_List_Faces.ToArray(), Eigen_Threshold, ref termCrit_Faces);
                return true;

            }
            else return false;
        }
        catch (Exception ex)
        {
            Error = ex.ToString();
            return false;
        }
    }
    else return false;
}

Answer: You are missing a few Dispose or using statements there.
You need to free up resources for some of the objects you are using like the Strems.
Try with the following code:
private bool LoadFaceRecognition(string Training_Folder, string TrainedFaces) {

      if (File.Exists(Training_Folder + TrainedFaces + "/TrainedLabels.xml"))
        {
            try
            {
                Names_List_Faces.Clear();
                trainingImages_Faces.Clear();
                using (FileStream filestream = File.OpenRead(Training_Folder + TrainedFaces + "/TrainedLabels.xml"))
                {

                    long filelength = filestream.Length;
                    byte[] xmlBytes = new byte[filelength];
                    filestream.Read(xmlBytes, 0, (int)filelength);
                    filestream.Close();

                    using (MemoryStream xmlStream = new MemoryStream(xmlBytes))
                    {
                        using(XmlReader xmlreader = XmlTextReader.Create(xmlStream))
                        {

                            while (xmlreader.Read())
                            {
                                if (xmlreader.IsStartElement())
                                {
                                    switch (xmlreader.Name)
                                    {
                                        case "NAME":
                                            if (xmlreader.Read())
                                            {
                                                //Names_List_ID.Add(Names_List.Count); //0, 1, 2, 3....
                                                Names_List_Faces.Add(xmlreader.Value.Trim());
                                                NumLabels_Faces += 1;
                                            }
                                            break;
                                        case "FILE":
                                            if (xmlreader.Read())
                                            {
                                                //PROBLEM HERE IF TRAININGG MOVED
                                                trainingImages_Faces.Add(new Image<Gray, byte>(Training_Folder + "/TrainedFaces//" + xmlreader.Value.Trim()));

                                            }
                                            break;
                                    }
                                }
                            }
                            ContTrain_Faces = NumLabels_Faces;
                            if (trainingImages_Faces.ToArray().Length != 0)
                            {
                                recognizer_Faces = new EORecognizer(trainingImages_Faces.ToArray(), Names_List_Faces.ToArray(), Eigen_Threshold, ref termCrit_Faces);
                                return true;

                            }
                            else return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Error = ex.ToString();
                return false;
            }
        }
        else return false;
    }

Comment: actually I already tried that code but nothing change. still the loading of training images takes too much time and  of memory and worst the program cannot load faster


Is it possible to control the legend key size when using ggdag?

Question: I am drawing DAGs in R using ggdag and I would like to change the size of the legend key without changing the size of the DAG nodes.
The theme() argument legend.key.size appears to control the size of an invisible box around the legend key, but doesn't affect the actual key size, as illustrated by the code below.

ggdag::confounder_triangle() %>%
  ggdag::node_status() %>%
  ggplot(aes(x=x,y=y, color = status)) +
  geom_dag_point() +
  theme(legend.key.size = grid::unit(3, 'cm'))

The key size appears to respond to the size argument in geom_dag_point(), as illustrated with this code:
ggdag::confounder_triangle() %>%
  ggdag::node_status() %>%
  ggplot(aes(x=x,y=y, color = status)) +
  geom_dag_point(size = 4)

Is it possible to change the key size without changing the node size?
Comment: Sorry, `confounder_triangle` is a function from `ggdag`. I've edited the question to clarify. Hopefully that is reproducible now.
Comment: Can you share a the output of `confoudner_triangle` so that we can run that code and help you to solve this problem?!
Answer: You can change the size of the color with the guide_legend by the same override.aes argument in your guides. You can use the following code:
library(ggdag)
library(ggplot2)
ggdag::confounder_triangle() %>%
  ggdag::node_status() %>%
  ggplot(aes(x=x,y=y, color = status)) +
  ggdag::geom_dag_point() +
  guides(color = guide_legend(override.aes = list(size = 2)))

Created on 2022-07-14 by the reprex package (v2.0.1)


Estimating out-of sample forecast for an ARIMA model

Question: I'm trying  to estimate the out-of sample forecast of an ARIMA model, I tried the code below, but it totally doesn't work!
for(i in 1:83) {
   mod[i] <- arima(window(betahat[,1], start=1, end=109+i),order=c(1,0,0),include.mean=TRUE)
   pre[i] <- predict(mod[i],12)
   error[i] <- pre[i]$pred[12]-betahat[(109+i+12),1]
}

the data are taken monthly and I divided the data into 2 subsets, the first  composed by 109 obs and the second by 83 observations. From the code I would like to obtain the error for each 12 month forecast, so about  59 errors. In the code I probably have to add an if , the argument in [109+i+12] has to be lower than 192, but it's not the problem.
I don't know how to obtain each error, I would like that the outcome of the loop is the list of all the errors.
I would appreciate any suggestions.
Comment: Here's some sample code for time-series cross-validation (or rolling out-of-sample forecasts) that might be useful: http://robjhyndman.com/researchtips/tscvexample/
Answer: In the future it would help if you provided error messages, etc., but for this problem it's easy enough to fix anyway.   Just some comments before the code:
1) You don't have to subscript the model or predictions.
2) In the code below, betahat is a vector, not a matrix.  Your betahat might also be a vector, which would have caused errors in your run (hence the value of providing the error messages!)
3) Make your for-loop indices correct!
Here you go:
betahat <- rnorm(192)
error <- rep(0,71)
for (i in 1:71) {
   mod <- arima(window(betahat, start=1, end=109+i),order=c(1,0,0),include.mean=TRUE)
   pre <- predict(mod,12)
   error[i] <- pre$pred[12]-betahat[109+i+12]
}


The outcome of part of Exercise 7.1.4 of one of Robinson's books.

Question: This is concerning part of Exercise 7.1.4 of Robinson's, "A Course in the Theory of Groups (Second Edition)". According to this search of "similarity type" in the group-theory tag, it is new to MSE.
The Details:
(This can be skipped.)
Arguments are written on the left of functions.
A permutation group is, given a nonempty set $X$, a subgroup $G$ of $S_X$; its degree is the cardinality of $X$.
A permutation group $G$ on $X$ is transitive if, for any $x,y\in X$, there is a permutation $\pi\in G$ such that $x\pi=y$
A similarity from permutation groups $G$ and $H$ on sets $X$ and $Y$, respectively, is a pair $(\alpha, \beta)$ consisting of an isomorphism $\alpha:G\to H$ and a bijection $\beta:X\to Y$ such that
$$\pi\beta=\beta\pi^{\alpha}$$
for all $\pi\in G$.
A similarity type is an equivalence class of similarities.
The Question:
Here is Exercise 7.1.4:

List all similarity types of transitive permutation groups of degree less than or equal to five.

However, I am interested in what the answer would look like, not a full solution. The reason why, I hope, will become clear from my thoughts below.
Thoughts:
According to GroupNames, $S_5$ has $156$ subgroups; I doubt I have to sieve through them all, looking for transitive groups.
But I don't know how to do this exercise without brute force.
Surely there's a more sophisticated way . . .
I don't suppose it'd be difficult to put this in GAP. I haven't had chance to over the last couple of weeks, due to other commitments.
I want to ask this question sooner rather than later. I'm starting to forget the preceding material of the book.

The kind of answer I'm looking for is a description of what a solution to the exercise would look like, with an emphasis on techniques beyond brute force.

Please help :)
Comment: I personally would list all isomorphism types of subgroups $G$ of $S_5$, then for each of these work out all $\mathrm{Aut}(G)$-classes of core-free subgroups of $G$ of index at most $5$. There aren't too many such groups, which is what makes this approach feasible. But it is still brute force.
Comment: Since the order of each transitive subgroup of the group $S_5$ is divisible by $5$, it is sufficient to consider subgroups of orders $5$, $10$, $20$, and $60$. And this is not such a big problem.
Comment: Here's why. If $H$ is a transitive subgroup, then denote
$$
H_i=\{\sigma\in H\mid\sigma(1)=i\},\ i=1,2,3,4,5.
$$
It is easy to check that $H_1$ is a subgroup of $H$ and $H_i$ are cosets.
Comment: How come they're divisible by $5$, @kabenyuk?
Comment: Please pare down the verbosity and exaggerated vertical length of your posts.  And can I ask, are you compiling a complete solution manual to this Robinson text?
Comment: Come now! I'd rather have too much context than not enough, @amWhy; besides: I think everything in the question is necessary. No, I am not compiling a solution manual - just working my way through the book.
Comment: I'll take a charitable interpretation of that comment, @amWhy. Thank you. Good luck to you too!
Comment: At the very least, give of the freshman: "please help me :)" You're not 18 years old anymore.
Comment: That's just manners, @amWhy.
Answer: If the group is transitive of degree $5$ it must contain a $5$-cycle, and that must generate a $5$-Sylow subgroup, call it $S$. If $S\triangleleft G$, then $G$ is (up to similarity) a subgroup of $N_{S_5}(\langle(1,2,3,4,5)\rangle)$, which is a semidirect product of $S$ with $C_4$. (There are 3 possibilities, orders 5,10, 20. Otherwise, there is more than one $5$-Sylow subgroup, which implies that the order of $G$ is at least $5\cdot 6=30$. But $S_5$ has no sugroup of index $4$ (would give homom. into $S_4$, and normal subgroup that does not exist. So then $|S|\in\{60,120\}$ with $A_5$ and $S_5$ as the only possibilities.


google universal analytics events sent but not received by analytics

Question: I am using google universal analytics on my website. Although POST requests seem to be sent correctly there are no tracked events in my analytics account.
This is the post request (url and analytics id are masked)
Request URL:http://www.google-analytics.com/collect
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:120
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:www.google-analytics.com
Origin:http://www.xxxxxxxx.com
Referer:http://www.xxxxxxxx.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
Form Dataview sourceview URL encoded
v:1
tid:UA-xxxxxxxxx-1
cid:3E1FA9FE-28B3-7032-1714-5083DD155FCF
t:click
ec:link
ea:outbound_link
el:startpage
ev:headline
Response Headersview source
Access-Control-Allow-Origin:*
Cache-Control:private, no-cache, no-cache=Set-Cookie, proxy-revalidate
Connection:keep-alive
Content-Length:35
Content-Type:image/gif
Date:Fri, 10 May 2013 13:25:44 GMT
Expires:Mon, 07 Aug 1995 23:30:00 GMT
Last-Modified:Sun, 17 May 1998 03:00:00 GMT
Pragma:no-cache
Server:GFE/2.0
Via:1.0 non_disclosed:3128 (squid)
X-Cache:MISS from non_disclosed
X-Cache-Lookup:MISS from non_disclosed:3128
X-Content-Type-Options:nosniff

Does anyone have a clue what's going on here? Thanks!
Jesse
UPDATE
I was trying to send the request via jquery's $.post method first. You can see the result above. Nothing has been tracked by Google Analytics.
Now I switched to this method as described in the analytics.js developer guide
function trackOutboundLink(link, event_hittype, event_category, event_action, event_value) {
ga('send', event_hittype, {
    'clientId' : clientId,
    'eventCategory' : event_category,
    'eventAction' : event_action,
    'eventLabel' : link.href,
    'eventValue' : event_value,
    'hitCallback' : function () {
        // document.location = link.href;
    }
});

    window.open(
        link.href,
        '_blank'
    );
}

The generated request looks like this:
Request URL:http://www.google-analytics.com/collect?v=1&_v=j8&a=217518556&t=event&dl=http%3A%2F%2Fwww.mywebsite.de%2F&ul=de&de=UTF-8&dt=Foosd=24-bit&sr=1440x900&vp=1439x747&je=1&fl=11.7%20r700&ec=OutboundLinkClick&ea=Startpage&el=http%3A%2F%2Ftest.de&ev=Headline&_u=OCC~&cid=283560406.1367606414&tid=UA-XXXXXXXX-1&z=496696042
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:www.google-analytics.com
Referer:http://www.mywebsite.de/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
Query String Parametersview sourceview URL encoded
v:1
_v:j8
a:217518556
t:event
dl:http://www.mywebsite.de/
ul:de
de:UTF-8
dt:Foo
sd:24-bit
sr:1440x900
vp:1439x747
je:1
fl:11.7 r700
ec:OutboundLinkClick
ea:Startpage
el:http://test.de
ev:Headline
_u:OCC~
cid:283560406.1367606414
tid:UA-XXXXXXXX-1
z:496696042
Response Headersview source
Access-Control-Allow-Origin:*
Age:120360
Cache-Control:private, no-cache, no-cache=Set-Cookie, proxy-revalidate
Content-Length:35
Content-Type:image/gif
Date:Thu, 16 May 2013 00:10:08 GMT
Expires:Mon, 07 Aug 1995 23:30:00 GMT
Last-Modified:Sun, 17 May 1998 03:00:00 GMT
Pragma:no-cache
Server:GFE/2.0
X-Content-Type-Options:nosniff

Event is fired correctly while the target link is opened in a new window. Status is 200 for the request.
Guess what, I do not get any events tracked in google Analytics. I double-checked the UA code and I cannot imagine any filter in analytics because I did not set one up.
This method is online since yesterday (24 hours). I don't know what's the problem here.
Answer: One thing I do see that's off is t:click.  If it were an event it would show t:event
https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#event
Comment: Sorry for my late answer. You are right it must be t:event but nonetheless it is not working. I tried this request from the website but nothing happens in my analytics account
http://www.google-analytics.com/collect?v=1&tid=UA-12312312-1&cid=283560406.1367606414&t=event&ec=link&ea=click⪙=outbound_detailpage&ev=image
Comment: i assume you did obvious checks like make sure the account number is right, no filters setup that would reject it, etc.?  How long are you waiting to check if it shows up? It can take up to 24 hours to show up.  Did you try outputting the same custom code via the js imp to compare request urls? if so, did you try seeing if the same thing vs js works?
Comment: What do you mean by "outputting the same custom code via the js imp to compare request urls"?
Comment: @Jesse Okay, so you are currently doing this via server-side code, e.g. with a curl request, or else using some API to build the query string and send it, yeah? I assume so because that's the only way it would be a POST request.  Well the standard implementation is via javascript like on a web page (which is a GET request).  So what you can do is make a test webpage with the javascript version of your code and load the web page and compare requests.
Comment: @jesse stupid question- you are masking the account number only here and not in your real code,  yes?
Answer: Ok, here we go.
It seems as if the problem was piping the event through another method.
I finally managed to make it work with this setup:

    ...

and then in the view
Outbound headline link on my startpage

All relevant data including unique user id is applied to the event and fired correctly. You can see data flowing in immediately when looking at the realtime event view in google analytics.
Thanks for your help guys.
By the way: There is a nice tutorial over at http://blog.kissmetrics.com/universal-analytics
Comment: This was an interesting resolution, however in my case, I am only seeing about 1:20 requests. On my home machine I see the requests instantly with a 1:1. On my remote machines, I get random results. This has been very elusive and problematic.


Assign "glyphicon download-alt" icon to a submit button

Question: I have an issue with adding glyphicon icon to a submit button. Once I try it with "a" tag, the action did not work when I press the button. So how do I do it?
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<form method="post" action="<%=Const.ActionURIs.INSTRUCTOR_COURSE_STUDENT_LIST_DOWNLOAD%>" style="display:inline;">
            <input id="button_download" type="submit" class="btn btn-primary"
                    name="<%=Const.ParamsNames.FEEDBACK_RESULTS_UPLOADDOWNLOADBUTTON%>"
                    value=" Download Student List ">

            <input type="hidden" name="<%=Const.ParamsNames.USER_ID%>" value="${data.account.googleId}">
            <input type="hidden" name="<%=Const.ParamsNames.COURSE_ID%>" value="${courseDetails.course.id}">
        </form>

Answer: Use a <button> tag instead of an <input> tag. Change your button like this:
<button type="submit" class="btn btn-primary" id="button_download" name="<%=Const.ParamsNames.FEEDBACK_RESULTS_UPLOADDOWNLOADBUTTON%>">
   Download Student List
</button>

The reason it doesn't work is given on Bootstrap website.
Don't mix with other components : Icon classes cannot be directly combined with other components. They should not be used along with other classes on the same element. Instead, add a nested  and apply the icon classes to the .
Working example:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<form>
<button type="submit" class="btn btn-primary">
   Download Student List
</button>
</form>


Find the number of points in $(-\infty,\infty)$ for which $x^2-x\sin x-\cos x=0.$

Question: Find the number of points in $(-\infty,\infty)$ for which $x^2-x\sin x-\cos x=0.$

How should i attempt this question?I have no idea.Please help.Thanks.
Answer: This is a nice, differentiable function, and the question asks for only the number of solutions. I'll use the standard method to attack problems of this kind: we try to divide the function up into areas where it is growing and falling, and then appeal to the intermediate value theorem over a few domains to get the answer. For this particular case, this proceeds as below.
Let $f(x) = x^2 - x \sin x - \cos x$.
Note that:
$$f'(x) = x (2 - \cos x) : \left\{ \begin{array}{ll}
  >0  & \mbox{if } x > 0 \\
  <0 & \mbox{if } x < 0  \\
        = 0 & \mbox{if } x = 0
 \end{array} \right. $$
and that $$f(0) = -1$$ $$ f(x) \underset{x \to \pm \infty}{\longrightarrow} \infty $$
So, $f$ is always decreasing for negative $x$, is positive for negative $x$ with large magnitude, and is negative for $x = 0^{-}$. By this and the intermediate value theorem, there exists exactly one solution for $f(x) = 0$ in $(-\infty, 0)$
Similarly, there exists exactly one solution in $(0, \infty)$
As $x = 0 $ is not a solution, the total number of solutions in $\mathbb{R}$ for the equation  is $2$.
Answer: Here we have to calculate number of real values of $x$ in $x^2=x\sin x+\cos x$
So we will draw graph of $f(x) = x^2$ and $f(x) = x\sin x+\cos x$
First one is upward parabola passing through origin and for drawing graph of
$f(x)=x\sin x+\cos x\;,$ we will put $\displaystyle x=0\;,\frac{\pi}{2}\;,\pi,\frac{3\pi}{2},2\pi$ and $f(-x) = f(x)$
Means $f(x)$ is an even function .

So here these two graph intersect each other at $2$ distinct point
So we get number of real solution of the equation is $\bf{Two}$


List all days of week in query

Question: I'm trying to list all days of the next week of given date
Example:
If today is 2019-09-24 then the result should be:
DAY_OF_WEEK

2019-09-24
2019-09-25
2019-09-26
2019-09-27
2019-09-28
2019-09-29
2019-09-30

This is the query I came up with and I wonder if there is more elegant way to achieve the same results:
SELECT date('now') AS DAY_OF_WEEK
UNION
SELECT date('now', '+1 day') AS DAY_OF_WEEK
UNION
SELECT date('now', '+2 day') AS DAY_OF_WEEK
UNION
SELECT date('now', '+3 day') AS DAY_OF_WEEK
UNION
SELECT date('now', '+4 day') AS DAY_OF_WEEK
UNION
SELECT date('now', '+5 day') AS DAY_OF_WEEK
UNION
SELECT date('now', '+6 day') AS DAY_OF_WEEK

Answer: Your code is correct.
If you want you can use a CTE which returns only the numbers from 0 to 6 and select from it the number of days to add to the current date:
WITH days as (
  SELECT 0 AS day UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL
  SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
)
SELECT date('now', '+' || day || ' day') AS DAY_OF_WEEK FROM days

See the demo.
Or with a RECURSIVE CTE:
WITH RECURSIVE days(day) AS (
  SELECT 0
  UNION ALL
  SELECT day + 1 FROM days
  LIMIT 7
)
SELECT date('now', '+' || day || ' day') AS DAY_OF_WEEK FROM days;

See the demo.
Results:
| DAY_OF_WEEK |
| ----------- |
| 2019-09-24  |
| 2019-09-25  |
| 2019-09-26  |
| 2019-09-27  |
| 2019-09-28  |
| 2019-09-29  |
| 2019-09-30  |

List all days of week in query


Can't get my SSTP VPN to works due to a certificate issue

Question: I am trying to create a SSTP VPN on my Windows Server 2008 R2, I installed the Network Policies and Access Service, and the AD Certificate Autority service,
I create my root certificate and generated a Server authentication certificate (named with the FQDN of the server), validated it and installed it on the server, I also have installed the CA authority certificate on the client that I need to connect, but when I try to connect, I get this error

Could not build a certificate chain for CA certificate 0 for xxx.netyxia.net-DC-CA.  A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider. 0x800b0109 (-2146762487).

(xxx.netyxia.net is the (altered) hostname), the certificate is deployed on both the server and the client..
I've searched for hours... and nothing :(
Any idea please ?
Thank you
Answer: It sounds like you've installed the certificate in the wrong store, you should try manually putting it in Trusted Root Certificate Authorities on the client machine.
Take these steps on the client machine: MMC > Add 'Certificates' snap-in for local computer > Trusted Root Certificate Authorities > Import the certificate here.
Comment: also make sure the ssl listener in RRAS is configured to point to the ssl certificate you are wanting to user to secure the VPN
Comment: Make sure to install this certificate on the *local computer* storage, not for just user session.
Comment: I've checked this, but its alreary installed, but does the certificate needs to use the used DNS name, or the "real" machine name ? How does the client know what certificate to use ? Because I don't have configured anything to tell the VPN server/client to use this specific certificate
Comment: Oky i've found that I had to define the certificate on the VPN properties, thank you
Answer: If you are using a self signed certificate on a Windows Server, you may need the certificate bound to the VPN host address itself and one from the server itself that has issued this certificate.  I have just set up a SSTP VPN on Windows 2012R2 Essentials and at the client end, I had to do two things:

Install the VPN certificate (e.g. my.vpn.hostname.com) AND the Windows server CA ceritifcate that signed it.  Both of these needed to be installed in the Local Computer account (NOT the user section) of the client in the Trusted Root Certificate Authorities section.  This gives you the chain - the Windows Server CA that signed this certificate is trusted and the VPN certifcate is trusted.  You can normally get your Server CA cert from the Windows Active Directory cert server e.g. my.domain/certsvr, or just export it.

As its self signed, you will likely get an error (I did...) re the client being unable to check for revocation. Go to RegEdit and add a new DWORD called NoCertRevocationCheck key in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SstpSvc\Parameters and set this to 1 (i.e. true, don't check to see if cert has been revoked)

Ideally you would use a cert issued by a proper CA to avoid any issues over revocation servers being available.  Re the certificates themselves, this article goes into detail about the security aspects:
https://directaccess.richardhicks.com/2018/07/16/always-on-vpn-ssl-certificate-requirements-for-sstp/


The easiest way for paging with MVC3 C#?

Question: Have a website project in MVC3 C # where I retrieve information from the database and presents in a table in my view. I want to use paging to show up to five lines per page. Have been looking for tutorials on Internet but they all seem very advanced to achieve it. What is the easiest way for paging with MVC3?
Look in the lower left corner of the picture to see what I mean by paging
paging http://www.syncfusion.com/content/en-US/products/feature/user-interface-edition/aspnet-mvc/grid/img/Paging_Larger.jpg
Answer: Try PagedList. There's a NuGet package for MVC.
@{
    ViewBag.Title = "Product Listing"
}
@using PagedList.Mvc; //import this so we get our HTML Helper
@using PagedList; //import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)

<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />

List of Products

    @foreach(var product in ViewBag.OnePageOfProducts){

@product.Name

    }

@Html.PagedListPager( (IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page }) )

Comment: thanks for mentioning the NuGet package: install-package PagedList ...very easy :)
Answer: Alternatively, this NuGet package is also very useful and easy to implement. I would highly recommend going through this utility.
https://github.com/martijnboland/mvcpaging
NuGet [PM> Install-Package MvcPaging ]


Converting epoch time to PST zone in hadoop/hive

Question: I want to convert the epoch time into pst time zone.
For example : 1482440069 when I convert to PST, I should get 2016-12-22
Now, when I try this I get proper answer
SELECT  from_utc_timestamp('1970-01-01 07:00:00', 'PST');

Also, When I try this, I get proper value
select from_unixtime(cast(1482440069 as bigint), 'yyyy-MM-dd')
o/p : 2016-12-22

But, When I try this query, I get NULL response
select from_utc_timestamp(from_unixtime(cast(1482440069 as bigint), 'yyyy-MM-dd'),'PST') -- Gives NULL response

Answer: You can try:
SELECT  from_utc_timestamp(cast(from_unixtime('1970-01-01 07:00:00', 'yyyy-MM-dd HH:mm:ss') as bigint) + (time_zone value like -5 or -6 * 3600));

Answer: Use yyyy-MM-dd HH:mm:ss instead of yyyy-MM-dd
hive> select from_utc_timestamp(from_unixtime(cast(1482440069 as bigint), 'yyyy-MM-dd HH:mm:ss'),'PST');
OK
2016-12-22 04:54:29


Differential equation of population growth or decay $\frac{dP}{dt}=KP(P_m-P)$

Question: Verhulst's Logistic Growth Model , an equation to model population growth or decay:
$$\dfrac{dP}{dt}=KP(P_m-P)$$
One way to do it is by partial fractions,
I get:
$\int \frac{1}{P(P_m-P)}  \frac{dP}{dt} dt = \int K dt$
By using partial fraction decomposition
$\int \frac{1/P_m}{P} + \frac{1/P_m}{(P_m-P)} dP = \int K dt$
This then gives :
$e^{(P_mKt)}e^{CP_m} = |P||P_m-P|$
But the solution (moment 33:11) is :$$\dfrac{AP_m}{A+e^{-kP_mt}}$$
What did I do wrong? Or what was a better way to do it?
Answer: The result of the integration is
$$ \frac{1}{P_m} \left(\ln |P| - \ln|P_m-P|\right) = Kt + C$$
that is
$$ e^{P_m(Kt+C)} = \left|\frac{P}{P_m-P}\right|$$
$$ \frac{P}{P_m-P} = A e^{P_mKt}$$
$$ \frac{P_m}{P_m-P} = 1+ \frac{P}{P_m-P} = 1 + A e^{P_mKt}$$
$$ \frac{P}{P_m} = \frac{A e^{P_mKt}}{1 + A e^{P_mKt}}$$
$$ P = \frac{A P_m}{A + e^{-P_mKt}}$$
Answer: When you integrated, you had a sign error:$$\int\frac{dP}{P_m-P}=\color{blue}{-}\ln|P_m-P|+C.$$


Vercel old preview deployments

Question: I really like to deploy apps on Vercel. I do however wonder how one is supposed to deal with all the preview deployments that inevitably will get created.
Are you supposed to delete them yourself? Is there a way to automate deletion of preview deployments after a certain amount of time?
Answer: There is no need to delete preview deployments because they are not indexed by search engines.
If you want to make sure no one outside your organization can access preview deployments, you can enable password protection for your project.
Comment: would still like to be able to control when they are deleted :)
Comment: Totally agree here, @FabianBosler. Were you able to figure out in the end?
Comment: If you're working with a database, however, I'd be worried that an old deployment might function in a way that destroys data or inserts/updates records improperly according to the latest spec (more of a problem for NoSQL); anyone on your team could open up an old deployment and cause issues. I wonder if there's a general Vercel-recommended way to deal with that...
Comment: Thanks for the answer, but "no need" is wrong.

e.g. what if you commit a version of your app that has a glaring security vulnerability, then that is going to exist on the internet FOREVER. Even though it's pretty unlikely someone will guess the url and then exploit the vulnerability it still makes me uncomfortable.
Comment: @styfle I just realized that one of our apps has hundred (maybe thousands) of preview deployments. I don't think we are getting billed for all this but wouldn't it make sense for Vercel to allow the configuration of a retention policy?
Answer: You can use this in CLI:
<code>vercel rm <APP> --safe
</code>
Comment: @Sebi scans your project and deletes the deployment you specify instead of
e.g. vercel rm yourprojectname-64v3upi73-youruser.vercel.app --safe
Comment: Can you explain what this does?

Vercel old preview deployments


Comparing two double variables Objective-C

Question: double a = 10.123420834;
double b = 100.123412321;

if (a > b) {
// do something here
}

I am trying to compare the two values, the code above doesn't seems to work. Any idea?
Comment: `a` is not greater than `b`, so `// do something here` will never be executed.
Comment: What doesn't work?  Is the "do something here" part executing, even though your example has a < b?
Comment: While we're at it: for true correctness, try to avoid comparing two floating-point variables to each other; rather, try to compare the difference between them to a small 'epsilon' - the smallest amount of acceptable discrepancy between them while they would still be considered equal. `float`s and `double`s have some nuances that make them behave funny in comparisons; it doesn't always work as you'd expect.
Answer: The code is correct.
Note that your snippet is equivalent to
float a = 10.123420834;
float b = 100.123412321;

if (a > b) {
// do something here
}

since Objective C uses double by default unless the number is followed by an f.
Also note that a < b, so the if statement will always evaluate to FALSE. Hence you may want to do
double a = 10.123420834;
double b = 100.123412321;

if (a > b) {
// do something here
} else {
// do something else here
}

to test this properly.
Answer: double a = 10.123420834
double b = 100.123412321

You need to have a semicolon at the end of each of those lines.
Answer: The code in your example is correct. Your problem must be in the "do something here", or elsewhere.


Help in summing up this series involving binomial coefficients?

Question: Find the sum of this series:
$\sum_{r=1}^{19}\left( (-1)^{r-1}\frac{r}{{20\choose r}}\right)$
NOTE: ${20\choose r}$ = $\frac{20!}{(20-r)!r!}$
The final answer is 10/11.
I do have a way to solve this, but i find that to be wayy too tedious and long. Please don't use concepts that are above high school level.
Thanks in advance!
Answer: In general you are dealing with:
$$S_n^{(m)} := \sum_{k=0}^{n} (-1)^k k^m \binom{n}{k}^{-1}$$
We really only want to deal with:
$$S_{n}^{(0)}=(1+(-1)^n)\frac{n+1}{n+2}$$
For $n=20$ and also subtract $2=\binom{20}{0}^{-1}+\binom{20}{20}^{-1}$, and negate the expression, i.e:
$$\sum_{r=1}^{19}(-1)^{r-1}\binom{20}{r}^{-1}=2-S_{20}^{(0)}=2-2\frac{21}{22}=\frac{1}{11}$$
Next:
$$\sum_{r=1}^{19} (-1)^{r-1}r\binom{20}{r}^{-1} = 10\sum_{r=1}^{19}(-1)^{r-1}\binom{20}{r}^{-1}=\frac{10}{11}$$
$r$ was replaced by a constant of $10$ due to the $9$ pairs in the sum (Some all positive, the rest all negative): $$r\binom{20}{r}^{-1}+(20-r)\binom{20}{20-r}^{-1}=10\binom{20}{r}^{-1}+10\binom{20}{20-r}^{-1}$$
And the $10$th is of course the central $-10\binom{20}{10}^{-1}$.


Escutar mensagens com vários clientes(pub/sub)

Question: Se quero poder ter vários usuários e canais, preciso então para cada usuário criar um cliente no redis(ou seja qual for o pub/sub utilizado) para se inscrever no canal? e como faria para receber as mensagens? estou pensando assim, os clientes redis-pub/sub precisariam estar no nível em que está o servidor websocket, pois a comunicação cliente servidor seria apenas por websocket, não sei o que pub/sub utiliza para comunicação, mas estou querendo apenas websocket entre cliente e servidor, e o redis(banco de dados + pub/sub) comunicando localmente dentro do servidor:
'use strict';

//CREATE WEB SERVER
var express = require('express');
var app = express();
var http = require('http').Server(app);
//CREATE WS
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server: http, port: 8080 });
//CREATE REDIS
var redis = require('redis');
var redisClient = redis.createClient({host : 'localhost', port : 6379});

var clients = {};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
         // Aqui dependendo de certa mensagem recebida,
         // como um login por exemplo, eu faria algo assim:
         ws['user'] = obj.login.user.toString();
         //CRIAR UM NOVO CLIENTE REDIS SUBS
        clients[obj.login.user.toString()]['cliRedis'] = redis.createClient({host : 'localhost', port : 6379});
        // SE INSCREVER NO CANAL
        clients[obj.login.user.toString()]['cliRedis'].subscribe();
    });

   if("user" in ws) {
        clients[ws.user]['cliRedis'].on("message", function(channel, message) {
             console.log("Msg on subscriber: " + message);
             //aqui enviaria os dados por websocket para o cliente
        });
   }
});

Up 1:

Com a resposta e comentários do @rodorgas consegui esclarecer bastante o que tenho a fazer. Então cheguei a conclusão que existem duas possibilidades,  para os vários clientes poderem escutar as mensagens enviados pelo sistema pub/sub:
1 - Utilizando o Centrifugo como indicado na resposta do @rodorgas:

2 - Utilizando o redis pub/sub:

Comparações:
A maneira 1 teria quer ter duas conexões websockets ativas, uma para o Centrifugo e outra para o ws-server, pelo menos não encontrei nada na documentação do Centrifugo em que eu possa tratar mensagens que não sejam especificas para o pub/sub, algo como centrifugo-server.on("menssage", então penso que seria mesmo necessário duas conexões websockect nesse modo. Então ambos gastariam praticamente a mesma quantidade de sockets, pois os sockets necessários para a comunicação do redis pub/sub que seriam ganhos utilizando a maneira 1, são perdidos tendo que abrir uma nova conexão para a comunicação com o client-godot. A vantagem da maneira 1 é que parece ser de mais fácil entendimento, pois o client pub/sub está mesmo no cliente, que até nem existe de verdade, porque o Centrifugo apenas requer mensagens por websocket, não existe um cli-Centrifugo como existe um cli-redis, o client-Centrifugo é apenas o client-godot enviando mensagens via websocket. Já a maneira 2 os clientes-redis estariam armazenados dentro de um objeto javascript no script do nodejs. A maneira 1 eu terei que enviar as mensagens no padrão do Centrifugo que são grandinhas comparado ao que posso fazer enviando da maneira 2.
Enfim, estou indeciso de qual modo começar implementar, talvez faça os dois e escolha o que for mais rápido. De qualquer forma estou sem tempo nos próximos dias para começar a trabalhar nisso, então ainda tenho tempo para pensar no que fazer.

Conclusão:

Escolhi implementar com o redis pub/sub, pelo que estudei eu teria mais controle sobre o que estou fazendo. Porém não descartei o Centrifugo, ele me servirá muito bem caso eu venha implementar um chat no jogo, pois ele é muito bom para essa tarefa, com ele tenho como, por exemplo, criar conversas privadas entre apenas dois clientes, entre outras facilidades que já vem implementadas para você utilizar.
Comment: Você quer distribuir as mensagens para pessoas através do navegador? Não sei como o pubsub do redis vai te ajudar nisso, pois não é uma tecnologia web. Seria útil se você quisesse distribuir mensagens para servidores ou aplicativos nativos. No que parece ser o seu caso, só o websocket é suficiente. E talvez você queira usar o `socket.io` ao invés do `ws` (pois o socket.io implementa vários fallbacks).
Comment: acho que não consegui passar o que quero muito bem, as mensagens do pub/sub não iriam diretamente para o cliente, ali chegaria a mensagem e por websocket iria para o cliente, irei até editar.
Comment: O que quero: criar canais que são "pedaços do mapa" e todos os jogadores que estiverem nesse pedaço, ouvirão as mensagens desse canal, minha duvida é se estou fazendo certo acima, criando os clientes e armazenando no script do server. Seria: cliente envia mensagem por websocket para o server, o server salva no banco de dados/cache, cliente entra em um canal onde ficará escutando as mensagens, redis pub/sub envia mensagem buscada no banco de dados/cache, e assim é enviado via websocket para o cliente.
Comment: Em " cliente envia mensagem por websocket", o cliente é o navegador. Em "cliente entra em um canal …", o cliente é o servidor em node-js. Tá confuso. Mas acho que é isso mesmo.
Comment: me desculpe, está mesmo. Sim em "cliente envia mensagem por webscoket" ele é o navegador. E "cliente entra em um canal" ele é o cliente redis que está no servidor mesmo, dentro de `var clients`, e ai é que entra dúvida, tenho mesmo que criar um cliente redis para cada cliente websocket?
Comment: As duas questões. **1 -** Tenho mesmo que criar um cliente redis para cada cliente websocket? se sim, entra a questão **2 -** A maneira(`... clients[ws.user]['cliRedis'].on("message" ...`) como estou escutando as mensagens acima está correta?
Comment: 1. Tem certeza que você precisa de redis/pubsub? Quem vai gerar as mensagens? Você pode enviar mensagens websocket direto do backend, usando várias linguagens. Pelo objetivo que você descreveu, eu não usaria redis não. Dê uma olhada no diagrama do [centrifugo](https://fzambia.gitbooks.io/centrifugal/content/), não é só isso que você precisa? Claro que dá pra fazer usando redis mas parece uma volta em circulos, talvez eu não esteja entendendo sua arquitetura. Quem vai gerar as mensagens? 2. Não tenho experiência com essa biblioteca.
Comment: eu já estou utilizando redis como cache para as informações, o pub/sub seria para os canais, é preciso, se não teria que enviar mensagem de atualização da posição de todos online no servidor para todo mundo, o que seria ruim.
Comment: Tenho o cliente-jogo(pode chamar de navegador) que se conecta ao servidor, quando isso acontece, é criado um cli-redis para ele, o cliente-jogo envia sua posição para o servidor por websocket, então o servidor salva no redis essa informação, o cli-redis se inscreve em um canal que é a área ao redor dele, assim só lhe interessa informações dessa área, evitando informações desnecessárias de serem enviadas. Outro cliente-jogo se conecta na mesma área, cria outro cli-redis para ele, que entrará no mesmo canal, assim cada um recebe a posição do outro, sincronizando suas posições no jogo.
Answer: O Centrifugo é um servidor pubsub, ele "cria canais" no websocket (na verdade é uma camada de abstração, ele cuida dos usuários singulares e permite que você agrupe-os em canais). Isso sem ter o redis como intermediário.
Então vamos supor que seu mapa é dividido em setores. A intenção é entregar uma mensagem para milhares de jogadores que estão no setor (1,1) do mapa. Coloque assim no navegador:

No backend, no lado do servidor. Emita uma mensagem assim (to assumindo backend em nodejs, mas o centrifugo suporta várias linguagens):
Client = require("jscent");

var c = new Client({url: "http://localhost:8000", secret: "secret"});

c.publish("(1,1)", {"input": "test"}, function(err, resp){console.log(err, resp)});

Quando seu jogo estiver enorme e você tiver muitos servidores, você coloca o redis na parada. O Centrifugo usa o redis para fazer load balancing, por exemplo, em situações com alta escala.
Talvez alguém surja com uma ideia usando o redis no meio. Mas eu tô vendo que o redis sempre vai ficar no meio: você vai precisar passar para o navegador depois. O Centrifugo realmente já resolve isso numa tacada só. Eu usaria ele.
Comment: agora entendi, mas não daria para mim usar o Centrifugo, porque o cliente-jogo na verdade não é um navegador, disse "navegador" apenas para ficar mais claro que não era o cliente-redis, então não existiria essa biblioteca Centrifugo, o cliente estou fazendo na godot(game engine), a não ser que eu faça um módulo para o centrifugo, mas como já salvo os dados do cliente no redis, acho que seria muito trabalho fazer um modulo para isso, por isso tive a ideia de utilizar os cli-redis no backend.
Comment: Mas esse godot suporta websockets? Suporta javascript? Você programa nele em que linguagem?
Comment: não, estou tendo que utilizar um modulo para websocket, mas na godot 3 ficarão de implementar webscoket. Não suporta javascript, ela utiliza uma linguagem própria de script chamada GDScript. Eu havia pensado em fazer dessa maneira, colocando os cli-redis no cliente-jogo. Porém teria que criar um módulo para isso também, por isso lidar com os cli-redis no backend.
Comment: Olha o que ele fala aqui "Connections can use pure Websockets protocol" não precisa do centrifuge.js https://fzambia.gitbooks.io/centrifugal/content/server/index.html Se você realmente não quer usar o centrifugo, você basicamente vai acabar reescrevendo algo igual ao que ele já faz. Pelo menos pode olhar no código-fonte e copiar um pouco hehe.
Comment: E desta maneira utilizando o Centrifugo, os dados não estão sendo salvos, o que preciso também, de qualquer forma preciso enviar para um banco de dados primeiro.
Comment: O pubsub do redis não salva nada, anyway
Comment: sim, mas o redis sim, estou enviando informações para o redis cache/persistência, onde busco para enviar para os clientes com o pubsub.
Comment: Você não consegue enviar para o redis e para o centrifugo simultaneamente?
Comment: é isso que pensei agora, e estava digitando kkkkk é o que daria para fazer, e talvez seria mais rápido. Mas teria um problema, as vezes precisaria ir buscar no banco de dados e enviar para o Centrifugo do mesmo jeito, nem tudo estaria sempre acessível na cena do jogo. O projeto tem extrema necessidade de um banco de dados, pois gero tudo por ruídos e as mudanças ficam salvas no redis. Acho que não tem jeito, vai ter que ir no banco de qualquer maneira, por isso escolhi o redis, pelo menos estaria em memória, mas rápido.
Comment: tipo aqui `c.publish("(1,1)",{` onde pegaria a informação para enviar para o canal? é ai que entra o redis banco de dados, porém utilizando o  Centrifugo, eu não precisaria ter o trabalho todo com o redis pub/sub, sockets a menos sendo utilizado, já que o Centrifugo envia via websocket. De qualquer forma o redis estaria lá como cache/bd, mas prefiro mesmo deixar o cliente no cliente. Vou estudar esse Centrifugo, acho que vou usar ele. Funciona como o redis pub/sub para se inscrever/excluir etc nos canais? porque precisaria mudar várias vezes, já que o players se movimentam e mudam de canal.
Comment: o problema de utilizar Centrifugo é que as mensagem que ele envia/recebe são grandes demais. Com pub/sub do redis eu teria controle sobre como criar a mensagem, e reduziria o máximo. Com ele perco esse controle, porque tenho que seguir o padrão dele, mas se não atrapalhar eu não ligo, tenho que testar e ver como vai ser. Acho que vou implementar das duas maneiras, utilizando o redis pub/sub e o Centrifugo, o que ficar melhor eu utilizo.


A Linux USB driver for a generic 2-way comm device

Question: What would be the best existing Linux device driver to use for a generic device that requires 2-way communication (custom protocol)? Preferably bulk transfer, as fairly large blocks will need to be transmitted.
I have considered using mass storage, but I'm unsure if it requires file system handling?
I have also considered modem, but I can't seem to find much information on it (most people who ask are just told that "This is not how you connect to the Internet". Since I'm not going to connect to any "internets" this is rather unhelpful to me). If anyone can point me to some more detailed information on this one, preferably with C or C++ examples, I'd be grateful.
Linux also seems to have a generic serial communications driver, though it does not seem to have bulk transfer? I am also unsure if it provides the speed of the other drivers, since it is apparently targeted at USB->serial converters?
Comment: Just realized that stackoverflow probably isn't the best place to ask this...
Answer: Bulk transfer is the correct choice for large transfers "as fast as the device/PC can handle it".
Well you could get away with just CDC ACM profile. But this has some issues: You need the user to select the correct serial device <code>/dev/ttyACMx</code>.
If you only need to talk to your application, I recommend using libusb. This way you don't need a kernel driver, and you can talk to individual bulk endpoints of your device.
Comment: Making the user select the correct serial device is not a problem, this is a very specific and enclosed system. I'll look further into libusb, though. Thanks
Comment: Just wanted to say that we ended up using the USB->serial port driver. User does not have to select the device, we detect it automatically and then do some handshaking to make sure it's the right one.


Local install of live site looks different

Question: Localhost site looks different than live site.
Drupal 7.37 > 7.5 (Commons), viewed in Chrome on Mac OS X.
Prep Steps:

installed a clone of the website from an outdated repository on my local machine
reconciled the code differences between the live site and the slightly outdated repository site
imported a current copy of the database from the live site.
featurized database configurations
updated most of the modules as well as Drupal core.
checked default theme and settings to make sure they are the same between sites

After noticing the problem:

downloaded theme files into respective locations
installed stage_file_proxy on local dev to load any files I ignored

Thematic Differences
From the moment I imported the database, until now, after all updates have been performed, there is a thematic difference between the live site and my local version. (The difference is slight, but annoying.)

live site is centered and contained, local stretches all the way across in some places but stays left aligned in others
some fonts are larger on local site
navigation menu splits itself to a new line early
live site has blocks on the right, local has one column with blocked content at bottom

Summary of Question
Is this a commonly known problem when certain steps are forgotten and is there another place to address configuration besides in the codebase and the database or is this probably not a theming issue but something else?
Update: I pushed the site up to my remote dev server anyways, to see if the problem was environmental or database and codebase. The remote dev looks perfect. There is definitely an issue with my local dev environment causing this somehow.
Answer: Sounds like some CSS files are not loaded on the local site. Or some additional or other CSS files are loaded on the local site.
Clear caches
First thing to start troubleshooting the local site is to clear the caches. Not only CSS/JS caches but all caches.
If the site has the Advagg caching module installed, then sometimes it is not enough to clear its cache by clicking the Administration menu link. Advagg cache might also need to be cleared by clicking the Flush AdvAgg Cache button on this path:  /admin/config/development/performance/advagg/operations
If the above does not help then on the same Advagg page there are more buttons to click, hidden behind the headings containing 'Clear' and 'Delete'.
Look at CSS with Firebug
Firebug is an addon for Firefox. Instead of this you can also use the browsers built in inspector by pressing F12(maybe another key on Mac).
See what CSS is different and if the CSS is taken from different files on live site vs local site.
Panels Page layout
Having blocks on the right vs bottom could also be affected by Panels Page layout. Check for that if the blocks are still wrong after you got all other thematic right by getting all CSS right.
Comment: Something is definitely wrong with either panels or panalizer but I'm not sure what. I use drush to clear my drupal cache frequently, but also clear my browser cookies. I do not have Advagg installed. I will double check the source code for both sites and see if there are any CSS link differences. But even still, how would there be if I reconciled codebase changes and imported current database?
Comment: Maybe the panels code was hacked by a previous developer and when you updated, a panels layout was not there anymore. Checking the source code for links is good but it shows you what the browser _should see_. If you inspect with Firebug, then you will see what the browser _actually sees_. When inspecting, you see the CSS selectors and also the CSS-file names and URL's they are downloaded from.


How to reload a jQuery element when a button is pressed

Question: I have a button that generates a graph (using Chart.js):
<canvas id="graph"></canvas>

But each time the button is pressed a new graph is created above the old graph. So then I have a lot of graphs. With jQuery I need to delete or empty the graph element and recreate it everytime the button is pressed.
Answer: You can destroy it first like so:
<canvas id="graph"></canvas>


Swift MapView not adding annotation to Map

Question: So for my mapView, I am receiving coordinates from another VC by passing it longitude and latitude through a global array like such:
Adding the latitude and longitude into the array:
var location_one: [String: Any] = ["title": eventName, "latitude": latitude, "longitude": longitude]
    locations.append(location_one)
    if let tbc = self.tabBarReference {
        if let map = tbc.viewControllers?[1] as? MapVC {
            map.loadViewIfNeeded()
            map.add(newLocation:location_one)
        }
     }

Receiving the coordinates on the MapViewVC:
    func add(newLocation location_one:[String:Any]) {
        let momentaryLat = (location_one["latitude"] as! NSString).doubleValue
        let momentaryLong = (location_one["longitude"] as! NSString).doubleValue
        let annotation = MKPointAnnotation()
        annotation.title = location_one["title"] as? String
        annotation.coordinate = CLLocationCoordinate2D(latitude: momentaryLat as CLLocationDegrees, longitude: momentaryLong as CLLocationDegrees)
        map.addAnnotation(annotation)

        //        self.map.centerCoordinate = annotation.coordinate
    }

viewForannotation code:
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let identifier = "pinAnnotation"
    var annotationView = map.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true
    }

    annotationView?.annotation = annotation
    return annotationView
}

The coordinates are properly transferring and the func add is being called upon (verified using a break statement), however when I go to the MapView in the simulator, the annotation isn't being placed. I have no idea what is going on, as this worked properly in another App I tested, but don't have a clue what could cause it to mess up.
I also have code that finds the user's current location and places a pin based on that... perhaps that could mess up the add coordinate code?
Comment: @Rob yeah, your clarification is totally correct and acceptable.
Comment: @Kevin that method is called just when the annotation is about to be displayed over the map. It returns the annotation object the map will later use.
Comment: By any chance did you set the delegate to the map object and implemented the viewForAnnotation method?
Comment: @Rob the momentaryLat and momentaryLong receive the coordinates properly so I think that part is good. I have edited my question to include the viewForAnnotation. My app worked properly with displaying the current location's annotation so I'm not sure if I properly implemented it or not.
Comment: @apineda yep I set, self.map.delegate = self in my viewDidLoad(). Also, I've edited my question to include my viewForAnnotation method, however, I am not sure if I've implemented it properly.
Comment: So, I'd add a breakpoint in `viewFor` and examine the `annotation`. That kills two birds with one stone, (a) making sure you're reaching this bit of code correctly; and (b) that the annotation contains what you think it should.
Comment: @Rob I inserted a breakpoint in the viewFor. May I ask when this method is called? It didn't break until I switched the VC to the mapView in the simulator. I do not know much about viewForAnnotation method so I'm not sure if it is properly called on after I transfer the coordinates.
Comment: @apineda - "It returns the annotation object the map will later use" ... not to split hairs, but it returns the annotation _view_ object, not the annotation object, which is different. I know you know that, but for folks not familiar with the distinction, it can be a source of confusion.
Comment: @Rob Ah I see. Could it be that the coordinate is not being placed because it is not on the visible portion of the map? My code has centered the view of the map on the user's current location and the coordinate I have been using is New York, which I need to zoom out to see whether an annotation was placed or not. Am I interpreting that correctly? Is the visible portion of the map the whole map or only the screen that is loaded on the simulator?
Comment: @Rob Great explanation, I understand now thanks. Also I revisited what you mentioned about the momentaryLat and momentaryLong being 0.0. I previously thought you meant something else, but when I printed the values to the console they did print out 0.0! You mentioned this to be a parsing issue.. could you explain further what may be up?
Comment: @Rob Hmm, I am not familiar with what raw JSON is and I don't think I am using JSON in my code. To help clarify my situation, I have the user input an address and I use a reverse geocoder to change the address into coordinates in my first VC. This process works, and then I transfer these coordinates into the MapView VC through the array. I did a similar idea in another project where I had the user input the coordinates into the first VC and then I transferred them to the MapView. This worked fine.. so perhaps it could be an issue with the reverse geocoder?
Comment: Sorry for introducing the JSON confusion. Just look at what `location_one["latitude"]` and `location_one["longitude"]` are before you convert them to doubles. Maybe there's some extraneous stuff in those strings. Maybe they're empty strings because this array wasn't populated correctly. Break the assignment of `momentaryLat` and `momentaryLong` into smaller steps and look at the values at each step of the process and the problem will likely jump out at you.
Answer: I'd suggest double checking the numeric values of momentaryLat and momentaryLong, because it's possible that due to parsing problems, they're not what you think they are (e.g. make sure they're not 0.0, in the Atlantic Ocean!). We'd have to see what location_one["latitude"] values were before you converted it to NSString and extracted the double value from that. Break it down into separate steps, and the problem will likely jump out at you.

Your viewFor looks fine. Unrelated, I'd suggest putting the annotationView?.annotation = annotation inside the else clause of the preceding if statement (no need to set the annotation if you just created the MKPinAnnotationView using that same annotation ... you only need to do this if reusing the annotation view). And I'd also generally check to make sure the annotation is not the MKUserLocation because we generally let the map view render that for us.
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation { return nil }   // let the OS show user locations itself

    let identifier = "pinAnnotation"
    var annotationView = map.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView

    if annotationView == nil {
        annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        annotationView?.canShowCallout = true
    } else {
        annotationView?.annotation = annotation
    }

    return annotationView
}

But neither of those two observations have anything to do with your issue of the missing annotation.

Remember, the viewForAnnotation (or viewFor in Swift 3) method is only called when one or more of the map's annotations has a coordinate that falls within the visible portion of the map and it therefore concludes that it needs to render the associated annotation views. So, one would not expect it to be called until (a) the map tries to draw itself and (b) one or more of the annotations have coordinates within (or near) the visible portion of the map.
For example, if you have 100 annotations added to the map object, of which only 10 fall within the visible portion of the map, only 10 annotation views will be created. And if you scroll the map such that 5 fall out of view and 7 more scroll into view, it call viewForAnnotation 7 more times, once for each newly visible annotation. The viewForAnnotation will likely successfully dequeue/reuse the 5 annotation views that scrolled out of view and and will only create new annotation views for the two additional ones. (It's more complicated than that, but that's the basic idea.)
It's analogous to table/collection views, where cells are created only for the visible cells. So, if you have 100 objects in your model, but only 12 rows are visible in a table, you'll create 12 cells only. And as a row scrolls out of view, it becomes available for dequeue/reuse for future rows that scroll into view. It's a common pattern that you'll see throughout iOS, where computationally-expensive view objects are only created as needed, and reused wherever possible.
Comment: I was just suggesting that you add a breakpoint in `viewFor` and print the `annotation` (or, the `coordinate` property of that `annotation`). It doesn't make sense that `viewFor` is getting called for your annotations (not just the `MKUserLocation`), but you're not seeing the pin on the map. The only thing that would account for that would be if you have multiple map view objects floating about (e.g. the one that you added in IB and another you instantiated programmatically). But first, let's make sure you're seeing `viewFor` called for the annotation you added to the map.
Comment: breaking it down has helped a little! I realized that my code for putting the coordinates in my array wasn't in the right spot. Now after running it, the output for location_one["latitude"] is Optional("40.713054"), and momentary latitude is outputting 40.713054; however it is still not placing an annotation at the location.
Comment: OK, so you have the debugging skills to figure this out. Look at the `coordinate` value of the annotation object right before you add it to the map's array of `annotations`. Look at it in `viewFor`. Is the annotation just not in the right spot or is it not getting added at all for some reason?
Comment: I understand what the viewFor method does, but I'm having trouble understanding each line of code inside. I'm not quite sure what you mean to look for the coordinate value of the annotation in viewFor. The annotation before added to the array is: CLLocationCoordinate2D(latitude: 40.713054, longitude: -74.007). And the annotation is not being placed at all.
Comment: Ah ok. When I tried printing the annotation in the viewFor, nothing shows up, while in my function add, which receives the array coordinates, is able to print out the annotation. My other app that works in placing the annotation prints the annotation in the viewFor. So the issue is that the annotation is not passing through the viewFor. What could be the cause of this?


What are the new "for", "at", "in" keywords in Swift3 function declarations?

Question: I'm working through a beginners' tutorial on Swift that is written in Swift 2.
It contains code like (random example)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

This has changed in Swift 3 (I'm using XCode 8 Beta), and the IDE helpfully converts this to the new (beautiful!) notation:
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {

What confuses me here is the  "for" in "for segue:". I get why it's there, but what kind of an element is it syntactically? Is the parameter named for,  for segue, or segue?
Is it mere decoration - an element with no meaning but to help the developer understand the context? Does it do anything else? Does the concept have a name? Can I use it in my own methods?
I see the same happening with "in" and "at".
Comment: It was called "external parameter name" in Swift <= 2, and is called "argument label" in Swift 3: http://stackoverflow.com/questions/38410889/changes-in-terminology-for-swift-function-parameter-labels, https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID166.
Comment: syntax mistake? should be forSegue:, parameter label
Comment: @ShadowOf nope, it seems to be the new [Swift 3 way](https://www.hackingwithswift.com/swift3)
Comment: @El I get that, but what is it syntactically? Is the parameter named `for segue` or `segue` in the method? If it's `segue`, the `for` has to be defined somehow.
Answer: The syntax allow you to label arguments twice - once for use within the function (the parameter name) and once for use when calling (the argument label). By default these two will be the same (like with sender in your example), but they differ when it makes a function more readable at the call site:
prepare(for: aSegue, sender: something)

being more readable-as-a-sentence than:
prepare(segue: aSegue, sender: something)

Which sounds like you're preparing the segue, not preparing for the segue.
for would be a dreadful name to use internally in the function to refer to the segue, so you can use a different one if you require.
The idea is to meet the sometimes conflicting goals of readability at the call site and sensible naming in the implementation.
When defining a function, if you are going to use separate argument labels and parameter names, you specify the argument label first, and the parameter name second:
func sayHello(to name: String) {
    print("Hello " + name)
}

sayHello(to: "Pekka")

to only has relevance when calling the function. name is used inside the function.
Answer: Those for and at are not reserved keywords in swift's parameter function, They are Argument Labels that you can freely define which makes more sense to users of your function
Syntax
func prepare([ARGUMENT LABEL][PARAMETER NAME]: String) {}

Function Definition
func prepare(for segue: UIStoryboardSegue) {
   print(segue) //what your function scope knows
   // print(for) won't work, it's a label for function usage readability
}

Function call
prepare(for: mySegue) //with argument label
prepare(segue: mySegue) //without argument label


ATTR passando _blank

Question: O código abaixo redireciona para outra pagina, porém gostaria que fosse em outra aba do navegador, por isso usei o _blank. más não vai para outra aba.
Alguém poderia me falar onde estou errando? Obrigado pessoal.

ATTR passando _blank


Maximum of a utility function

Question: I was practising some related rates problems and I came across this particularly difficult question. The question goes like this:
Suppose Peyam's utility function is given by:
$U(\theta)=\frac{\mu C}{\mu\sin(\theta)\;+\;\cos(\theta)}$
where C is a universal cake-constant and $\mu$ is the intensity of happiness.
Note: Think of $\theta$ here as the time of the year. So $\theta=0$ corresponds to the beginning of January 1st, and $\theta=2\pi$ corresponds to the end of December 31st.
Show that Peyam is happiest precisely when $\tan(\theta)=\mu$.
I believe what is being asked for is the value of the maximum value of $\mu$, which should be equal to $\tan(\theta)$
I tried by making $\mu$ the subject, and ended up with
$\mu=\frac{U(\theta)\cos(\theta)}{C-U(\theta)\sin(\theta)}$
I'm guessing the next thing to do is to differentiate, but I'm not exactly sure how to differentiate $U(\theta)$. Do I substitute back in the original equation for $U(\theta)$? How can I move on from here?
Comment: This would be an extremization problem, rather than a related-rates calculation: for what value(s) of $ \ \theta \ $ is the derivative of $ \ U \ $ equal to zero? As it stands,  $ \ \mu \ $ can be "canceled out" from this ratio.  _Is it_ a constant?  Is it supposed to be in _all_ of the terms in _both_ the numerator and denominator?
Comment: You're new so I hope you'll learn this:  Always write an *INFORMATIVE* title... one that relates to the specifics of your problem.
Comment: You should also show what you've tried yourself on this problem; otherwise, this post will likely be closed.  This is not an "answers-on-request" site.
Comment: @boojum sorry I added an extra mu in the denominator, I've made an edit now
Comment: @DavidG.Stork, thanks for understanding, I only recently discovered stack exchange. I hear the guidelines on posts here are pretty strict. What should the title look like? I'd appreciate it if you could help so I don't make this mistake in the future
Comment: @boojum wouldn't that give you the maximum for U(θ)? I believe they were asking the max value for μ
Answer: It looks like we want to treat the "utility" as a number $ \ 0 \ < \ U \ < \ 1 \ $ in order to keep the ratio defined "everywhere". [Graph the curve $ \ \frac{y}{y·\sin(x) \ + \ \cos(x)}   $ equal to a constant and vary the constant's  value  to see this.]  There is then a "family" of such utility functions which have maxima in the specified interval for $ \ \theta \ . $
Since $ \ \mu \ $ is  a variable in addition to $ \ \theta \ , \ $ it will help to write the relation as
$$ U·(\mu \sin \theta \ + \ \cos \theta) \ \  = \ \ \mu · C \ \ , $$
which we would differentiate implicitly with respect to $ \ \theta \ \ , $ thus
$$ \frac{d}{d \theta} \ [ \ U · (\mu · \sin \theta \ + \  \cos \theta)  \ ] \ \  = \ \ \frac{d}{d \theta} \ [ \ \mu · C \ ]    $$
$$ \Rightarrow \ \ U · \left( \frac{d \mu}{d \theta} · \sin \theta \ + \mu·\cos \theta \ - \  \sin \theta \right) \ \ = \  \ C  ·  \frac{d \mu}{d \theta}  $$
$$ \Rightarrow \ \   \frac{d \mu}{d \theta} · (C \ - \ U · \sin \theta) \ \ = \ \ U ·  (  \mu·\cos \theta \ - \  \sin \theta  ) \ \ . $$
Since we want the maximal value for $ \ \mu \  $ in any particular utility function, we would set $ \  \frac{d \mu}{d \theta} \ = \ 0 \ \ $ and the result for $ \ \mu \ $ follows.  So this is sort of a "related-rates" problem...
Answer: No need to make $\mu$ a subject.
You take derivative of the utility function and equate to zero:
$$U'(\theta)=\left[\frac{\mu C}{\mu\sin(\theta)\;+\;\cos(\theta)}\right]'=-\frac{\mu C\cdot [\mu \cos(\theta)-\sin(\theta)]}{\mu \sin(\theta)+\cos(\theta)}=0 $$
Can you finish it yourself?

Maximum of a utility function


Badminton, double hit by one player, new rules?

Question: What are the rules that apply when a player makes a double hit ?
Answer: There is a foul if the player hits the shuttlecock twice in row, except in the case it touches the racket head and the strings in the same shot.

13.3.8 is hit twice in succession by the same player. However, a shuttle hitting the head and the stringed area of the racket in one
  stroke shall not be a "fault";

Source (in French, sorry : http://www.badminton-web.fr/badminton/regles-badminton.php)
Comment: Maybe they include all the body (except the strings) and not just the racket head...
But I jusk looked at the official rules and this is a foul : `13.3.8 is hit twice in succession by the same player. However, a shuttle hitting the head and the stringed area of the racket in one stroke shall not be a "fault";`
And the head is connected to the shaft by the throat, so it's not the same thing... Thus, definitely a foul.
Comment: Thank you for your answer. I have an additional question, namely: what if the player hits the shuttlecock firstly by throat or shaft and then by the stringed area?
Comment: I think this is a foul.
Comment: But you are not sure, right?
Comment: The exception I pointed out in the only one I found, so I'm not 100% sure but logically, this is a foul.
Comment: I met some players, who are claiming that it is not a foul. This is the reason why I am asking about details.
Comment: OK, let's wait and see, maybe answers will be added.
Comment: it's definitely a fault. let your players read the rules :)
Comment: Updated link to the regulations: https://system.bwfbadminton.com/documents/folder_1_81/Regulations/Laws/Part%20II%20Section%201A%20-%20Laws%20of%20Badminton%20-%20June%202016%20Revised%202.pdf
Answer: According the official LAWS OF BADMINTON, set by the Badminton World Federation, chapter 13 is affected: FAULTS. Here the different situations are outlined when it is considered a 'fault' and in paragraph 13.3.8 the following about that is mentioned:

13. FAULTS
It shall be a 'fault':
...

13.3 If in play, the shuttle:

...
13.3.8 is hit twice in succession by the same player. However, a shuttle hitting the head and the stringed area of the racket in one stroke shall not be a 'fault'.


Castle Windsor config pointing to connectionStrings section in web.config

Question: I want to inject a connection string into my repository but ideally, I want this connection string to be in my web.config connectionStrings section rather than in my windsor config. Is this possible?
I know I can use the fluent interface and achieve this easily but my bosses want an xml config file.
I also know that I can define a property and use that in my windsor config to pass the parameter in, but I have other code that reads the connectionstring from the web.config directly and do not really want two places with the same connectionString.
Answer: There are several ways to do this:

This question has a solution that's very similar to what you want
You can tag the classes that need the connectionstring with an interface like this:
interface IRequiresConnectionString {
    string ConnectionString {get;set;}
}

then you subscribe to the event container.Kernel.ComponentModelCreated (or write a IContributeComponentModelConstruction), inspect the component implementation type and if it implements IRequiresConnectionString you put the connectionString in the component's parameters.
You can also do the above without the interface if you follow the convention that the connectionstring parameter will always be called connectionString (or whatever you like) but this is error-prone, if you accidentally name your parameter conectionString it would not get injected.
Comment: I would actually use `IContributeComponentModelConstruction` and convention to name the parameter 'connectionString' and write a unit test to verify I didn't screw that one up :)


Qual a diferença entre match_parent e fill_parent?

Question: Quando estou editando o layout xml sempre fico confuso ao escolher entre o  match_parent e o fill_parent, e acabo por sempre achar que estou fazendo tudo de forma errada por não saber o que são cada um deles ou se são iguais.
Alguém poderia explicar qual a funcionalidade de cada um?
Answer: Qual a diferença entre match_parent e fill_parent ?
Eles são a mesma coisa (no Nível API 8+).
Sim, MATCH_PARENT e FILL_PARENT são apenas diferentes nomes de constantes para o mesmo valor inteiro (-1 se você está curioso) usado para especificar o modo de layout de um View dentro de seu parent.
O fill_parent foi renomeado para match_parent pois o problema com o antigo nome  era que implicava a afetar as dimensões do parent, enquanto match_parent melhor descrevia o comportamento resultante - correspondendo a dimensão com o parent.
Qual a função do match_parent ?
A função do match_parent é de dar um valor especial para o height ou o width solicitado por um View.
Use match_parent pois não há diferença caso você esteja em versões do API 8+,e já que celulares => Android 2.2 é aconselhável usar match_parent,mas por questão de compatibilidade para versões anteriores ainda existe fill_parent.

OBS : Em versões do Android API do 1.6 á 2.1 é aconselhável usar fill_parent pois usando match_parent nestas versões ocorrem certos erros,então nestas versões de API use fill_parent.

Segundo a própria documentação oficial do Android,ele especifica que são a mesma coisa e que não há diferença em usar um ou outro.
https://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html
Comment: Agradeço a explicação detalhada, acho que vou ter de fazer muitas mudanças então, agora, no caminho certo. =)
Answer: O fill_parent não é mais usado, ele está obsoleto.
Foi substituido pelo match_parent, você até pode usar o fill_parent, mas pode acontecer alguns "defeitos" na aplicação.
Então é melhor usar o atual mesmo que é o macth_parent.
Answer: Basicamente, nenhuma. Os dois são a mesma coisa.
Link da documentação aqui
fill_parent foi renomeado para match_parent na API 8 e maiores. Tente usar sempre match_parent
Answer: Na prática, não há diferença.
match_parent substituiu fill_parent a partir da API Level 8.
Veja a documentação do Android:


If $A-I$ is positive definite matrix

Question: It is known that if a matrix $A$ is positive definite (i.e., $A>0$) then it will be invertible. What about the following:
If $A-I$ is positive definite then $A$ is invertible. Is this true?
Comment: $A-I$ positive definite  implies $(A-I)+I=A$ is, too.
Comment: Eigenvalues of $A$ are shifted $+1$ with reference to   $A-I$.
Answer: As mentioned by @kimchilover in the comment, if $A-I>0$ then so $A$, since:
$$A=(A-I)+I>0.$$
Answer: The reason why $A-I$ being positive-definite implies that $A$ is positive definite is because the set of positive-definite matrices is a convex set.  Hence whenever $A$ and $B$ are positive definite, then $A+B$ will be as well.  The convexity however doesn't guarantee that subtracting positive definite matrices will yield another positive definite matrix (though it will be symmetric at the very least).

If $A-I$ is positive definite matrix


Android : How to refresh the state of whole activity after the user login and a session is maintained

Question: i have certain screens which allow user to comment , reply and view certain other features . Even the Navigation drawer is designed to get itself updated once the user login to the application .
My problem is i dont know about any good approach how to refresh the whole activity stack once the user Logins  and a session is created for him/her .
Some screens shows comment edittext boxes , these boxes are only visible if the user log in, Is their any way so that, if the user tries to login from any screen and gets back  after complete login session the comment box appears quick and the drawer also gets updated automatically .
Do i have to make some listener and call refresh on each activity in the stack or to kill all back-stack and re direct user to a new main activity and their after.
Can any one please get me know of some good approach i must use !
Comment: A -> B -> C -> Login
in some case A -> D -> F -> Login
in other case A -> E -> G -> Login

For now am Clear all back Stack and move the User with new A

What i want is User After login Sets back to C / F / G  and refresh all activity which uses the Session to create some Screen , To be more clear assume that Activity  B is to show user profile pic after login, i want to refresh all stack activity which uses session details and refresh it after login rather then just deleting all back stack and moving to a new A

What will be the best approach !
Answer: I would broadcast an intent with your own custom action when the user logs in then listen for this event in an activities\fragments which are interested though a BroadcastReceiver
https://developer.android.com/reference/android/content/BroadcastReceiver.html
For broadcasting the login intent:
https://developer.android.com/reference/android/content/Context.html#sendBroadcast(android.content.Intent)
You'll then need to refresh any UI elements when the activities resume.
I guess you could kill all activities on login but seems like a poor user experience.
Comment: Please see my comment in top i have added , may be the picture will get more clear
Comment: I think Changing the backstack when the user logs in would lead to a very confusing user experience - if I'm reading your intentions correctly. I would stick with returning to acitvity A
Comment: Yeah, am doing the same for right now ! Let me know if theirs any more of information you could suggest any time.

Thankx man for the help .
Answer: Try to use
finish();
startActivity(getIntent());

Comment: Please see my comment in top i have added , may be the picture will get more clear
Answer: You can just re-launch the activity after a successful login. Or, if you are using a separate a different activity for user login, then you can launch the particular activity in whichever you want to get re-directed to. And, that activity will be re-initialized.
If you are worried about persistence factor of user data or, some other user state at that particular moment, you can use saveInstanceState and then sync from it after re-initializing the activity. But, this time the activity will(may) contain some of the logged-in user's information like profile pic, name, gender -etc.

Option 1

For refreshing the current activity, you can use this below code snippet-
public void refreshActivity (View v){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Option 2

You can save your current activity state-
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

So, you can save your instance state by putting some information as key-value pair relevant to your activity. Then revert it back from the same saved data.
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

I am putting the original answer's
link for your reference. Hope this solves the issue for you.
Comment: Please see my comment in top i have added , may be the picture will get more clear
Comment: I understood your requirement. You not only want to refresh the state of the current activity but instead of going back to main activity(A), you want to update the state of all the activity in your activity call stack.

Well, I don't know the exact solution to this. But, there is a way in which you can update the current activity and make sure that after pressing the **back** button, you get back to the **main activity** and it's get refreshed.

please go to this [link](http://www.tutorialspoint.com/android/android_session_management.htm) if you want to know more on this.
Comment: Okey , i went through the link i am already using the session Concept !
Thanks for the efforts! Need to figure some better move ! Thanx man
Answer: You can use this.recreate() on restart, like this:
 @Override
protected void onRestart() {
    this.recreate();
    super.onRestart();
}


Trace-class, Hilbert Schmidt operators, $L^p(H)$: duality theorems

Question: Let $H$ be a Hilbert space, separable if necessary, and let $tr$ be the usual trace on $L^1(H)$. It is classical theory that $K(H)^*=L^1(H)$, and $L^1(H)^*=B(H)$, via the canonical application $\langle T,S\rangle=tr(TS)$ for suitable $T$ and $S$.
It is often mentioned that these duality results are analogous to the well-known $c_0^*=\ell_1$ and $\ell_1^*=\ell_\infty$. I think I more or less understand how this analogy works: The operator norm in $B(H)$ is the uniform norm when we restrict the maps to the unit ball, so $B(H)$ consists of the maps with finite "uniform norm", $K(H)$ consists of the elements which can be approximated by finite rank ones, and these are clear analogues of $\ell_\infty$ and $c_0$, respectively. I see more or less the analogy between $L^1(H)$ and $\ell_1$: identify the $i$-th element of a fixed basis for $H$ with the $i$-coordinate function in $\ell^1$, but I don't really see, precisely, how $\langle T\xi_i,\xi_i\rangle$ relates with $x_i$, for $T\in L^1(H)$ and $x=(x_i)\in\ell_1$.
My question is what is the precise relation between these two duality results. More precisely,

Question 1: Can we obtain the duality results $c_0^*=\ell_1$ and $\ell_1^*=\ell_\infty$ from $K(H)^*=L^1(H)$ and $L^1(H)^*=B(H)$? What if we consider a measure/probability space $(X,\mu)$ instead of $\mathbb{N}$ with counting measure (although $c_0$ has no analogue in this case).

More generaly, we might define $L^p(H)$ to consist of those $T\in B(H)$ for which the "norm" $\Vert T\Vert_p=(\Vert |T|^p\Vert_1)^{1/p}$ is finite. I'm not sure if this is indeed a complete norm, but if we assume so, it is natural to ask:

Question 2: Let $p$ and $q$ be (finite) Hölder conjugates. Are $L^p(H)$ and $L^q(H)$ duals of each other (with the usual application $\langle T,S\rangle=tr(TS)$), and does this indeed generalize the duality of $\ell^p$ and $\ell^q$? Moreover, is the map $p\mapsto\Vert T\Vert_p$ continuous in some sense and does $\Vert T\Vert_p$ converges to $\Vert T\Vert$ as $p\to \infty$ for $T\in \cap_p L^p(H)$?

I'm interested in these questions to understand better how tracial von Neumann algebras/$II_1$ factors are related to probability spaces, and the importance of the Hilbert-Schmidt norm on such algebras.
Answer: Most of your question is answered by Theorem 3.2 in Simon's Trace Ideals and Their Applications. It is not an easy read because of the awkward notation, but it is worth it.
Yes, $L^q(H)$ is the dual of $L^p(H)$, basically because Hölder holds, $|\text{Tr}(TS)|\leq\|T\|_p\|S\|_q$. I cannot say that the dualities in the sequence spaces follow from the dualities in $B(H)$, but you'll find (the first half of) Chapter 2 in Simon's book interesting, where Lidskii's results are developed. I have no idea about going from $\mathbb N$ to $X$.
The convergence of the $p$-norms follows in a rather obvious way from $\|T\|=\mu_1(T)$ and
$$
\|T\|_p=\left(\sum_{k=1}^\infty\mu_k(T)^p\right)^{1/p}
$$
(where $\mu_k(T)$ are the singular values of $T$) with the same proof as in the discrete measure case.