$E[X|\mathcal{Q}] \leq \liminf_nE [X_n\mid\mathcal{Q}]$

Question: If $(X_n)_n$ is a sequence of nonnegative random variables and $\mathcal{Q}$ is a sub $\sigma$-algebra, then the conditional Fatou lemma holds almost surely,  $$E[\liminf_n X_n\mid\mathcal{Q}] \leq \liminf_n E[X_n\mid\mathcal{Q}].$$
Let's say that $(X_n)_n$ converges in probability to $X$. Is it true that, almost surely, $$E[X\mid\mathcal{Q}] \leq \liminf_nE [X_n\mid\mathcal{Q}] \text{ ?}$$
Comment: @Kaind "Almost surely" commonly means "with probability 1".
Comment: May I ask if the term "almost surely" here has a rigorous mathematical definition, or is used in plain English sense?
Comment: @BrianMoehring What is begging the question and answering the wrong question here? You give no comment and you still downvote. Show me where is the error in my argument?
Comment: @BrianMoehring I was modifying "As $X = \lim X_n$ then $\liminf X_n$ exists, hence $\liminf X_n = \lim X_n = X$. So, the hypothese that you said we didn't have, in fact, you have it.
Source: https://math.stackexchange.com/q/122755/195378
Comment: @NN2 The only thing I can say is that if we only have $X = \operatorname{plim} X_n$ and not $X = \lim X_n$, then we may even assume $\liminf X_n \neq \limsup X_n$ almost surely, so there's no way to make the argument valid that you're trying to make.
Answer: This is false.
For an easy counterexample, let $X_n\geq 0$ be any sequence of random variables with $\liminf_n X_n = 0$ which converges to $X = 1$ in probability.  Then let $\mathcal{Q}$ be large enough so that the $X_n$ are $\mathcal{Q}$-measurable.  The inequality in question then becomes $X \leq \liminf_n X_n,$ which is false almost surely.
For instance, this is the case when $X_n$ is any sequence of independent random variables supported in $\{0,1\}$ such that $P(X_n = 0) \to 0$ but $\sum P(X_n = 0) = \infty$.
Comment: Do note that the inequality is true in at least certain cases, such as when $\mathcal{Q} = \{0, \Omega\}$ or more generally when $\mathcal{Q}$ is generated by a partition of $\Omega$.  I can't give a fine condition on $\mathcal{Q}$ for it to be true, but it's apparently false when $\mathcal{Q}$ is large enough.
Comment: We can always find an example on $([0,1],\mathcal{B}([0,1]),\lambda)$ such that $X_n$ converges in measure to $1$, and take $\mathcal{Q}=\mathcal{B}([0,1])$ (large enough)


Symfony 2.7 choice_attr with EntityType field

Question: I need to add an additional HTML attribute to each choice of an EntityType field in Symfony 2.7.
Following this guide, I assume that EntityType inherits this feature from ChoiceType. I tried something like the following, but without effect; no mytype attribute gets added to the rendered select options.
$builder->add('customer_email', 'email')
        ->add('Product', 'entity', array(
              'class' => 'MyBundle:Product',
              'property' => 'name',
              'empty_value' => 'None',
              'required' => false,
              'choice_attr' => function ($val, $key, $index) {
                  return array('mytype' => $val->getType());
              }))

Comment: your choice options elements don't have attribute "mytype"?
Comment: that's right. sorry, got this wrong in the question; edited it.
Answer: This is not necessarily the best answer, but I can't post comments yet.
When implementing choice_attr, choice_labels etc... on ChoiceType and EntityType, it seems like choice_attr was left behind on the latter, there are a few comments about it on github, I personally need the same feature, hopefully it'll be implemented.
https://github.com/symfony/symfony/issues/4067
P.S.: Investigated further, it is indeed inherited from ChoiceType, and it only appears in the 2.7 documentation, if you write something like
'choice_attr' => function (Product $product, $key, $index) {
    return ['class' => $product->getType() ];
}

You should get the class attribute set correctly, for custom attributes I am not sure, you might need to use 'attr' => 'foo'.
P.P.S.: Tested 'foo' =>'bar' and it works, no need to nest inside 'attr'.
Comment: OMG! Where did you find this in docs? I've spend hours searching for this in docs. Thnkx!!!


Firewall to Load Balancer throughput

Question: I have a theory question for you networking guru's if wouldn't mind answering :). Let's say I have a Cisco ASA 5510 who's cleartext throughput is 300Mbps and sitting behind that I have Citrix MPX 5650 who's throughput is 1Gbps - everything is connected to a 1Gbps Access swich. Will my load-balancer ever get to push 1Gbps of throughput if my FW only supports 300Mbps, but I'm on 1Gb access switches? The ASA has a 1Gb Interface, so I'm curious why have 1Gb interface if you can only process 300Mbps of throughput?
Firewall > Load Balancer > Web Servers

Answer: can't really run 300Mbps throughput over a 100Mbps connection :P
Also, you are limited to the weakest link (least throughput) when establishing a connection.
Say you have the following (this is for teaching not really real life):
      Host1   Host2
          /    \
      10mbps   100mbps
          \    /
            R1
            |
          1000mbps
            |
          Host3

List showing communications and max throughput

Host3 and Host1 = 10mbps
Host3 and Host2 = 100mbps
Host3 and R1 = 1000mbps
Host2 and Host1 = 10mbps
R1 and Host1 = 10mbps
R1 and Host2 = 100mpbs

So to answer your question, if the the application/server that is being accessed by the hosts has to go through the ASA, then yes the max throughput you'll get is 300mpbs.
Comment: +1 for Nice diagram :). I'm not concerned with the host/server speed since it's all 1Gb. I'm more curious about the ASA to load-balancer
Comment: If the throughput is only 300mbps max and your links are Gigabit, then your throughput will only be 300mpbs max.

Firewall to Load Balancer throughput


How to change Macro value in VC++ project

Question: I migrated one VC++ project from VS2008 to VS2010, and some Macro value was changed. I want to change the value(e.g. $(TargetName)) back to match what I have in VS2008.
Any idea how to do it?
Answer: If you right-click on the Project name in Solution Explorer, the first page (Configuration Properties \ General) has the Target Name definition.
Comment: @Jess: I tried that w/o luck. I changed value for "Target Name" on the first page and saved the config, but I checked $(TargetName) not changing. I assume $(TargetName) and "Target Name" should match.
Comment: Where are you looking for $(TargetName)?  This value will be used by VS when compiling your code (typcially its the base filename for your .obj / .exe files).  Note, there are independent values for Debug, Release and other Configurations -- and also, it is only known to VS, it won't be available as a "blanket" environment variable.
Comment: @Jess: Thank you for your reply. After I change and save new value of "Target Name", then open configuration window again, select one of fields to edit, you would get the Macro list here. I see $(TargetName) value not changed.
Comment: The other fields are using this value (whatever you set ($TargetName) as part of their value.  You are actually changing ALL the objects that use ($TargetName) when you change that parameter -- its a macro to be used in other fields.  If you want to change specific fields, just edit them individually.
Comment: Do you have write-access to the project/solution file?


Splitting group of $2n$ to couples.

Question: There are $n$ boys and $n$ girls in a class.I'm trying to figure out how many possibilities are there to split them into couples of boy and girl. For example, if there are  $2$ boys(A and B) and $2$ girls(C and D) in the class, we could split them:
A with C, B with D or A with D, B with C. We need to split the whole class.What I was trying to do is to calculate how many ways are there to split into 2's couples(not necessarily boy and girl) in a $2n$ group of students, and then divide by the number of ways to order $2n$ boys and girls in a line where a boy can't sit next to a boy and a girl can't sit next to a girl, but it didn't turn well.
I would love some directions. I do know the final answer is $n!$.
Comment: In how many ways can you choose a partner for the first boy?  Once you've made that choice, how many are left for the second boy?  Continue in this fashion.
Comment: Well, $n$ partners for the first, $(n-1)$ partners for the second.. but, shouldn't I first choose the $n$ boys from the $2n$ students?
Answer:
In how many ways can $n$ boys and $n$ girls be split into $n$ male/female couples?

Line up the boys in some order, say alphabetically.  We now match girls to boys.  We have $n$ choices for which girl to match to the first boy in line.  For each such choice, we are left with $n - 1$ choices for which remaining of the remaining girls is matched with the second boy in line.  Continuing in this way, we see that there are $n - 2$ choices for which girl is matched with the third boy in line.  In general, there are $n - (k - 1) = n - k + 1$ choices for which girl is matched to the $k$th boy in line. Continue until there is only one girl left to match the last boy in line.  Hence, there are $n!$ ways to form male/female couples.

In how many ways can $2n$ students be split into $n$ pairs?

Line up the students in some order, say alphabetically.  There are $2n - 1$ choices of which student is matched to the first student in line.  Remove those two students from the line.  There are $2n - 2$ students left in the line.  There are $2n - 3$ choices of which student is matched to the first student remaining in line.  Continuing in this way, we see that there are $2n - 5$ choices for which student is matched to the first student remaining in the line after the first two pairs have been removed.  At the final step, after $n - 1$ pairs of students have been removed from the line, there is only one choice for matching a student with the first student remaining in the line.  Thus, there are
$$(2n - 1)(2n - 3)(2n - 5) \cdots 5 \cdot 3 \cdot 1$$
ways to form $n$ pairs of students from $2n$ available students.
Comment: I'm though choosing $n$ boys from $2n$ students. Doesn't that mean that I need to multiply the answe by $\binom{2n}{n}$?
Comment: No.  There are only $n$ boys.  There is only one way to choose all $n$ of them.  Take the $n$ boys as given.  What we are choosing is which girl to match with which boy.  We start with $n$ choices.  Once a girl has been matched with a girl, we are left with $n - 1$ choices for the next match, and so forth.

Splitting group of $2n$ to couples.


Suspending a pitcher for misconduct

Question: For an everyday player the standard 5 game suspension for misconduct certainly hurts both the player and the team as a whole. Whereas, the same standard 5 game suspension for pitcher doesn't even result in a pitcher missing a start (next game).
Why are MLB pitchers suspended with the same standard procedures as everyday position players?
Answer: In baseball, any player can play any position (unlike, say, rugby where certain positions can only be played by designated players). This is why it has been possible for a single player to play every single baseball position in a single game. There is nothing stopping a team playing their normal catcher as a pitcher or a starting pitcher in any other position.
I think that MLB suspensions are equal for all players because pitchers are not officially registered as being pitchers. Consequently, the leagues do not enforce that a player always plays in a certain position. Therefore, MLB doesn't have the right to give a longer suspension to a player only because he usually plays as a pitcher (even though everyone knows he actually is a pitcher). The equal suspensions for all players is probably part of the collective bargaining agreement between the leagues and the players' union.
Comment: That sounds like another good question to be asked ;)
Comment: I wonder if Major League Baseball has ever prevented a player from playing a **specific** position via suspension.
Answer: This isn't exactly an accurate question.  MLB starting pitchers are generally suspended for 5 games at a minimum, which is intended to mimic being suspended for a start.  While it doesn't exactly mean a start is missed, it does affect the team - you need 5 other starters for those 5 games, likely meaning you are starting someone who wouldn't normally start, or someone from AAA, or you're starting someone on short rest.
This is most easily seen in the default suspensions for actions a pitcher would likely take.  In recent years (more recent than the question, following the latest CBA largely) starting pitchers are actually given 6 games commonly, which will often reduce their total start count for the season.
In the case of things like brawls, starting pitchers get similar levels to position players, except they usually start at 5 games.  That's reasonable, because it's a similar proportion of the season for them (2/32 instead of 10/162, both are effectively 1/16).  Ian Kennedy for example received 10 games, or effectively 2 starts, for his role in starting the Dbacks-Dodgers brawl in 2013; only one other player received even 5 games.
Answer: If you think about the math, suspending a starting "field" player for five games prevents that player from contributing to his team for the next five games.  If a pitcher was only going to be able to contribute in a meaningful way for that one start over that period, a five game rip, even though it really only affects one start, still has the same result of the player not being able to contribute for five games.
Plus, you never know what might happen.  If the pitcher is slated to start game 1 and they have to move to a temporarily shortened rotation (Game 3 pitcher gets food poisoning), it could cost him two starts.  If they get into a marathon extra inning game, that pitcher is not available to pitch to a single left-handed batter in the 18th inning as the manager perhaps would have wanted.
In any scenario, the same net effect of not being able to contribute to five games holds.
If you had a non-pitching bench player who was a backup and used mostly as a substitute or pinch hitter, how would that be evaluated for suspension for involvement in a bench-clearing brawl?  Would they also require a different kind of calculus?  Generally, with rules, the simpler they can keep it, the less subjective it is and the less opportunity for controversy over arbitrary treatment of one player vs another.

Suspending a pitcher for misconduct


Newbie question : where to put "advanced" page content?

Question: It's been almost 3 years that I'm a web developer and I just started with Drupal 8. I have to say that's I'm feeling really confused by all the things in the Drupal worlds that you have to understand in order to create a website.
Here is the thing, I'm supposed to create a little website (3 pages for now) with a 100% custom appearance. I started by creating a new Drupal 8 theme with its libraries and dependencies and started coding the website's layout in twig. I added a few blocks in the theme's configuration (and in the twig) like a header block, two highlights blocks, a main content block and so on.
I'm at the point where I finished the layout and I'm supposed to add content of the 3 pages :

A main page containing text, images, a thumbnail of the last posted photos album, and an overview of the two last posted articles.
A form who's supposed to store the data somewhere (in the database I guess).
A second form who's supposed to do quite the same.

My questions are :

Since I have a very specific content for my three pages with HTML/CSS and Javascript, where am I supposed to put it ? Simply in 3 separated "Basic page" in the "Content" section of Drupal ? It seems way too simple. The "Basic page" content isn't supposed to be only text/images ?
I'm using a "naked" Drupal. In order to create the forms and other special stuffs, I'm supposed to use modules, right ? Are there any that are mandatory ?

Thank you all in advance, and please excuse my English, it isn't my mother tongue.
Comment: Welcome to Drupal Answers. This is a very broad question. I will *not* vote to close it, because I think I understand what the essence of your confusion is. However, in the future I recommend that you try and be as specific as possible, because that will usually yield higher-quality answers.
Answer: IMHO it's easier to start with content, and add the design once the content structure is ready. Drupal tries to separate content and design as much as possible, so you can always change one and keep the other.
There are no mandatory modules, especially with Drupal 8 you can get very far without any additional modules.
Drupal stores the content of a page as "nodes". Nodes have a type, like "article" or "product". You can use the default node types that you get out-of-the-box, or define your own. Each node type has a number of fields, like a text fields, image fields, date fields, etc. You can enhance node types by adding additional fields. Drupal will take care of rendering those fields on a form, storing the content in the database, and displaying the content on the page. There is a lot more I could say about this, but I recommend that you read the documentation, especially the part about content structure.


In Bach's WTK I Prelude in C major, is Glenn Gould's performance more literal reading of the score?

Question: Bach's prelude in C major, being beginners' favorite, seemingly shouldn't be controversial as to how it should be read. This is why Glenn Gould's interpretation came to me as a shock with each arpeggio ending abruptly. Virtually every other performance has smooth transitions between every chord (for example, Lang Lang, Schiff, Goulda – the last one being clavichord). Therefore I decided to check what the score really says.

My beginner's reading is that it is Gould who is right, for the following reasons:

high note of each chord is a sixteenth note just like the ones preceding it, as a sort of confirmation there's even a pause saying "play no further",
lack of pedal marks (obvious given the period in which it was written),
lack of legato marks

Is there anything in the score that justifies the majority interpretation? Or does it come from some implicit assumptions known to experienced musicians?
Answer: Gould's interpretation is his, but it is in no way more "right" than others, any more than his singing along is right or wrong - it is simply a feature of his recordings that appeals to some and not to others.

The pedal wasn't invented in Bach's time, and whether or not to use it when playing his music on a modern instrument (or whether to do this at all or not) has long been an controversial but unprovable  question.

Gould does in fact not play the sixteenths alike that are notated alike. He adds a pronounced staccato on the last one that makes it a lot shorter than the previous ones. This separates the to halves of the bar clearly, but there is no reason to assume that this is more or less true to Bach's intentions.
Comment: I don't focus on the authors intent because I'm aware that's too hard too guess, my question is about consistency with the score as it's written. Thanks for pointing out that Gould's sixteenths aren't born equal either.
Comment: @Szymon The whole point of a score is to communicate the composer's intent. However, different composers and different eras have included or excluded details differently, which is why there are different interpretations in performance. To leave out author intend renders the question trivial. Obviously Gould is following the score accurately, but so are all the others. The differences don't lie in the score; they lie in what's not in the score.
Comment: @Szymon You may find this of interest: [What does it mean to "play what is not written"?](https://music.stackexchange.com/questions/113511/what-does-it-mean-to-play-what-is-not-written).
Comment: @Szymon Of course it's not so simple, because "author's intent" and "score as it's written" are entangled. The score certainly records some degree of authorial intent, but there's an additional job of uncovering just what they *meant* by it (and that's where the whole field of "performance practice" comes in). Among the things that various authors and periods "mean" differently is how literally they expect the performer to respond to what's written.
Answer: Disclaimer: I'm not a Glenn Gould biographer and can't speak with authority about how he perceived his relationship to the original work.
But regardless of how he felt about it, all of his Bach is very much "interpreted." It is his Bach, and largely frees itself from any ironclad guilt about "the right way" or "Bach's way." It's not unlike a modern production of Shakespeare—when Joel Coen, Kenneth Branagh, or Baz Luhrmann create their version of a play, the results are very much something that started with Shakespeare, ended with them, and can't be mistaken for anyone else's.
The wonderful thing about operating in this mode is that no one can (legitimately) say that you shouldn't have made a certain choice. They might say that they don't like it, they might say that one shouldn't operate in that mode at all, but as long as you're in "this is what I make of it, and anything goes" mode, then you can do whatever you like.
Okay, all that out of the way, it's still true that Bach wrote (as far as I can tell, there are several "original sources") that sustained C and E. Gould is just taking a very literal reaction, making the other sixteenths quite separated. So his articulation is not merely the result of his own whim, but motivated by what he sees on the page.
At the same time, I don't know that one has to have that extreme a response   to the differences in how Bach has notated the members of the arpeggio. If others choose to pedal straight through the chord, I don't see that that's inappropriate.
Answer: Whether it's true to Bach's intention or not I don't know, but to answer your question unequivocally: no, it's definitely NOT a more literal reading of the score.
As written in the other answers; his last notes of the arpgeggio's are staccato's. And to my ear not only the very last ones either.
There are situations where the difference between non-staccato and staccato 16ths can be unclear, but this is not it, since we can hear very clearly the shorter attack(s) and release(s) of the last note(s)


C# Split text array into sub array

Question: I can't seem to find much on this online :(
For my course I have to get text from a grocery.txt file and output an invoice.
The text file looks like this:
regular,bread,2.00,2
regular,milk,2.00,3
regular,cereal,4.00,1
fresh,rump steak,11.99,0.8
fresh,apple,4.60,1.00
fresh,cucumber,2.20,0.936
regular,cream,2.20,1
regular,mustard,3.30,1
fresh,carrots,1.79,1.5
regular,tomato sauce,2.95,1
regular,salt,2.80,1
fresh,bananas,4.00,1.2

Currently I use this method to get the text:
    string[] groceryItemsArray = System.IO.File.ReadAllLines(@"C:\C\groceries.txt");

What I get is an array that in stores the entire line (for example "fresh,bananas,4.00,1.2").
I have no idea how to split the array into sub arrays or even whats the best way to go about this. Unfortunately this course task are way too advanced for the little material we have been taught and time we have for this. I have already spend around 6 hours watching videos and getting not very far in learning the advanced stuff.
This is what I am trying to accomplish.
A. Class named grocerrItem. This class has properties:
    name and price
    this class must have 2 constructors
A. subclass of this is a purchasedItem.
    this class has an integer property 'quantity'
    one of its methods findCost, calculates the cost of the item, including 10% GST.
    the formula for this is price * quantity * 1.1
C. A subclass of this class (purchasedItem), freshItem has
    a property weight, a double type.
    The findCost method here, uses the formula:wieght * price, as it is not subject to GST.
Groceries.txt contains information as follows:
type(regular or fresh), name, price, quantity/weight - depending on being regular or fresh.
** An invoice should be represented as a collection of grocery items (parent class). This can be done using any container structure i.e. array, list or collection. you will then use iteration
Comment: Look up string.Split()
Comment: possible duplicate of [CSV File Imports in .Net](http://stackoverflow.com/questions/1898/csv-file-imports-in-net)
Comment: Just to confirm, are you trying to split it into individual strings? Or are you trying to have a "sub array" for each line? What do you mean by "sub arrays?"  There are a ton of ways of getting either one of those done very easily, but we need more information.
Comment: Could you add what you expect as  output?
Comment: Sorry, added outcome to question.
Answer: You can just use String.Split which returns you the sub array that you want.
public static void Main()
{
    string[] groceryItemsArray = System.IO.File.ReadAllLines(@"C:\C\groceries.txt");

    // now split each line content with comma. It'll return you an array (sub-array)
    foreach (var line in groceryItemsArray)
    {
        string[] itemsInLine = line.Split(',');

       // Do whatevery you want to do with this.
       // e.g. for 1st line itemsInLine array will contains 4 items
       // "regular","bread","2.00", "2"
    }
}

Comment: Interesting, makes sense. but when I try to write out itemsInLine I get an error "The name itemsInLine does not exist in this context". Can you please explain a little how this works?
Comment: @RiCHiE where are you accessing that `itemsInLine` variable and also let me know, what actually you want to do at the end so that I can explain how to achieve that
Comment: Never mind sorry I was using wrong syntax.  I'm using           Console.Write(groceryItemsArray[0][1]);  this seems to be seperated by letter though and not by the ,
Answer: You can use this code (I'm not sure what exactly you looking for):
/// It's return all text as a single list
var groceryItemsArray = System.IO.File.ReadAllLines(@"C:\C\groceries.txt")
      .SelectMany(x => x.Split(new char[]{','} , StringSplitOptions.RemoveEmptyEntries)).ToList() ;

Or if want to return as Child List can use this code:
 var groceryItemsArray = System.IO.File.ReadAllLines(@"C:\C\groceries.txt").Select(x =>
           new { Child = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) }).ToList();

Comment: Looking to split the array up by each item in each line but not loose each line as an item.
Comment: Lambdas might be a bit too advanced for him.  He needs to understand what they are, what they do and how they should be used... not just given the code.  Just a thought.
Answer: I didn't really understand what are you trying to output, but here's some basic things I did understand on your question:
(code not tested)
I created a parent class:
class GroceryItem
{
    public string ItemName {get;set;}
    public decimal Price {get;set;}

    public GroceryItem() { }
}

And creates a child class:
class PurchasedItem : GroceryItem
{
    public int Quantity { get;set; }
    public decimal Cost { get;set; }

    public PurchasedItem(string[] item)
    {
        ItemName = item[1];
        Price = decimal.Parse(item[2]);
        Quantity = int.Parse(item[3]);
        FindCost();
    }

    private void FindCost()
    {
        Cost = Price * Quantity * 1.1;
    }
}

Using your input to get all groceryItems, you can iterate using foreach loop and collect a list of purchasedItems.
Main()
{
    string[] groceryItems = System.IO.File.ReadAllLines(@"C:\C\groceries.txt");

    var purchasedItems = new List<PurchasedItem>();
    foreach (var item in groceryItems)
    {
        string[] line = item.Split(',');
        purchasedItems.Add(new PurchasedItem(line));
    }
}

Well if you didn't understand this basic concept of programming, you better start on this link.
Comment: Yeah a bit lost I guess, been through a lot of basic material.
Comment: If you didn't understand the example that I've posted. I recommend you to start with the link I included to my answer, good luck! :)
Comment: Yeah I'm having a look, I don't see why it's so complicated to turn the array into a multidimensional array that has the 4 split values similar to what Sachin posted. Maybe my thinking of other languages is completely different to C#

C# Split text array into sub array


problema com matriz de ordem maior que 10 em C

Question: olá, companheiros programadores! Venho pedir ajuda com um problema que encontrei ao fazer um código que gera uma matriz aleatória, sem repetição em formato de caracol. O problema surge quando dou uma ordem pra matriz maior que 10, os valores aleatórios são equivalentes ao numero de elementos da própria matriz.
Segue o codigo:
<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int ordem;//global

int verifica(int valores[ordem][ordem], int valor)
{
    for(int i=0; i<ordem; i++)
    {
        for(int j=0; j<ordem; j++)
        {
            if(valores[i][j]==valor)
            {
                return 1;
            }
        }
    }
    return 0;
}

int aleatorio(int matriz[ordem][ordem])
{
    int aux;

        aux=rand()%(ordem*ordem)+1;

        while(verifica(matriz, aux)==1)
        {
            aux=rand()%(ordem*ordem)+1;
        }
        return aux;
}

void caracol(int matriz[ordem][ordem])
{
    int inicio=0;
    int fim=ordem-1;  //o fim tem que ser ordem -1 pra não estourar a matriz q vai de 0 a 4
    int c;    //contador para o while

    c=0;

    while(c<ordem*ordem)
    {
        for(int i=inicio; i<=fim; i++) //percorre no sentido X+
        {
            matriz[inicio][i]=aleatorio(matriz);
            c++;
        }

        for(int i=inicio+1; i<=fim; i++) //percorre no sentido Y-
        {
            matriz[i][fim]=aleatorio(matriz);
            c++;
        }

        for(int i=fim-1; i>=inicio; i--) //percorre no sentido X-
        {
            matriz[fim][i]=aleatorio(matriz);
            c++;
        }

        for(int i=fim-1; i>=inicio+1; i--)  //percorre no sentido Y+
        {
            matriz[i][inicio]=aleatorio(matriz);
            c++;
        }

        fim=fim-1;
        inicio=inicio+1;
    }
}

int main()
{
    printf("Qual a ordem da matriz: ");
    scanf("%d", &ordem);
    printf("\n\n");

    int mat[ordem][ordem];

    srand(time(NULL));

    caracol(mat);

    for(int i=0;i<ordem; i++)
    {
        for(int j=0;j<ordem; j++)
        {
            printf("%3.d", mat[i][j]);
        }
        printf("\n");
    }

   return 0;
}
</code>
Comment: Olá amigo! Qual é a dificuldade que estás tendo? Há algum erro no teu código?
Comment: olá! nenhum erro que eu saiba, percebi que escrevi o espaçamento errado,  e os valores estavam grudando no que estava do lado, agora ja esta tudo certo, obrigado
Answer: A função "caracol" não está preenchendo todos os valores da matriz, então pode ser que a matriz esteja com lixo de memória.
Inicie ela no começo da função "caracol" desse jeito:
<code>for(int i=0; i<ordem; i++)
{
    for(int j=0; j<ordem; j++)
    {
        mat[i][j] = 0;
    }
}
</code>
Outra coisa, esse algoritmo me parece muito ineficiente. Acho que seria executado bem mais rápido se você criasse um vetor de tamanho ordem*ordem e preenchesse ele com os valores de 1 a ordem*ordem. Depois você embaralha esse vetor e vai pegando os primeiros valores. Assim você garante que não vai ter números repetidos na matriz.
Comment: obrigado! com embaralhamento de array deu certo, mas eu tinha feito dessa forma porque o professor pediu, ai gostaria de tentar resolver esse . O que você falou sobre iniciar em for duplo o caracol? não entendi muito bem.  Eu tentei iniciar tudo com 0 mas no final voltam aqueles números gigantescos, e tambem eles estão preenchendo todos espaços, só que como param no limite do place holder de 4 casas.


Dynamically add $watch

Question: I have a JSON dataset that each row includes an input value, a small block of JavaScript code used to calculate and a subtotal value that is the result of the input value after an eval() preforms the calculation.  The dataset will contain one or more rows.  Each input will be repeated onto the page in HTML and a sum of the subtotals will be shown to the user as a total value along with each separate subtotal value.
I tried to use $watch and add one for each row in the repeater but I can't seem to get them to fire as the user changes the input value.
I have created my first Sample_Plunker  to demonstrate what I'm trying to achieve with no success.
Not sure if I should also be posting the code here or not but any help would be greatly appreciated.
Basically my HTML:

        Input_{{$index}}: <input ng-model="rule.inpValue" type="number" />

        Subtotal: {{rule.nSubTotal}}

    Total: {{MainCtrl.nTotal}}

This is my sample data and $watch that is not responding:
app.controller('MainCtrl', function($scope) {
    var _this = this;
    _this.nTotal = 0;
    // sample js code tht will be execuited later
    _this.myCode = [{
        "code": "_this.myCode.inpValue +2",
        "inpValue": 0,
        "nSubTotal": 0
    }, {
        "code": "_this.myCode.inpValue*3",
        "inpValue": 0,
        "nSubTotal": 0
    }, {
        "code": "_this.myCode.inpValue/5",
        "inpValue": 0,
        "nSubTotal": 0
    }];

    this.init = function() {
        $scope.$watch('MainCtrl.myCode[i].inpValue', function() {
            // debugger;

            // assuming if watch would fire, subtotal = eval( input )
            _this.nSubTotal = eval(_this.myCode[i].code);

            // I would also keep a running total at this point
            _this.nTotal = _this.nTotal + _this.myCode[i].nSubTotal;
        });
    }; //end init()
});

Comment: Your watch is not firing because there is no property `i` on the `$scope` against which the watch expression is being evaluated. Can you please explain more about the dataset? Why do you need those JS code snippets? From what I see, they aren't even valid. `_this.myCode.inpValue` will resolve to undefined since `_this.myCode` is an array.
Comment: there is no wildcard `[i]` to make your watch work. Also your logic inside watch isn't going to keep proper track of total. Using `eval` like this looks really dangerous and really doesn't make much sense. There are cleaner ways to do the modifiers using 2 properties and no `eval`
Comment: Igor: the code snippets are part of a shopping cart system but not like anything I've ever seen before.  There are hosts who are a fairly fixed group of around 800 (think of these as companies).  Each of the hosts has 1 or more checkout rules that apply to their customers.  There about 150 customers per host.  The host can create the rules (code snippets) and assign them to each of their customer. so to hard code all these rules into the source, I think fetching the rules from data is a much better way to handle a matrix of this size. And to maintain it, I only have revise the data.
Answer: There's a lot wrong with your code, but basically to answer your question, you can apply a watch to each of the items in an array by looping through the array and calling $scope.$watch once for each element.
I also strongly advise you to use actual functions and not eval() in order to evaluate expressions.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  var _this = this;
  _this.nTotal = 0;

  // sample js code tht will be execuited later
  _this.myCode = [{
    "code": function() { return this.inpValue + 2; },
    "inpValue": 0,
    "nSubTotal": 0
  }, {
    "code": function() { return this.inpValue * 3; },
    "inpValue": 0,
    "nSubTotal": 0
  }, {
    "code": function() { return this.inpValue / 5; },
    "inpValue": 0,
    "nSubTotal": 0
  }];

  function sum (values) {
      return values.reduce(function (a, b) { return a + b; }, 0);
  }

  this.init = function() {

    _this.myCode.forEach(function(code) {
      $scope.$watch(function() {
        return code.inpValue;
      }, function() {
        code.nSubTotal = code.code();
        _this.nTotal = sum(_this.myCode.map(function(c) { return c.nSubTotal; }));
      });
    });

  };

});

    Input_{{$index}}:
    <input ng-model="rule.inpValue" type="number" />

    Subtotal: {{rule.nSubTotal}}

  Total: {{MainCtrl.nTotal}}

Comment: What is so wrong with eval()?  I was thinking the eval would be wrapped by a try/catch.  And the code that is stored in the JSON would have been pretested before it ever goes live.

Your answer offers a lot of new things to me, never used map or reduce - very cool!  And I'm still trying to understand what you have done but it sure looks simple and straight forward.  **Brilliant** - thank you!
Answer: Your $watch is not firing because you are watching an expression which will always evaluated to undefined against the $scope. You have a few options when it comes to watching a set of items for changes:

A separate $watch for each item. Not very efficient, especially if the array is large.
A $watchGroup, which accepts an array of watch expressions. Useful when the expressions are non-uniform, for example different properties of different objects.
A $watchCollection, which shallow-watches a single object. I think this works best for your situation.

Also, note that the first argument to $watch* can be a function which returns a value you would like to watch. Putting this together, your watcher can look like
$scope.$watchCollection(function() {
  var aInputs = [];
  for (var i = 0, len = myCode.length; i < len; ++i) {
    aInputs.push(myCode[i].inpValue);
  }
  return aInputs;
}, function() {
  // one of the inpValues in myCode has changed
  // need to re-compute nTotal
});

Also, I strongly recommend you do not use eval() and follow JLRishe's suggestion of using functions. If you absolutely need to evaluate string expressions, you can do this safely with Angular's $scope.$eval. This evaluates expressions against a scope and a set of local variables. For example,
$scope.$eval("inpValue + 2", { inpValue: 3 }) === 5;

Here is a working Plunker. It uses $eval as a proof of concept, but again, if you can, use plain functions.

Dynamically add $watch


Softlayer API timeout

Question: I am using Softlayer Python API to pull hardware details. The script exits midway with below API error. I have rate-limited the number of servers to as low as 10, but still it errors.
Is there a way we can close/disconnect the connection to api ?
For example how do I close the "client" explicitly in below ?
Any help to overcome this ?
<code>client = SoftLayer.Client(username=USER, api_key=API_KEY,timeout = 1000)

hardware = client['Account'].getHardware(mask='id, fullyQualifiedDomainName,operatingSystem.softwareLicense.softwareDescription.longDescription,hardwareChassis.manufacturer,hardwareChassis.name,hardwareChassis.version,networkComponents.primaryIpAddress,processorCount,datacenter.name,primaryBackendIpAddress,motherboard.hardwareComponentModel.longDescription,processors.hardwareComponentModel.longDescription,memory.hardwareComponentModel.longDescription,memory.hardwareComponentModel.capacity,raidControllers.hardwareComponentModel.longDescription,hardDrives.hardwareComponentModel.longDescription',limit=limit,offset=offset);

File "/usr/local/bin/inv.py", line 90, in fetch_hw
hardware = client['Account'].getHardware(mask='id, fullyQualifiedDomainName,operatingSystem.softwareLicense.softwareDescription.longDescription,hardwareChassis.manufacturer,hardwareChassis.name,hardwareChassis.version,networkComponents.primaryIpAddress,processorCount,datacenter.name,primaryBackendIpAddress,motherboard,processors,memory,raidControllers,hardDrives',limit=limit,offset=offset);
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 392, in call_handler
return self(name, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 360, in call
return self.client.call(self.name, name, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/API.py", line 263, in call
return self.transport(request)
File "/usr/local/lib/python2.7/site-packages/SoftLayer/transports.py", line 199, in __call__
raise exceptions.TransportError(0, str(ex))
SoftLayer.exceptions.TransportError: TransportError(0): ("Connection broken: error(104, 'Connection reset by peer')", error(104, 'Connection reset by peer'))
</code>
Answer: There is not a way to close/disconnect the client when a process is running.
I was able to reproduce the error with more than 150 hardware items, not less. Sometimes it takes more time to get all data because your mask is very long, I suggest to reduce it as much as you can.
The Internet connection may be affecting the results you are getting, I suggest review it.
If you want to get all BMS, you can try by getting all of them part by part, below you can see an example.
If error persists you can try by retrieving them one by one (limit=1)
<code>"""
List Bare Metal servers.

The script retrieve all bare metal servers part by part in order to avoid time out
errors.

Important manual pages:
https://sldn.softlayer.com/reference/services/SoftLayer_Account
https://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
https://sldn.softlayer.com/reference/datatype/SoftLayer_Hardware/
https://sldn.softlayer.com/article/object-masks
https://sldn.softlayer.com/article/object-filters

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <firstname.lastname@example.com>
"""
import SoftLayer

# Your SoftLayer API username and key.
USERNAME = 'set-me'
API_KEY = 'set-me'

# The limit and offset of resultLimit feature.
limit = 10
offset = 0

# The array where all SoftLayer_Hardware objects will be stored.
hardware = []

# Flag to know if there are still SoftLayer_Hardware
has_items = True

# Create client instance
client = SoftLayer.create_client_from_env(username=USERNAME, api_key=API_KEY)

object_mask = 'id,fullyQualifiedDomainName,operatingSystem.softwareLicense' \
              '.softwareDescription.longDescription,hardwareChassis.manufacturer,' \
              'hardwareChassis.name,hardwareChassis.version,networkComponents' \
              '.primaryIpAddress,processorCount,datacenter.name,' \
              'primaryBackendIpAddress,motherboard.hardwareComponentModel' \
              '.longDescription,processors.hardwareComponentModel.longDescription,' \
              'memory.hardwareComponentModel.longDescription,' \
              'memory.hardwareComponentModel.capacity,raidControllers' \
              '.hardwareComponentModel.longDescription,hardDrives' \
              '.hardwareComponentModel.longDescription'

try:
    """
    Following loop helps to retrieve all data part by part. This example shows how
    to retrieve each 10 objects. Just change limit value if you want to
    increase or decrease the number of retrieved data.
    """
    while has_items:
        hardware_items = client['SoftLayer_Account'].getHardware(mask=object_mask,
                                                                 limit=limit,
                                                                 offset=offset)
        hardware.extend(hardware_items)

        if len(hardware_items) > 0:
            offset += limit
        else:
            has_items = False

    print(hardware)

except SoftLayer.SoftLayerAPIError as e:
    """
    If there was an error returned from the SoftLayer API then bomb out with
    the error message.
    """
    print("Unable to get SoftLayer_Hardware objects: %s, %s " % (e.faultCode,
                                                                 e.faultString))
</code>
I hope this help you.
Regards.

Softlayer API timeout


Angular 2 - Get all @input() in directives or component

Question: Is there a way to get all component or directive property with @Input decorators in angular 2?
Comment: all property of a class that declared with @Inputs() decorator.
Comment: What do u mean by components or directive property?
Answer: If you want to get all inputs value you can go with ngOnChanges hook.
class MyComponent implements OnChanges {
  @Input() myProp: any;
  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges - myProp = ' + changes['myProp'].currentValue);
  }
}


Do confidence intervals apply to quota sampling?

Question: French polling institutes are currently facing a major crisis after they recently published what can only be called the most ridiculous poll so far on the 2012 presidential election horse race. The French Senate is now considering to legislate on the issue by forcing polling institutes to publish, among other things, the confidence intervals for their results.
However, some pollsters are opposing the measure, claiming that confidence intervals do not apply to quota sampling, which is the method used by polling institutes in France. Since quota sampling is formally non-probabilistic sampling, there is some truth to the claim. But since quota sampling is fundamentally stratified sampling, confidence intervals should apply, right?
May I ask for experiences about this issue outside of France, in countries where pollsters also use quota sampling?
Comment: Quota sampling is distinct from stratified sampling in precisely this respect: unlike selection in a stratified sample, the lack of randomness in quota sampling means we cannot assure lack of bias.  So: maybe you can't erect CI's for estimates from quota sampling, but you *can* establish intervals for the bias.  Unfortunately, except when the sample is a substantial proportion of the population, the bias extends from almost -100% to almost +100%.  This is why quota samples have long been discredited ("Dewey defeats Truman", etc.).  *Caveat emptor.*
Comment: A lot of non-experts (i.e. people who don't understand the statistical theory behind sampling) throw around the term "quota sampling" without really knowing what it means.  That may explain the claim that it's common practice in Britain and Southern Europe.
Comment: @Fr Quota sampling is easier to carry out than random sampling: the pollster can specify what kinds of subjects are needed and how many to interview, send interviewers onto the street with these instructions, and easily check whether the job was correctly done: no need to do the difficult work of establishing a sampling frame, drawing a probability sample from it, hunting down its members, chasing after nonrespondents, *etc*.  Quota sampling is a textbook poster child for outmoded, known-bad sampling methods: see http://www.randomservices.org/random/data/1948Election.pdf for instance.
Comment: French opinion polling shortly before elections has more often than not been as accurate or more accurate than elsewhere in the world, though they do better when there are only two choices.  [Other polls conducted in March 2011](http://fr.wikipedia.org/wiki/%C3%89lection_pr%C3%A9sidentielle_fran%C3%A7aise_de_2012_%28sondages%29#Sondages_r.C3.A9cents) seem to be fairly consistent with the one which provoked this question.
Comment: Pollsters are claiming that quota sampling, which is the industry standard in France, is also widespread in Britain and Southern European states. I wonder if Britain really uses quota sampling, and why use quota sampling in the first place if the bias is irremediable?
Comment: @whuber: Thanks for the details. I knew about the "Dewey defeats Truman" story. I still doubt that British polling institutes are indeed using quota sampling, as claimed by the previously cited document, and would have to check. It would be interesting to know what are the different industry standards across the largest countries. I know for a fact that most of the data I download from [ICPSR](http://www.icpsr.umich.edu/icpsrweb/ICPSR/) is Random Digit Dialling.
Answer: As whuber says, the short answer is that quota samples are the "poster child for outmoded, known-bad sampling methods" and "have long been discredited."  The longer answer is that there may be conditions under which "quota-like" samples can work reasonably well.
Exhibit A here is recent work on reconstructing representative results from opt-in Internet panels. This paper gives the statistical grounding for this approach.  To make a long story short, typical sampling schemes 1) draw a random sample, 2) attempt to recruit subjects, and then 3) add post-stratification weights to compensate for differences in who responds.  In the opt-in approach, you 1) recruit subjects non-randomly, 2) compare responses to a representative baseline, and 3) add weights to compensate for the differences.
In terms of practice, opt-in sampling is similar to quota sampling, but the statistical foundation is more developed. The upside is that you can make claims about representative sampling, confidence intervals, etc. The downside is that your claims are based on difficult-to-verify assumptions about how people self-select into your sample.
A lot of people are skeptical about these methods -- they sound too much like quota sampling. But some evidence suggests that opt-in sampling can work well at least some of the time.  So despite the controversy, Polimetrix/YouGov (an early adopter of the opt-in sampling model) seems to be doing reasonably well.  Among other things, they've done all the data collection for the Cooperative Congressional Election Study, a series of recent academic U.S. national election studies.
(I'm pretty sure ICPSR carries this data.  If not, Harvard's social science dataverse certainly does. Lots of academics are using data from these samples.)
Anyway, you asked about quota sampling.  As you can see already in the comment thread here, any well-trained pollster will tell you that quota sampling is bunk. The jury is still out on opt-in sampling. For the time being, if you want to draw confidence intervals around quota samples, I'd say these methods are your best bet.
Comment: Thanks for the detailed answer. I flagged the following points in it: (1) Quota sampling is used for Internet sampling in your example. Out of that context, there is no reason to use it over random sampling through RDD or equivalent techniques. (2) Even in the context you describe, it remains very controversial. So, to go back to my question, French pollsters justifying quota sampling for all their work are just being silly, or ignorant of sampling theory, or both.
Comment: "French pollsters justifying quota sampling for all their work are just being silly, or ignorant of sampling theory, or both." Sounds about right to me.
Comment: Well, I am checking "Answered" on that one. Thanks for your time and detailed references.
Answer:
In most non-compulsory survey contexts, there is a substantial problem with nonresponse. This from 2002: "the recently reported estimate of survey cooperation rates from CMOR, the Council for Market and Opinion Research [USA], averaged only 14.7 percent." and from Paul Gerhold, "I believe that it is still possible to draw random samples. I just don't believe that it is possible to execute them." In this context, the fact that the SAMPLE is random isn't very relevant, because the resulting data isn't.
This makes bias adjustment the major issue in valid estimation, and field method design is an important component. The ways in which one might want to do this, and the resulting confidence estimates, are well beyond what can be discussed here.


Auto apply a coupon for a specific product based on Woocommerce cart subtotal

Question: Referring to this question: Apply a coupon programmatically in Woocommerce and then this one:How to apply an automatic discount in WooCommerce based on cart total?
Complete rookie here. I need to auto-apply an already existing coupon to one particular product when the subtotal of other products in the cart is $40. And I need to make sure that applying the discount doesn't create a loop by taking the coupon out due to dropping the total below the $40 threshold.
I'm not sure how to modify this code to do that:
add_action('woocommerce_before_checkout_process','add_discount_at_checkout');

function add_discount_at_checkout(){
global $woocommerce;
$minorder = 99;
if( $woocommerce->cart->get_cart()->cart_contents_total>$minorder){

 //APPLY COUPON HERE

}
}

Comment: I suggest you do add some of the code variations you have tried. And explain the subsequent results. Just adding some code you think you could use does not hold much water. Also, this question was perhaps better placed at https://wordpress.stackexchange.com/ .
Comment: I haven't tried any code yet as I am not a coder, the cart is an unstable one (long story) so trying things at random is dangerous, and I've not found code that does specifically what I am asking.
Answer: First the targeted coupon code need to be set as restricted to the targeted product only:

The following code will apply a specific coupon (a discount) just to a specific cart item if the cart subtotal (excluding this specific cart item) is up to $40:
add_action('woocommerce_before_calculate_totals', 'discount_based_on_total_threshold');
function discount_based_on_total_threshold( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Your settings
    $coupon_code      = 'summer'; // Coupon code
    $amount_threshold = 40; // Total amount threshold
    $targeted_product = 37; // Targeted product ID

    // Initializing variables
    $total_amount     = 0;
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );
    $found            = false;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ) {
        if( ! in_array( $targeted_product, array( $cart_item['product_id'], $cart_item['data']->get_id() ) ) ) {
            // Get the cart total amount (excluding the targeted product)
            $total_amount += $cart_item['line_total'] + $cart_item['line_tax'];
        } else {
            // Targeted product is found
            $found = true;
        }
    }

    // Applying coupon
    if( ! in_array($coupon_code, $applied_coupons) && $found && $total_amount >= $amount_threshold ){
        $cart->add_discount( $coupon_code );
    }
    // Removing coupon
    elseif( in_array($coupon_code, $applied_coupons) && ( $total_amount < $amount_threshold || ! $found ) ){
        $cart->remove_coupon( $coupon_code );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.
Comment: I encountered a conflict as I already had the coupon set for a minimum spend of $40.00. It wasn't allowing the auto-application of the coupon. Once I removed that from the coupon itself, this worked perfectly.


11:1 error Parsing error: Unexpected token }

Question:
I don't know what is wrong here. I have seen other posts but did not get answers.
The error is:
11:1  error  Parsing error: Unexpected token }

✖ 1 problem (1 error, 0 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely     additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-10-01T18_46_12_434Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

This is my code:
index.js
use-strict'
const functions = require('firebase-functions');
const admin= require('firebase-admin');
admin.initializeApp(functions.config().firestore);

exports.sendNotification= functions.firestore
    .document('Users/{user_id}/Notifications/{notification_id}')
    .onWrite(event=> {});

const user_id= event.params.user_id;
const notification_id= event.params.notification_id;

console.log("User ID: "
    + user_id
    +"| Notifications ID : " + notification_id);

});

Comment: The template literal also looks incorrect. It should be `\`Users/${user_id}/Notifications/${notification_id}\``
Comment: You'd also need to define a `user_id` and `notification_id` variable somewhere in your code (unless they're globally available or something) if you are indeed trying to use a string template here.
Comment: Doesn't seem clear whether you're trying to use a string template for `'Users/{user_id}/Notifications/{notification_id}'` - is [this what you're trying to do here?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
Answer: Try removing the orphaned }); on line 11.
I'm not sure if you are trying to use string templating on line 5, but if you are, make sure you are using magic quotes (`) around your string, and ($) before the brackets in this line:
exports.sendNotification= functions.firestore.document('Users/{user_id}/Notifications/{notification_id}').onWrite(event=> {});

It should look like this instead:
exports.sendNotification= functions.firestore.document(`Users/${user_id}/Notifications/${notification_id}`).onWrite(event=> {});

Comment: Are you sure the OP is trying to use a string template expression here?
Answer: I believe you are missing a:
• ' in the beginning of your 'use strict' statement
• random }) at the end of your code. Remove }).
• String interpolation using ${variable here}
Try the following:
"use-strict"

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firestore);
exports.sendNotification = functions.firestore.document(`Users/${user_id}/Notifications/${notification_id}`).onWrite(event => {});

const user_id = event.params.user_id;
const notification_id = event.params.notification_id;

console.log("User ID: " + user_id + "| Notifications ID : " + notification_id);

Answer: The code snippet you provided has some obvious syntax errors, as the other answers have indicated (there's an extra }); at the end of your script, and you need to make sure you have quotes around both ends of the use-strict statement. The the index.js file is line at the top of your snippet looks like you made an error when creating your post, so you should move this line out of your code snippet, or if it's in your actual script, remove it or prefix it with // to comment it out.
Which version of NodeJS are you using? There's a chance that if you're using an older version of node, you are using an arrow function syntax that is not compatible with your version of node.

Check your node version node -v against the ES6 compatibility chart here.
If your node version indicates that it does not support arrow functions, try replacing the following: event=> {} with function(event) {}

Edit: It also appears that the arrow function you provide to your onWrite does not match the arguments defined in the latest NodeJS Firebase documentation for the onWrite method. Looks like the arrow function should take the following arguments (change, context) => { /* method body */ }:
exports.modifyUser = functions.firestore
  .document('users/{userID}')
  .onWrite((change, context) => {
    // Get an object with the current document value.
    // If the document does not exist, it has been deleted.
    const document = change.after.exists ? change.after.data() : null;

    // Get an object with the previous document value (update/delete)
    const oldDocument = change.before.data();

    // perform desired operations ...
  });

EDIT 2: You are seeing an Error for user_id undefined because you are not supposed to pass the literal string text of {user_id} to Firestore. That's just a placeholder representing a value you need to provide. You should provide a valid user id. For example, if you have a user id of joe, and a notification id of 1, you should pass the values in as such: functions.firestore.document('Users/joe/Notifications/1'). Read the documentation here
You are also referencing the following variables in a call to console.log, which also appear to be undefined: console.log("User ID: " + user_id +"| Notifications ID : " + notification_id);. Are you setting these somewhere else in your code? I'm not seeing where they are set. If not, you need to set them somewhere before you reference them. Once these variables are set, then you need to update your call to the Firestore method as follows (note the use of back ticks ``, not quotes). This is called a string template. Something like this (obviously use the actual values for user_id and notification_id):
var user_id = "joe";
var notification_id = 1;
functions.firestore.document(
    `Users/${user_id}/Notifications/${notification_id}`)

Comment: now after removing }); it is giving this error
Error: Error occurred while parsing your function triggers.

ReferenceError: event is not defined
    at Object. (C:\Users\HP\Desktop\FirebasePushNotificationns\functions\index.js:7:16)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
Comment: I've updated my answer. Looks like the arrow function you're providing to your `onWrite` method is incorrect.
Comment: now am facing this error :TypeError: Cannot read property 'user_id' of undefined
    at exports.sendNotification.functions.firestore.document.onWrite.event (/user_code/index.js:7:28)
    at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
    at /var/tmp/worker/worker.js:733:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
after successful deployment ,in firebase function log.


Fundamental group of the complement of $S^1 \cup Z \subset \mathbb{R^3}$

Question: I want to calculate the fundamental group of the complement of this space:

This is the complement of $S^1 \cup Z \subset \mathbb{R^3}$ where $S^1$ is the unit circle in the $xy$-plane and $Z$ is the vertical axis.

My idea is to homotopy retract the space onto a more familiar space which we know the fundamental group.
I am having trouble 'visualizing' what the space could be and would like some help

Edit - I think it may be the torus, since the two generating loops have a similar structure. I could use help showing this explicitly
Comment: Thanks for the reply, yes I can see it resembles the two generating loops of the torus.. How could I prove this somewhat explicitly?
Comment: Hint: think torily.
Answer: Recall that $\mathbb{R}^3$ is homeomorphic to $D^3$, by contracting it radially. Under this map, $Z$ goes to a vertical line through the ball, and $S^1$ stays right where it is (maybe smaller, depending on your parameterization).
Then jam your thumbs through the $z$-axis, and you'll get a solid torus minus an equatorial circle inside it. Then you can thin down the walls (or inflate the circular gap, depending on how you want to think of it) to get a torus. I sketched something out in MS Paint to illustrate this:
Comment: Just looked in my notes, and the proof of this claim I was taught relies exactly on OP's question. Whoops. I'll go edit that.
Comment: How does adding the point at infinity turn it into $S^3$?
Comment: [Stereographic projection](https://en.wikipedia.org/wiki/Stereographic_projection). Just like how adding it to the line will make a circle, or adding it to the plane makes a sphere.
Comment: alright thanks, the picture really helps me visualize it. would an explicit paramaterisation be quite complicated?
Comment: Most likely. From $\mathbb{R}^3$ to the ball is pretty okay, but I don't know a parameterization for the step taking it to the solid torus.


Schedule update with specific new data in MySQL table

Question: I'm wondering if there is any way to schedule an update where I update a tables data on expiration of the old one.
E.g. John Smith has an active service at Company X, but wants to upgrade the service. However, due to restrictions to his current agreement the new service doesn't take effect until X days.
Is there any way to store the new data and update it at the end of a month in MySQL? If yes, would this require me to have another table with the new order data stored?
Answer: Often this requirement for changing things at future times is handled by placing start_date and end_date columns in your services table.
Then you can find presently active service rows with
   SELECT user_id, whatever, whatelse
     FROM services
    WHERE (start_date IS NULL OR start_date <= NOW())
      AND (end_date IS NULL OR end_date > NOW());

You can, if you wish, create a view called active_services automatically filtering the services table for currently active services.
 CREATE VIEW active_services AS
   SELECT *
     FROM services
    WHERE (start_date IS NULL OR start_date <= NOW())
      AND (end_date IS NULL OR end_date > NOW());

Note -- in this design end_date contains not the last moment the service is active but the first moment it becomes inactive. If end_date is null the service continues to be active.
To change a service  or user_id at the beginning of next month you do these two operations:
  UPDATE service
     SET end_date = LAST_DAY(NOW()) + INTERVAL 1 DAY
   WHERE user_id = <<user id you wish to change >>

  INSERT INTO service (start_date, user_id, whatever, whatelse)
          VALUES (LAST_DAY(NOW()) + INTERVAL 1 DAY,
                  <<user id you wish to change >>,
                  <<whatever>>,
                  <<whatelse>>;

Then, when next month arrives the active_services view returns the new service.   This is much more robust than relying on a precisely timed monthly job. If you do a monthly job, it can run anytime. It simply cleans up expired services.
You can use MySQL events to run particular jobs at appointed times. (But some shared MySQL systems don't let you use events.)
Comment: Ah.. I didn't know you could create views, I'm quite new to MySQL as you might've noticed. This actually makes it a lot easier, and solves more than one of my current problems. Thank you very much

Edit: How would I update the "view" for the user? I imagine I have to schedule something that updates the view every day or something, correct?
Comment: Nvm, I saw they automatically update. Much love, thanks :)
Answer: Interestingly mysql has event schedulers have a look at the documentation.
below is an example of a minimal CREATE EVENT statement:
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
  UPDATE myschema.mytable SET mycol = mycol + 1;

The previous statement creates an event named myevent. This event executes once—one hour following its creation—by running an SQL statement that increments the value of the myschema.mytable table's mycol column by 1.

If yes, would this require me to have another table with the new order data stored

I am not sure if you need another table or so...it purely depends on how you want it to be one
Comment: It's best to give an example, not just a link.


Android Eclipse- Do I need a new Manifest file for each activity?

Question: I have 1 manifest file set up right now that has this inside it
<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.treacheryofimages.www"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.treacheryofimages.www.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".OtherActivity"></activity>
    <activity android:name=".OtherActivity2"></activity>
    <activity android:name=".OtherActivity3"></activity>
    <activity android:name=".OtherActivity4"></activity>
</application>

</manifest>
</code>
I want to create new buttons for my second activity page. So do I need to create a new manifest page for every activtity?
Comment: Please take a look here to grasp a general overview of android development. [Android first app](http://developer.android.com/training/basics/firstapp/index.html)
Answer: No, you don't create a second manifest.  There is only one AndroidManifest.xml per project.  I don't really see the relation that you are making between the buttons in an activity and the manifest file.
Answer: You should define your activities in the manifest file and leave your layouts in the

source/res/layout

folder, there you can use a layout file for each view for example
Here you can find the official Android documentation on how to structure your folders in your project.


The page is currently unavailable

Question: I wanna set up nginx server to work with PHP and MySQL. To do so, I have:

Downloaded nginx files, unzipped it (C:/nginx/)
Downloaded PHP binaries and put them inside C:/nginx/php/
Changed C:/nginx/conf/nginx.conf to

worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.php index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        location ~ \.php$ {
            proxy_pass   http://127.0.0.1;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

And unfortunately, I can't get .php files to working. Trying to run one only displays "Sorry, the page you are looking for is currently unavailable." message.
I have clean environment, so all I have is nginx and php...What's wrong here?
Comment: You need to install php-fpm for running php in nginx. You also need t change this line
Answer: You need to install php-fpm for running php in nginx. You also need t change this line
fastcgi_pass   127.0.0.1:9000;

to this one
fastcgi_pass unix:/var/run/php5-fpm.sock;

Change to this unix:/var/run/php5-fpm.sock; to php-fpm sock file path.
Comment: I didn't mention I'm running it on windows, but thanks, I'll give it a try.

The page is currently unavailable


In Rugby, why can't the tackling team pick up the ball after the ball carrier lets go?

Question: That's basically my question. When a ball carrier is tackled, he usually lets go of the ball (behind him more often than not). Why can't the opposing team pick up the ball? And who is legally allowed to pick up the ball at that moment? Is there a name for this position?
Edit: Why is the blue team not going for the ball in this scenario:
Answer: The tackler can and often does pick up the ball.  The person that is tackled must release the ball behind them.  Once they release the ball they may pick the ball up and get up with it.
Once the tacklee lays down and set the ball they form their "side".  The tackler must be on his side before he can return to grab the ball.
I played wing for large university outside of football season - and have also broken this rule 20+ times so I have an understanding of it.
When I tackled another wing in the open field they would lay down, set the ball behind them, while I am jumping over them or going around them to be on side, and then it is a fight to get the ball first.  Often they would get the ball again.  If I did get the ball in that situation it would often lead to score or big gain.  If I didn't get the ball after the tackle, the other wing picks it up and is retackled but at that point there is reinforcement and ruck follows.
And in most cases me or the other wing is going to get cleated and kicked as the guys working the scrum have quite the disdain for wingers.  I mention the wing position because this kind of play happens most in the open field where wings would get the ball.  Normally in more congested part of the field a player is tackled, set the ball behind them and then a teammate picks it up while stepping over them.
Comment: Thanks for your input! So my question is, looking at a picture like this: https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSx-C6fLcz8ry9jb-BstxiNpT-o1uJIwCr47NV4rDHmMr48Wj8Tsg , why isn't the blue team trying to go for the ball?
Comment: That is a totally different question.  That is a question about how you are allowed to engage the ball on defense once a ruck is formed.  So the green team has established control, formed a ruck, why isn't blue going after ball.  First there are many styles of rugby and I believe this scenario has varying rules.  The 1-1 tackle situation is easy.  Here I believe that blue cannot go after the ball until it breaks the outside of the ruck or unless blue player goes through the ruck.
Comment: The ball-carrier is not required to release it behind them; they must place it and release it but this can be in any direction they choose.
Comment: @Nij - Right - I was unclear on that.  They release behind to create a side.  If they release in front the defender would just pick up the ball and run.
Comment: @ Coach-D I was more concerned that this is what allows tries to be scored despite being tackled outside the in-goal area, if and when the questioner or others see this occur, it would cause some confusion.
Answer: They can, but only if they're on their feet and onside. This is known as jackalling. If a player is tackled, he must release the ball. If a player from the tackling team can reach over the ball and grab it, it's his. If the tackled player refuses to let it go to stop the jackaller from getting it, that's a penalty for not releasing. Jackalling is one of the most common kinds of turnover. But if the jackaller is unable to keep his feet, and handles the ball while his knee is on the ground or he's otherwise not supporting his weight on his feet, that's a penalty against him.
The main way the attacking team will try to stop the jackal is by rucking. Teammates follow the ball-carrier, and when he is tackled and releases the ball, they form up over it and push opposing players away. Once a ruck has formed you can only play the ball with your feet - playing the ball with your hands in a ruck is a penalty - and the offside rules are very strict. You have to join the ruck from behind - if you join from the side, that's a penalty. Rucking players try to push their opponents backwards and move the ball backwards with their feet, making it available for their teammates. Once it's out the back of the ruck, it can be picked up. The rules of the ruck favour the tackled player's team, but if the tackling team successfully push their opponents back and move the ball to their side with their feet, it's their ball. This is called a counter-ruck.
Here's a video demonstrating how to prevent the jackal.
Answer: That's a ruck, which usually forms after a tackle.
There are special rules for a ruck. Players can only enter the ruck from behind the hindmost foot of the players already in it, and must stay on their feet.
So the only way to go for the ball is to try and push the team with the ball backwards. You can't go around because then you'd be "coming in from the side" (offside?). You could try to go over but that's difficult because you also have to support your weight with your feet otherwise you'd be "off your feet". Either offence concedes a penalty.
So you have to go through. If you manage to push the team with the ball back quickly enough, there's a good chance you can get the ball because the tackled player has to release it or concede a penalty themselves. (though they may try and place it for the scrum-half, the trick is to disrupt it before they can do this)
In this case it's likely the blue team (France I think) have decided rather than commit several players to the ruck to compete for the ball, it would be tactically better to use them to form a stronger defensive line, as the green team (Ireland?) seem to be well in control of the ball.
Answer: In the picture, green has control of the ball in the ruck. If the ball comes out (passes the foot of the last green man) then the blue team can engage if they are coming from an onside position. The onside line for them would be the foot of the last blue man in the ruck.


What is the equivalent in dplyr to an Excel formula referencing the cell immediately above itself?

Question: In the reproducible R code shown at the bottom, I'm trying to create a column called LowClassSplit, using R package dplyr,  whose value depends on its own value calculated immediately above itself. My attempt to resolve is commented out. Equivalent to the Excel calculations illustrated below and highlighted yellow, where the calculations in each Column F cell refers to its value immediately above itself. The blue cells show the column F calculations using the =FORMULATEXT(...) formula in Excel.
Any recommendations for the functional equivalent in dplyr? Or if not available in dplyr, in base R?
Below is the expected output in R, same as the illustrated Excel example:
# A tibble: 10 x 4
   Element SplitCode PreSplitClass ClassAtSplit
   <chr>       <dbl>         <int>        <dbl>
 1 C               0             1            0
 2 B               0             1            0
 3 D               0             1            0
 4 A               0             1            0
 5 A               1             2            2
 6 A               1             3            2
 7 C               0             2            0
 8 B               0             2            0
 9 B               2             3            0
10 B               2             4            0

Reproducible code:
library(dplyr)

data <-
  data.frame(
    Element = c("C","B","D","A","A","A","C","B","B","B"),
    SplitCode = c(0,0,0,0,1,1,0,0,2,2)
  )

data <- data %>% group_by(Element) %>% mutate(PreSplitClass=row_number()) %>% ungroup()

data %>%
  mutate(ClassAtSplit =
           case_when(
             SplitCode == 0 ~ as.integer(0), # This eliminates checking for > 0
             SplitCode > lag(SplitCode) ~ PreSplitClass, # if > previous value
             SplitCode == SplitCode ~ lag(PreSplitClass) # if equal (0s are avoided)
           )
  )

# Below shows where I was going before running into issue of referencing cell above:
# data %>%
#   mutate(LowClassSplit =
#            case_when(
#              SplitCode == 0 ~ as.integer(0),
#              (SplitCode == lag(SplitCode) && lagitself == 1)|(SplitCode > lag(SplitCode) & PreSplitClass == 1) ~ 1
#            )
#   )

Final code including Rui Barrada's posted solution:
library(dplyr)

data <-
  data.frame(
    Element = c("C","B","D","A","A","A","C","B","B","B"),
    SplitCode = c(0,0,0,0,1,1,0,0,2,2)
  )

excelCopy <- data %>%
  group_by(Element) %>%
  mutate(PreSplitClass = row_number()) %>%
  ungroup() %>%
  mutate(ClassAtSplit =
           case_when(
             SplitCode == 0 ~ as.integer(0), # This eliminates checking for > 0
             SplitCode > lag(SplitCode) ~ PreSplitClass, # if > previous value
             SplitCode == lag(SplitCode) ~ lag(PreSplitClass) # if equal (0s are avoided)
           )
  ) %>%
  mutate(
    LowClassSplit =
      case_when(
        SplitCode > lag(SplitCode) & SplitCode == 1 ~ PreSplitClass,
        SplitCode == lag(SplitCode) & SplitCode == 1 ~ lag(PreSplitClass),
        TRUE ~ 0L
      )
  )

Comment: Start by replacing `&&` by `&` and `||` by `|`. Can you post the expected output of that last data set/pipe?
Comment: On the Excel example C1 is being used in LowClassSplit. Is that relevant? Should you be creating a variable targetClass to pull in?
Comment: In response to Rui Barrada - I just edited per your suggestion. The expected output for the LowClassSplit column in R is shown in column F, LowClassSplit. But I-ll try spelling it out more clearly in another edit.
Comment: In response to CALUM - my next step, once figuring out the question in this post, is to create a variable targetClass. Correct.
Answer: Maybe the following is what the question is asking for.
library(dplyr)

data <-
  data.frame(
    Element = c("C","B","D","A","A","A","C","B","B","B"),
    SplitCode = c(0,0,0,0,1,1,0,0,2,2)
  )

data <- data %>%
  group_by(Element) %>%
  mutate(PreSplitClass = row_number()) %>%
  ungroup()

data %>%
  mutate(
    LowClassSplit =
      case_when(
        SplitCode > lag(SplitCode) & SplitCode == 1 ~ PreSplitClass,
        SplitCode == lag(SplitCode) & SplitCode == 1 ~ lag(PreSplitClass),
        TRUE ~ 0L
      )
  )
#> # A tibble: 10 × 4
#>    Element SplitCode PreSplitClass LowClassSplit
#>    <chr>       <dbl>         <int>         <int>
#>  1 C               0             1             0
#>  2 B               0             1             0
#>  3 D               0             1             0
#>  4 A               0             1             0
#>  5 A               1             2             2
#>  6 A               1             3             2
#>  7 C               0             2             0
#>  8 B               0             2             0
#>  9 B               2             3             0
#> 10 B               2             4             0

Created on 2022-07-10 by the reprex package (v2.0.1)
Comment: @CuriousJorge-user9788072 `TRUE ~ 0L` gives the statement a default value, in case none of the other conditions is met. It is always a good idea to include a `TRUE ~ default` at the end of a `case_when` instruction.
Comment: Hi Rui, that is what I intended and your solution works. What does TRUE ~ 0L do in your mutate statement? For the sake of completeness I also edit the OP to include your answer for LowClassSplit while retaining the column ClassAtSplit which is needed for further calculations


Test hypothesis point process is Poisson

Question: I have some data and I would like to test the hypothesis that they come from a homogeneous Poisson process. I can of course look at the inter event times and test if these are exponentially distributed. However this misses lots of reasons why it might not be Poisson it seems .  Is there a list of tests, or a particular good test, that I can use that does more than look at the set of inter event times between consecutive events?
If you take all the differences between arrival times, that is not just consecutive arrival times, can this be used to make a more powerful test for example?
Comment: Maybe by testing the constancy of the hazard rate ? I would take a look here: http://geb.uni-giessen.de/geb/volltexte/2014/10793/pdf/RinneHorst_hazardrate_2014.pdf
Answer: Have a look at the Kolmogorov-Smirnov test - this is a standard and fairly general way of checking whether an empirical distribution matches a theoretical one.
Comment: Is there some way to apply the Kolmogorov-Smirnov test here other than looking at inter arrival times between consecutive arrivals?  If I look at all inter arrival times (that is all roughly $n^2$ of them for $n$ points), then I am not sure how to apply KS any more.
Comment: It seems like you are looking for a free lunch.  You might consider the distribution of the arrival times for alternate events (i.e. what is the probability that one event has occurred).  I believe this just $\frac{e^{\lambda t}(\lambda t)^1}{1!}$ You still have $n$ intervals to compare.  But I don't think you can then simultaneously try to test P(0) (first arrival time), P(1), P(2), P(3) etc all at the same time - you are then double counting data.  So, to answer your question, I don't think there is a more powerful test that can be constructed.
Comment: You might also check out this link: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-262-discrete-stochastic-processes-spring-2011/course-notes/MIT6_262S11_chap02.pdf
Comment: Thank you for  the link. Would Ripley's K function be usable for example?


Github API delete event

Question: https://developer.github.com/v3/activity/events/types/#deleteevent
Based on the above events, how can I discover if a repo has been deleted? I'm currently using the Github archives files (https://www.githubarchive.org/) to feed my application.
Answer: Currently, you can't -- there's no event for that, so you'd need to try and fetch the repository with an API call. And you also can't know if it was really deleted or made private (except if you have access to the private repository, which you probably don't).

Github API delete event


Div se movendo na mudança de tela

Question: meu site inicial possui de inicio um html:

Lukas Monteiro

Bem vindo

e no css coloquei:
header {
width: 100%;
height: 100%;
background-image: url(../img/backgroundheader1.png);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}

#divcentral {
width: 407px;
height: 500px;
margin: auto;
padding-top: 200px;
text-align: center;
}

para que a parte inicial do site ocupe 100% em qualquer tamanho de tela. Porém, quando eu expando a tela(aumento a tela que estou) a div central sobe um pouco, desalinhando o que é pra ficar no meio.
Foto na tela minimizada

Foto na tela maximizada

Como faço para deixar a div exatamente no meio em qualquer tamanho de tela? ainda nao consigo fazer isso.
Quando faço um site no meu notebook, e abro num computador TUDO fica fora de lugar (geralmente é em altura) já que nas laterais eu sempre centralizo ou coloco margin left em %.
Answer: Utilize o recente e moderno display: flex para solucionar os seus problemas!

#container{
    background-color: steelblue;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
}

#center{
   width: 100px;
   height: 100px;
   background-color: #222;
}

No seu caso, você poderá definir na "div pai" da sua imagem o valor display:flex, combinado com justify-content: center e align-items: center para centralizar o "elemento filho" (que seria sua imagem)
Comment: ah, e obrigado.
segui o que vc falou e alinhou certinho!
Comment: sem querer abusar da sua boa vontade, poderia me explicar o que o display flex & o justify-content fazem?
Comment: Talvez isso te ajude, https://developer.mozilla.org/pt-BR/docs/CSS/Usando_caixas_flexiveis_css
Comment: @LukasMonteiro que bom, cara! boa sorte aí no seu projeto. Considere votar positivo e marcar a pergunta, caso isso tenha resolvido seu problema.

Div se movendo na mudança de tela


Possible invalid domain records

Question: Hi I am using an elastic loadbalancer from amazon.
The problem I am having is that I first had an A record for my domain which pointed to the IP of the loadbalancer.
This however only works for a short while because the ip of the loadbalancer is not static.
So to resolve this I removed the A record and added a CNAME record with name www.example.com and pointing to the DNS address of the loadbalancer.
The weird behavior I am getting however is that when I go to example.com sometimes it cant find a dns record. If I go to https://www.example.com or http://www.example.com it will resolve and when I then try example.com afterwards it also works for a while.
Does anyone of you know what might be causing this weird behavior and how to fix it ?
Regards,
Comment: In this case I think you'll have to post your domain name so we can look at the DNS directly.
Comment: Your root domain can not be a CNAME record and still have child records. The solution to this is using a route53 alias record.
Comment: @Tim its vionero.com
Answer: When using an Amazon Load Balancer you also need to use ALIAS DNS records. You did not mention that you are using Route 53 but you will need to. You will need to use ALIAS records for the domain root (mydomain.com) and each subdomain (www.mydomain.com) that points to the load balancer.
This link explains how to setup ALIAS records for load balancers.
Routing Traffic to an ELB Load Balancer
Comment: Route53 is the best way to use an ELB, but can a CNAME in a standard DNS server work? I think there's an issue with www vs non-www though, since from memory you can't have a CNAME at the domain root.
Comment: Amazon created ALIAS records just for this issue: the root domain resource record cannot be a CNAME. You will need to switch over to Route 53, which by the way is very easy and I highly recommend doing this.
Comment: I know it's the best way, but it is possible to work around? I suspect it is. For example perhaps have the ELB using the WWW subdomain, and your web server can send redirects from the domain apex to the www subdomain - it's not ideal, but it could potentially work. I know [CloudFlare has a solution](https://support.cloudflare.com/hc/en-us/articles/200168986-How-do-I-add-a-Amazon-ELB-Elastic-Load-Balancing-record-to-Cloudflare-), but that's not entirely standard.
Comment: @JohnHanley I setup my domain at Route 53 and created an alias record for www.vionero.com and vionero.com , yet when I try the latter I do not reach my site. I get the message that the dns name could not be resolved. Do you have any ideas how this is possible ?
Comment: HTTP or HTTPS? What is the TTL for the problem record? Double check the Route 53 record entries. If you still have problems, create a new question and include your Route53 records. I will be happy to look at them.
Comment: Hi @JohnHanley if I take the dns name of the loadbalancer and use http or https I will get to the website. my dns records are :
vionero.com.
A
ALIAS dualstack.violb-461408028.eu-central-1.elb.amazonaws.com.
No
-

another:
www.vionero.com.
A
ALIAS dualstack.violb-461408028.eu-central-1.elb.amazonaws.com.
No
-

and las the NS:
vionero.com.
NS
ns-167.awsdns-20.com.
ns-1347.awsdns-40.org.
ns-628.awsdns-14.net.
ns-1555.awsdns-02.co.uk.
-
-
172800 TTL
Answer: I can answer my own question. I removed my hosted zone after transfering my domain to route 53. Then I recreated it but the nameservers where out of sync with my registered domain.
Thanks for the help all

Possible invalid domain records


Run .aspx page, which is 'Added as Link'

Question: I created a project in Visual Studio named 'MyProject', and Added .aspx file to it named 'MyPage.aspx'.
Now, I created another project in that same solution named 'NewProject'.
I added 'MyPage.aspx' from 'MyProject', to new Project, using Add as link option.

Now if I make 'NewProject' as startup project, and 'MyPage' from 'NewProject' as Startpage, then it says The resource cannot be found.
How to achieve this?
EDIT: Consider that MyPage from MyProject is fetching displaying a Value from Database 'abc'. The connection string for database 'abc' is defined in Web.config of Myproject
Now I want created another project, wherin I want the same functionality as that of MyPage, only if I want to fetch data from database 'xyz' and not database 'abc'. I shall do that by adding my connection String for 'xyz' in NewProject
Comment: Why exactly are you trying to do this?
Comment: It seems ur taking shorcuts as existing items.. instead take the exact aspx file.
Comment: Just saw your edit. I think you're using the wrong aproach for what you're trying to achieve. If you need to have 2 web projects with a different database, just deploy it twice with a different connection string. If you don't need 2 web projects, just add another connection string and add some logic to determine which one you need to use.
Answer: You need to add project reference from 'MyProject' to NewProject through add reference.
If using IIS 7 or IIS 7.5 you can use
<system.webServer>
  <defaultDocument>
    <files>
      <clear />
      <add value="MyPage.aspx" />
    </files>
  </defaultDocument>
</system.webServer>

http://www.iis.net/ConfigReference/system.webServer/defaultDocument
or you can try as in global.ascx
public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Url.AbsolutePath.EndsWith("/"))
        {
            Server.Transfer(Request.Url.AbsolutePath + "MyPage.aspx");
        }
    }
}


How do I get all the options of a field?

Question: In Drupal 7, we are using the following code.
$field = field_info_field('field_name');
$allowed_values = list_allowed_values($field);

What can we use in Drupal 8?
Answer: Drupal 8.9.x still has the options_allowed_values() (a function implemented in the Options module). If the field uses a selection, check box, or a radio button widget, you could use the following code. The same function is still implemented in Drupal 9.3.x, the latest Drupal version under development, at the time I am posting this answer.
$field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('entity', 'bundle');
if (isset($field_definitions['field'])) {
    $allowed_options = options_allowed_values($field_definitions['field']->getFieldStorageDefinition());
}

Replace 'entity' with the entity type ID (for example, 'node' for nodes), 'bundle' with the bundle machine name (for example, 'article' for Article nodes), and 'field' with the field machine name.
Keep in mind that this code requires the Options module; the module using the code I shown should declare its dependency from it.
Using options_allowed_values() has the benefit that, if the field has a function returning the allowed values, that function is called. The following is the code used by options_allowed_values() to achieve that.
if (!isset($allowed_values[$cache_id])) {
  $function = $definition->getSetting('allowed_values_function');
  $cacheable = TRUE;
  if (!empty($function)) {
    $values = $function($definition, $entity, $cacheable);
  }
  else {
    $values = $definition->getSetting('allowed_values');
  }
  if ($cacheable) {
    $allowed_values[$cache_id] = $values;
  }
  else {
    return $values;
  }
}

Using options_allowed_values() also allows to cache the allowed values. In this way, calling options_allowed_values() for the same field (and same entity type) multiple times has a minimal impact on performance.
options_allowed_values() is defined also in Drupal 9.x and Drupal 10.x.
Answer: To get list of allowed values of field of select list try with:
    $options_array = [];
    $field_name = 'field_name';
    $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('custom_entity_name', 'bundle');

    if (isset($definitions[$field_name])) {
      $options_array = $definitions[$field_name]->getSetting('allowed_values');
    }

Answer: Try directly from field:
    $allowedVals = $entity->get('field_name')->getSettings()['allowed_values'];

Comment: I believe we can say `$entity->get('field_name')->getSetting('allowed_values')` (Drupal 9)


nginx using proxy_pass very slow

Question: I had an existing website hosted on a server, but we migrated this to a GKE instance.
I set up a simple nginx reverse proxy to use the new GKE do all the work, and the server just redirect as we do not have control over the DNS entry (it's a subdomain of the client's web site).
Accessing the gke-hosted site through a GKE ingress works perfectly (e.g. gke-backend.company.com)
This worked for a bit, and then it started being extremely slow (with some queries timeout-ing, but with the browser cache you can get a full page once you have reloaded multiple times).
here is my conf:
upstream backend {
  server gke-backend.company.com:443;
}

server {
  listen 80;
  listen 443 ssl;
  server_name website.client.com;
  location / {
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host https://backend;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass https://backend;
  }
  ssl_certificate /etc/letsencrypt/live/site/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/site/privkey.pem; # managed by Certbot
}

I tried it with only the proxy_pass, and it works the same.
How do I find out the exact issue ?
Comment: slow data access can be caused by different parts, for example: server who serve the website is overloaded (for slow disk access or high performance usage) a vmstat could determinate it, a communication between the proxy and server is slow, how many firewall is present between the two server; client is slow to execute some JS on the page, and so on; try to begin to exclude one by one this and post the results.
Answer: The issue was that proxy_set_header Host https://backend; did not work, I copy-pasted the complete host name in both proxy_set_header and proxy_pass, and now everythong works.
I have no idea what happened before though

nginx using proxy_pass very slow