Showing that $f_n(x) = \frac{nx}{1+nx}$ is not uniformly convergent on $[0,\infty)$.

Question: So I need to show that $f_n(x) = \frac{nx}{1+nx}$ is not uniformly convergence on $[0,\infty)$.
I found a way of showing this, but I'm not sure whether this is correct.
I'd much appreciate it if someone could either confirm whether I can use this or show the error I made!
$\exists \epsilon > 0: \forall N\in\mathbb{N}: \exists n\geq N : \exists x \in [0,\infty): |\,f_n(x) - f(x)| \geq \epsilon$
Choose for $\epsilon = \frac{1}{2}$, choose for $x = 0$ and choose for $n = N$.
$ | \frac{nx}{1+nx} - 1| = | \frac{nx-1-nx}{1+nx}| = |\frac{1}{1+nx}| = \frac{1}{1} = 1 \geq \frac{1}{2} = \epsilon $
Comment: The pointwise limit is $1$. It is enough to show that $\sup |f_n - 1|$ does or does not go to zero if you want to test uniform convergence.
Comment: An easier approach than disproving uniform continuity would be to state that the pointwise limit is not continuous, as $f_n(x)\rightarrow 0$ for $x=0$, but $f_n(x)\rightarrow 1$ for any other $x\in(0,\infty)$. Because each $f_n(x)$ is continuous, uniform continuity would guarantee that the limit function is continuous as well.
Answer: You are on the right track. The pointwise limit at $x=0$ is $f_n(0)\rightarrow 0.$ So the sequence converges pointwise to $1,$ except at $x=0,$ where it converges to zero. So you can't choose $x=0$... the functions are always zero there, so the distance $|f_n(0)-f(0)|$ is always zero.
So limit our consideration to $x>0.$ As you computed, $$|f_n(x)-f(x)| = \frac{1}{1+nx}.$$
Let $N>1$ be chosen and just pick any $n>N$. Then we can always pick an $x>0$ such that $\frac{1}{1+nx}  > 1/2$ (just take $x<\frac{1}{n}).$


How to load dlls from a NuGet into the current AppDomain?

Question: I try to create a modulable system in which each module can depend on other ones. Each module is a NuGet and their dependencies have to be resolved via NuGet. Each module contains a Type which will implements an shared Interface which allow for extracting a list of instruction.
All these instructions are to be executed in reverse order.
The detailed situation is this:

I have 4 projects which I will call API, S, M1, M2. They are all NuGets and they depends one from another is that way (-> stands for 'depends on'): S -> API, M1 -> S, M2 -> M1.
On the other hand we have the projet CORE, CONSOLE and TESTS. They aren't NuGets but they references each others in this way (-> stands for 'references'): CORE -> S, CONSOLE -> CORE, TESTS -> CORE.
M1 et M2 are modules, once again they are special because they contains a Type which must be found and instantiated from within CORE.

The goal is this:

I must fetch and install locally NuGets from a given repository.

This is done, it fetch the NuGets, unzip them into a given location.

I must inject the dlls from this extraction into the installer as if they were some sort of plugins.

How do I inject the correct dlls from the imported NuGets knowing that:

some of them are already present in the project CORE (notably the dlls that are present in the projects API and S).
some of them contain copies of the dll for different .NET Frameworks.
when I succeed to inject the dlls (by some artificial processes of filtering the lib/whateverframework directories and I try to find all the types which have a specific Attribute (which is located in the shared project API), this attribute seems to be different if I use the one which is in the dlls from NuGet and the one which I can directly use in VS.

I use C# 6 and VS2015.
How could I load dlls into the running application with all its dependencies using NuGet core API to solve dependencies? What is the best/proper way to do this?
Comment: This is a bit broad... Do you have a more specific question that just generally "how do I do this?"
Comment: I edited my post to ask a more specific question... I know this question has been asked many times but none of the answers happened to be a good solution to me...
Comment: You should look at MEF for injecting the DLL's or types.  I'm not sure NuGet is the correct tool for this; it kinda depends on what you want to do.  NuGet is oriented for public consumption, so if you're not distributing the DLLs to the public, it's a bit overkill.
Comment: See also http://stackoverflow.com/q/1137781/102937
Comment: I will actually distribute the modules to the public eventually... that's the reason why I need NuGet. And plus I need to resolve dependency so I want to use NuGet to do that. But except from this I would like to use some tool to take the dlls I imported with NuGet and inject them into the current application... which will go through the types and fetch the ones which have a specific attribute.
Comment: See MEF and the SO post I linked.  You might not need MEF; you might just need `Activator.CreateInstance()`.
Comment: Thank you anyway! I'll keep you posted.
Answer: A sample code you could use:
var localRepository = new SharedPackageRepository(packagesPath);
var allAssemblies = localRepository
            .GetPackages()
            .ToArray()
            .SelectMany(p => p.AssemblyReferences.Select(a =>
            {
                var path = Path.Combine(packagesPath, p.Id + "." + p.Version, a.Path);
                var aname = AssemblyName.GetAssemblyName(path);
                return new { key = aname.FullName, value = path };
            }))
            .DistinctBy(i => i.key)
            .ToDictionary(i => i.key, i => i.value);
AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) =>
        {
            var aname = new AssemblyName(eventArgs.Name);
            if (allAssemblies.ContainsKey(aname.FullName))
            {
                return Assembly.LoadFile(allAssemblies[aname.FullName]);
            }
            return null;
        };


Proving that the vector $v=ax+by$ is an eigenvector $M$ leads to $a=0$ or $b=0$

Question: Let $M$ be a square matrix. Assume at $x$ is an eigenvector for $M$ with eigenvalue $\lambda$, and that $y$ is an eigenvector for $M$ with eigenvalue $\mu$. Let $a$ and $b$ be real numbers.
How does can be proven that if the vector $v=ax+by$ is an eigenvector of $M$, then we have $a=0$ or $b=0$ ?
Answer: Initial assumptions : We must assume $\lambda \neq \mu$ ; thus, as a consequence, $x$ and $y$ are independent (non collinear).
Otherwise, we could fall in the case of an eigenspace (associated with $\lambda$) with dimension $\geq 2$ and the result to be established wouldn't be true.

Proof: Let us reason by contradiction.
Let us assume the contrary of ''$a=0$ or $b=0$ i.e., ''$a \neq 0$ and $b \neq 0$".
Let us write that $v:=ax+by$ is an eigenvector of $M$:
$$\tag{1} \exists \nu \ \ \ \text{such that} \ \ \ Mv=\nu v \iff Mv=\nu(ax+by)$$
Besides:
$\tag{2}Mv=M(ax+by)=aMx+bMy=a \lambda x+b\mu y$
Equating (1) and (2) would give
$$\tag{3}a(\lambda-\nu)x=b(\nu-\mu)y$$
As $x$ and $y$ are assumed independent (see initial assumptions), and as $a$ and $b$ are $\neq 0$, the only possibility for (3) to hold is that :
$$\tag{4}\lambda-\nu=\nu-\mu=0 \ \ \ \ \ \iff \ \ \ \ \ \lambda=\mu=\nu$$
But $\lambda \neq \mu$ (our initial assumption). Contradiction.


Como popular um p:datatable com uma List<> que contém dois atributos List<> dentro?

Question: Passei o dia inteiro hoje tentando fazer uma coisa que supostamente é simples mas não consegui. É o seguinte, estou usando o primefaces e sou nova nisso ainda e preciso de alguma maneira popular minha
 com um uma lista de objetos. Até ai ok. Mas dentro do objeto da lista eu tenho mais duas listas. Exemplo:
List<GastosMes> gastosAno

public class GastosMes {
   public int mesReferente
   List<Conta> contas
   List<Comida> comidas
}

public class Conta{
   public Double valorGas;
   public Double valorAgua;
   public Double totalContas;
}

public class Comida{
   public Double valorFeijao;
   public Double valorArroz;
   public Double totalComida;
}

Supondo este exemplo bobo, tenho duas listas dentro do objeto GastosMes. A lista GastosMes é então passada para minha página (retornada pelo gastosAnoController.gastosAnoList), mas daí só consigo exibir OU as Contas OU as Comidas. Meu xhtml está assim :

                    <f:facet name="header">
                        <h:outputText value="#{gastosMes.mesReferente}" />
                    </f:facet>

                        <h:outputText value="#{contas.valorFeijao}" />

                        <h:outputText value="#{contas.valorArroz}" />

                        <h:outputText value="#{conta.totalContas}" />

como dá pra ver, eu criei uma subtable (pesquisei um monte e só achei ela como "solução") e consegui preencher as colunas com os atributos da lista de Contas. O problema é que preciso preencher a tabela com os atributos da lista de Comida também, como faço ? alguma ideia? tentei colocar duas subtables, duas datatables, nada ficou legal. Se alguém puder me ajudar.
OBS: Como vou separara por mês, achei que seria mais pratico criar a classe GastosMes e dentro dela ter uma lista de contas e comidas relativas a este mês.
Comment: Acho que tem vários componentes que você pode usar para compor o datatable, mas depende do que você quer fazer (pode usar o ui:repeat em vez de da subtable). Por exemplo, veja essa pergunta em que o usuário precisava agrupar uma lista de checkboxes dentro de outra lista de checkboxes. http://pt.stackoverflow.com/a/169839/60946
Answer: Quando você criou sua subTable você poderia ter usado o valor do dataTable como referência, exemplo:

                    <f:facet name="header">
                        <h:outputText value="#{gastosMes.mesReferente}" />
                    </f:facet>

                    <h:outputText value="#{bean.valorGas}" />

                        <h:outputText value="#{bean.valorFeijao}" />


How i can create VIEW table using Drupal hook_schema()

Question: i want to create a view table in my custom module .install file and i want join with another table like i did in my db_query function but i want this thing in hook_schema function.
 db_query('CREATE VIEW Sample_Label_Data_By_CategoryId AS
                select
                `sample_label_library`.`SampleNumber` AS `SampleNumber`,
                `sample_label_category`.`CategoryName` AS `CategoryName`,
                `sample_label_and_category`.`CategoryID` AS `CategoryID`,
                `sample_label_library`.`MaterialName` AS `MaterialName`,
                `sample_label_library`.`EPANumber` AS `EPANumber`,
                `sample_label_library`.`SampleFilename` AS `SampleFilename`,
                `sample_label_library`.`LabelFilename` AS `LabelFilename`
                from ((`sample_label_and_category` join `sample_label_library`
                    on((`sample_label_and_category`.`SampleNumber` = `sample_label_library`.`SampleNumber`)))
                    join `sample_label_category` on((`sample_label_and_category`.`CategoryID` = `sample_label_category`.`CategoryID`)))')
    ->execute();

Answer: hook_schema() is only used to return a structured array representing your module's database tables. You can't execute a query from it. Well, you physically can, but you shouldn't.
Since hook_schema() is used on install, your code to create the View should be in hook_install(), and the code to remove it should be in hook_uninstall()


Istio: How do I exclude unhealthy destination from a VirtualService?

Question: I'm trying to configure load balancing and failover for external services. Each HTTP endpoint for the service needs its own specific headers.
I created a virtual service with two destinations:
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: test-external
spec:
  hosts:
  - test-external.com
  http:
  - headers:
      request:
        set:
          test: "true"
    route:
    - destination:
        host: "201.returnco.de"
      weight: 50
      headers:
        request:
          set:
            Host: "201.returnco.de"
            api-key: "xxxxxxxxxx"
    - destination:
        host: "501.returnco.de"
      weight: 50
      headers:
        request:
          set:
            Host: "501.returnco.de"
            api-key: "yyyyyyyyyy"
    retries: {}

The hosts 201.returnco.de and 501.returnco.de are external services, so I created a service entry for them.
apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
  name: test-external
spec:
  hosts:
  - test-external.com
  - 201.returnco.de
  - 501.returnco.de
  location: MESH_EXTERNAL
  ports:
  - name: http
    number: 80
    protocol: HTTP
  resolution: DNS

What I want is to route requests only to 201.returnco.de. The requests should not be routed to a host which returns 5xx status code. In this case, 501.returnco.de always returns 5xx status code, so it is considered unhealthy.
How should I configure the mesh?

I tried making the following destination rule, but this doesn't work.
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: test-external
spec:
  host: "*.returnco.de"
  trafficPolicy:
    outlierDetection:
      baseEjectionTime: 1m
      consecutive5xxErrors: 1
      consecutiveGatewayErrors: 1
      interval: 15s
      maxEjectionPercent: 100

The mesh considers 201.returnco.de and 501.returnco.de as two separate services. After the unhealthy endpoint for the host 501.returnco.de is evicted, Istio proxy returns 503 error for requests because there are no healthy endpoints.
Configuring multiple endpoints for a single service is not ideal because I need to set different headers for each endpoint.
Answer: From your configs and description, it is understood that you are creating multiple endpoints for the same service. In this scenario if you use "*.returnco.de" in your DestinationRule for OutlierDetection, when you receive 5xx errors for the endpoint 501.returnco.de as you mentioned it will evict the pods. Since 201.returnco.de is another endpoint of the same service which inturn relies on the same pods you are getting 503 errors because the pods are already evicted. In order to prevent the pods from getting evicted you can directly mention 201.returnco.de in your DestinationRule as we already know 501.returnco.de returns the 5xx errors and will evict the pods, below is the modified DestinationRule for your reference
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: test-external
spec:
  host: 201.returnco.de
  trafficPolicy:
    outlierDetection:
      baseEjectionTime: 1m
      consecutive5xxErrors: 1
      consecutiveGatewayErrors: 1
      interval: 15s
      maxEjectionPercent: 100

Also if you don't want your requests to be routed to 501.returnco.de you can give less weight such as 0 to 501.returnco.de rule and some high weight such as 100 to 201.returnco.de rule or use the explicit deny option of Istio.
Comment: `501.returnco.de` is just an example to emulate the failure on a service. In practice I don't know when or which destination will return 5xx errors, so I cannot simply hardcode the configuration.
Comment: @hylowaker I gave this solution because of unique use case you mentioned in the description. In general if you don't want to have multiple services you should omit outlier detection configuration for the endpoints, as both the endpoints exist on the same pod it will evict the pods as a result you will continuously get the 5xx errors.
Comment: @hylowaker have you gone through my reply.., revert back if you are still facing some issues.
Comment: I didn't find a solution with Istio-alone so I implemented my own Envoy Filter for this.
Comment: @hylowaker can you provide your solution here so that it will be helpful for remaining community members.


When are heat kernels only dependent on the distance?

Question: "All" the examples of heat kernels in circulation are only dependent on the distance between the space variables rather than on the space variables themselves, i.e.
$$K(t;x,y) = K(t;d(x,y)).$$
Think to the heat kernel on the Euclidean $d$-dimensional space, on the $d$-dimensional hyperbolic space, or even to the heat kernel associated to the laplacian acting on modular forms of integer weight on the upper half plane.
While wondering why this was true I stumbled across this article, where, at the top of page $2$, the author observes that this happens because of the homogeneousness of the space. This seems to be a very reasonable statement, but how to prove it?
We claim that if $X$ is a homogeneous Riemannian manifold, i.e. if the group of isometries $\mathrm{Isom}(X)$ of $X$ acts transitively on the set of points of $X$, then, for $x,y,x',y'\in X$ s.t. $d(x,y) = d(x',y')$ we have
$$K_X(t;x,y) = K_X(t;x',y').$$
Since the heat kernel is isometry invariant, it would be enough to produce a $\varphi\in\mathrm{Isom}(X)$ such that $\varphi(x) = x'$ and $\varphi(y) = y'$ to get the statement. But this seems to me a stronger requirement than what the transitiveness of $\mathrm{Isom}(X)$ ensures, specifically this is the $2$-transitivity. What am I missing?
Moreover I would be grateful if somebody could point to me an example of a manifold which is known not to have a heat kernel purely dependent on the distance.
Thanks!
Answer: This might be more a comment than an answer and I only adress your second question but here goes. The heat kernel will almost never depend only on the distance. For example, think of a manifold $M$ on which there are two distinct parts: a flat part (where you have Euclidean volume growth), and a very thin, cylindrical part (where the volume growth is much smaller than Euclidean). Now for $i=1,2$, think of a heat source at a point $q_i$ heating up a point $p_i$ at distance $\text{dist}(p_i,q_i) = d$, where $p_1,q_1$ are in the thin, cylindrical part and $p_2,q_2$ in the flat part. It is physically obvious that for a same amount of time, at least for small times, the heat from $q_2$ in the flat part of $M$ will be more spread out than the heat from $q_1$ in the thin part. So the point $p_1$ will be heated much more rapidly from the heat source $q_1$ than the point $p_2$ from the heat source $q_2$. Thus for $k(t,x,y)$ the heat kernel on that space, we can't have $k(t,p_1,q_1) = k(t,p_2,q_2)$ for small times. The same picture but from a Brownian movement point of view might be even more convincing. To make this rigorous, one could use the various bounds on the heat kernel in terms of the local volume growth of balls.
Comment: Thanks for your answer! You address a point I'm eager to explore, but unfortunately I do not fully understand your answer. Specifically, I do not see the statement "for a same amount of time, at least for small times, the heat from q2 in the flat part of M will be more spread out than the heat from q1 in the thin part". This seems to be in contradiction with Varadhan's large deviation formula (on a complete manifold): $$\lim_{t \rightarrow 0} -4t \log(K(t;x,y)) = d(x,y)^2.$$ In order to mark your answer as accepted, could I ask you to elaborate a but more please? Thanks again and +1!


closed form for this sequence?

Question: $$a_1 = 1; a_2 = 9; a_{n+2} = \frac{a_{n+1}a_n}{6a_n - 9a_{n+1}}$$
I need to find non-recurring formula for $a_n$. Is there any good way to do this? The only one comes to mind is to guess the formula and then prove it using mathematical induction.
Thanks in advance!
I've got the result and it looks like this: $a_n = \frac{-3*2^{n-1} + 2^{2n - 1} + 1}{3}$ but I really don't like this way and would love to know how to solve this properly.
Answer: You formula for $a_n$ seems wrong, is it $\frac{1}{a_n}$? Take inverse, one has
$$
\frac{1}{a_{n+2}}=6\frac{1}{a_{n+1}}-9\frac{1}{a_n}.
$$
there is a standard way to solve this (http://en.wikipedia.org/wiki/Recurrence_relation#Linear_homogeneous_recurrence_relations_with_constant_coefficients).
Answer: Let $b_n = \dfrac1{a_n}$. We then have
$$b_1 = 1; b_2 = \dfrac19 \text{ and } b_{n+2} = -9b_n + 6b_{n+1} \implies b_{n+2} - 3b_{n+1} = 3(b_{n+1} - 3b_{n+2})$$
This gives us
$$b_{n+2} - 3 b_{n+1} = 3^{n+1}(b_1 - 3b_2) = 2 \cdot 3^n$$
I will leave the rest to you to complete the details.
Answer: Hint:
$$a_{n+2}=\frac{a_{n+1}a_n}{6a_n-9a_{n+1}}$$
$$6a_na_{n+2}-9a_{n+1}a_{n+2}=a_{n+1}a_n$$
Now divide by $a_na_{n+1}a_{n+2}$ to get:
$$\frac{1}{a_{n+2}}-\frac{6}{a_{n+1}}+\frac{9}{a_n}=0$$
This is reccurence relation is easy to solve

closed form for this sequence?


What are the repercussions of using really thick gauge strings on my electric guitar?

Question: I have a Jackson King V JS32T electric guitar in blue, see the linked text for specs and the look of it. Anyway, it came with 0.09-0.42 strings and I've been using 0.13-0.56's on it for a little while, but I worry that I could be putting extra strain on my neck and other components of the guitar. Should I be adjusting anything else on the guitar for it to properly handle such a thick gauge?
My friend (who doesn't really know much about guitars but likes to think he does) thinks I should adjust my bridge, but I'd much prefer to get a definitive answer and if anything needs to be changed, take it to a guitar shop.
I'd much prefer to work out what I need to do (if I do need to do something) so when I go to the shop I know what to ask for, and they don't try ripping me off.
I have noticed that my tuning keys for the higher strings (B and E) are a bit stiff and not working as well as they used too. I've also noticed my guitar regularly detunes itself even though I am using such a high gauge and only going to Drop B.
Answer: Thicker gauge strings do require more tension in order to maintain the proper pitch associated with standard tuning on a guitar--but it's nothing that your guitar isn't already designed to handle. Over a very, very long period of time the tension of those thicker strings could cause some damage, but it's likely that you will have retired the guitar before that happens; besides if it does indeed ever happen it's a simple repair. Electric guitarists are lucky because their instruments are so much easier to repair than acoustic instruments.
Any time you change the action on your instrument take it to a reputable luthier for a setup--that or learn how to do it yourself so you can save the cash for that cool pedal you want. String gauge changes usually require intonation adjustments, bridge height adjustments, pickup height adjustments, and in some special cases nut adjustments. The truss rod rarely needs any major adjustments in this case, but I have had to do a few turns here and there. The set you are using is pretty hefty, but unless the strings don't fit properly into the nut you shouldn't have any problems. If they fit really tight, then use some graphite lubricant as @ledfloyd suggests or get the nut slotted. Know this, however, once you expand the slots on the nut there's no going back without incurring additional costs.
Your tuning keys will likely be okay. Most mass produced guitars skimp in this area anyway--so a replacement there would likely be a nice upgrade, but I'd only do it if they break or cause serious tuning instability.
Concerning finding a luthier that won't rip you off: I'd recommend you find a local guy you can develop a relationship with instead of going to a mega-store. Local guys will usually work harder for your business--at least those who understand who their competition is i.e. those giant mega-stores. If you want to be armed with some ideas on how to approach talking to them, and I always support that, then simply follow this advice: if it doesn't play right take it back and make them fix it or don't do business there again. Tell them this, politely, up front. I took one of my firebirds in for a new nut to a local shop and they completely screwed it up--I don't really understand how they screwed it up that bad, the high e string was hanging off the fretboard by about a millimeter. I took it back and they said they'd fix it, but they charged me for the material for the new nut. I don't do business there anymore. Instead I found an older local guy who's honest and dynamite at what he does. No compaints since.
Answer: Besides adjusting intonation the only other adjustment might be the trussrod. Are the strings really high off the fretboard when you go down past the 12th fret or do they bottom-out?
Going from 9s to 13s might cause the nut to bind your strings a bit and may need to be slotted wider (try some graphite lube first), that might help the Tuner problems a bit. The extra tension isn't making it easier for your Tuners but they should be able to handle it.
If your strings are completely stretched out your guitar should be staying more or less in tune especially in Drop B
Answer: If you played single coil pickups, then you would notice a gain in volume with bigger strings. I took my Tele from .012s to .009s and thought "Where did my guitar go?!?" That is the big reason that people go heavy. You have humbuckers and your benefit for big strings would be much less.
I went back to .010s because I'd be bending sharp on accident and wanted some more tension so I wouldn't have to learn self control. That is another reason people go so heavy.
Sounds like you are playing tuning lambada: "How low can you go?" Drop-B implies C# otherwise. Which drops the tension down again.
Almost certainly you'll have to reintonate. The bridge should have sufficient play that you can get the saddles back, but I won't go as far as saying "will". That is the third main adjustment you will need.
Comment: I tend to run .009s on all my floating bridge guitars, and .010s on the rest - but then I do tend to spec pretty high gain pickups. Combine the light gauge with a drop-D on my gigging guitars and the feel is really nice. It is always a shock to go back to my Warlock with the .010s.
Comment: My Tele sees nothing other than .011's and I absolutely love it. Twelves are a little too rough on my dainty hands :D.
Comment: I see, I see. A friend of mine had his guitar adjusted (what was done I don't know) but it was tweaked in a way he couldn't go any higher than Drop C or he'd break his guitar strings. Speaking of tunings, I also sometimes Drop to Drop A as well, contemplating Drop G, but my guitar would sound like rubber bands on a cardboard box that low, better off getting a baritone for those kinds of tunings.
Comment: The more you drop, the more you have to pull the saddle back. If you go back to standard, the saddles need to go back again. You know you have it right when the note at the 12th fret is one octave above the open note. All you should need is a tuner and a screwdriver to adjust it.
Comment: My R8 Les Paul absolutely loves 0.11's too. I think those guitars were made for 0.11's despite that they ship with .09s because they get a ton of oomph when you drop the gauge.
Answer: well on my iceman i use .012-.056 and i have that in drop c sometimes drop b maybe pushing it to A and on my halberd .011-.054 and thats in standard maybe Eb but it all depends on scale length the longer the scale the more the tension on the strings thats why most people who have standard guitars the scale is usually around 25" which gives the thinner strings higher tension but on certain  models e.g. Sg Les Paul's and icemen e.t.c. the scale is around 24.5" which doesn't seem alot but it defiantly feels it requires a thicker string gauge for more tension so if your guitars scale length is 25.5" (a bit longer than standard) and your strings feel real heavy then its cool just take it easy when tuning and restringing as a string snap may be bad for the neck so just measure the scale (from nut to the string saddle).
Answer: Hi I play a carparelli S4 and had some modifications done but bottom line I've got my action down to 45 thou at 12th of low E and about 37 thou at 12th of high E. I have the relief set to 3 thou at the 7th of low E while capoing 1st and fretting 15th.  I use the stewmac steel card tool and a very bright light and get it set exactly as to blend the string height up the neck.  The gauge of strings I use are custom that I get from strings by mail,  I order a 12-54 pure nickel rollerwound GHS string sets and special order (soi) for some .046's for my 5th string and a 56 for my low E.  This works well for me,  I find because of the mass of the strings I get awesome tone and less string Buzz mind you if I really dig in I'll get some Buzz but it stops quickly but the A and low E are a problem at lower action heights when you want to dig in and not have go mushy in tone thru a amp (I play thru a pre se 50 all tube amp) I find now any buzz I get now doesnt make it thru the amp enough to effect anything, I find a little string Buzz can make the guitar sound more acousticly dynamic and give a little acoustic like breakup just like a tube amp. The thicker A and low E string let over come enough of the string Buzz when I dig in abd got the amount of buzz right where I like it and I believe it helps me with controlling the string energy.  Well that's what ice come to find what I like :-)
Comment: The carparelli S4 is a les Paul style guitar, the scale length is 24.7
Comment: If your play something like a Tele with a 25.5 scale length a set of 11's will feel the same in string tension when compared to a les Paul with a 24.7 to 24.75 with 12's


Rushing Yard and Yard Run

Question: To a layman like me, they both sound like similar concepts (though, of course, they're not!): The aggregate number of yards a QB had run with the ball in his hands before either passing off the ball or getting intercepted, etc. Is my understanding even remotely correct? What is the difference between the two?
Answer: Rushing yards are an official stat.  When a player receives a hand off or a backwards pass, he  then advances the ball by running forward or "rushing".  Most often you see this stat in the NFL for running backs.  However quarterbacks and receivers may also have rushing yards in a game.  You may see updates during a game with a rushing yard total for players, it is the total rushing yards to that point in the game. Rushing the Football Wiki
Yard run usually refers to what happens on a certain play.  I.e. "The player X had a 12 yard run".  This means he would get 12 rushing yards also.
Announcers may refer to a yard run after a receiver catches the ball also.  These yards after the catch are added onto his receiving yard total and the quarterback's passing yard total. Yards after catch (YAC)
Both Rushing yards and "yard run" will be measured from the line of scrimmage with a loss of yards being a negative yard run and subtracting from the rushing yard total.
If the quarterback passes the ball, he will not get credit for any yards that he has run prior to the pass (Pass meaning legal forward pass).
Comment: @AmitSchandillia A QB (or any player for that matter) will earn rushing yards until they are tackled, fumble, go out of bounds, or score a TD.  If a QB throws the ball (a passing touchdown, interception, or completion) then he will not receive any rushing yards.  He will receive passing yards for the play only.
Comment: @AmitSchandillia you cannot gain rushing yards and throw an interception in the same play, due to the passing nature of an interception and the rushing nature of gaining rush yards.
Comment: So a QB earns credits only for the yards he has run until interception (or a TD)?
Answer: A rushing yard is a "running yard" gained on an official "rushing" play. This occurs when the quarterback either runs the ball himself (without passing), or hands the ball to a halfback or fullback for "rushing."
There are running yards that are NOT counted as rushing yards on other, non rushing plays. For instance, suppose a quarterback completes a pass for 20 yards, and the receiver runs another 15 yards. Those are 15 "running yards" that are not rushing yards; it counts as a 35-yard pass. Suppose a defender intercepts a pass and runs it back 10 yards. Those are 10 running yards that are not rushing yards. And a 25 yard kickoff or punt return are running yards but not rushing yards.

Rushing Yard and Yard Run


Unable to understand the time consumption by Java threads

Question: I created a 1000 threads and each thread takes about 10 seconds to finish. During these 10 seconds the thread doesn't sleep but does a simple math operation.
However, the program still finishes under 20 seconds on my PC (Intel i7 6 cores). I don't understand how. I was expecting it will take at least about 1000/6=167 seconds. Any idea what is going on ?
public class test
{
   public static void main(String args[]) throws Exception
   {
       long startTime = System.currentTimeMillis();
       Thread[] threads = new Thread[1000];
       for(int i = 0; i<1000; i++){
           threads[i] = new Thread(()->doSomething(10));
           threads[i].start();
       }
       for(Thread t : threads){
           t.join();
       }
       long endTime = System.currentTimeMillis();
       System.out.println("Time taken "+(endTime - startTime)/1000);
   }

   public static int doSomething(int seconds){
    long st = System.currentTimeMillis();
    long usageTimeInMillis = seconds*1000L;
    long startTime = System.currentTimeMillis();
    int i = 0;
    while ((System.currentTimeMillis() - startTime) < usageTimeInMillis) { i++; }
    long lt = System.currentTimeMillis();
    System.out.println("Done "+Thread.currentThread().getId()+" in "+(lt-st)/1000+" seconds ");
    return i;
   }
}

Here is the partial output:
Done 48 in 10 seconds
Done 36 in 10 seconds
Done 597 in 10 seconds
...
Done 206 in 10 seconds
Done 217 in 10 seconds
....
Done 462 in 10 seconds
Time taken 17

The output shows that every thread does run for about 10 seconds. Then how come a 1000 threads finished in 17 seconds?
Comment: As the program is written, the threads are not going to run for 10s of CPU time, they will run until the system time is startTime + 10s. It's not the same thing.
Comment: Time slicing?................
Comment: The only way I can see is by doing something in the loop that lasts a known amount of time, and loop as many time as necessary.
Comment: Why do you want it to take longer? I would consider it a good thing that the JVM/OS can switch threads while they are working.
Comment: I have rolled back your edit. Please don't modify a question to something that attempts to answer it, and removes or obscures the original question. If you want to answer your own question, **post an answer**.
Comment: @MaxMeijer With that edit, the question was no longer a question, but included a solution and response to comments. That is not how this site works. I stand by my rollback.
Comment: 1) every time there is an interruption, it may be followed by a context switch to another thread. So the method `doSomething()` is not necessarily completely executed in one go. The timer generates an interruption every 1/20 of a second or so.
Comment: I am not sure if you realized what I am asking. The program is taking *less* time than expected, not more.  How are 1000 threads , each thread requiring 10 seconds of CPU time, able to finish in 17 seconds on a 6 core machine?
Comment: I see, so how do I make them run for 10 seconds (without sleep)?
Comment: "Intel i7 6 cores" — Six real cores? Is Hyper-Threading enabled, meaning 12 cores effectively?
Comment: What does that mean "run for 10 seconds (without sleep)" You want each thread to consume 10 seconds worth of clock cycles so the total time is 1000 * 10s / (6 cores).
Comment: @dan1stiscrying I can imagine it would be quite useful to "simulate" what would happen to the system if a costly operation were to take place.
Comment: Then use 6 threads being busy for 167 seconds? Or better, simulate actual load or use JMH if you want to do benchmarks.
Comment: @MarkRotteveel I disagree with your edit. The question was already in that form for hours. Then a third party comes along after a long time and edits out the question from the original poster to turn it back into a question that had already been answered long before by a comment. I'm not going to undo your edit myself but I think you should consider doing so yourself.
Answer: As commented by Maurice Perry, you devised a task that would take ten seconds to execute, but that is ten seconds of time elapsed on the clock, not ten seconds of CPU activity.
You loop repeatedly, checking the current time on each loop. You check the time by calling System.currentTimeMillis(). Your intention was to keep the CPU core busy for the entire ten seconds. But that is not what is happening.
The host OS managing the platform threads in Java schedules a thread for execution at a time, and for a duration, of its own choosing. Your Java platform thread may be paused at any time by that host OS. So, in an extreme example case, your code may be checking the current time once, for a result of 2024-01-23T00:00:22.123Z. Then the host OS may suspend your thread. Your thread does nothing for several seconds. Eventually the host OS schedules that thread for further execution. The second time your code checks the time, the result is 2024-01-23T00:00:34.567Z. So over 12 seconds elapsed, but your code ran only briefly, just checking the current time twice.
That example is a bit extreme, as the host OS will not generally let a thread go 12 seconds without executing. But if your host computer's CPU is severely overburdened, such as running a thousand Java threads, such long thread suspensions could indeed happen.
So the behavior you experienced is a feature, not a bug. A thousand tasks waiting for ten seconds to expire on the system clock will indeed, in total, take about ten seconds.
Running your exact code takes 20 seconds on my MacBook Pro, 16-inch, 2021, Apple M1 Pro, 10 cores (8 performance and 2 efficiency), 16 GB RAM, macOS Sonoma 14.3.1, Java 21.0.1 in IntelliJ IntelliJ IDEA 2023.3.4 (Ultimate Edition).
Then I modified your code. I show the number of loops executed in each task.
package work.basil.example.threading;

import java.time.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class BusyBusy
{
    public static void main ( String args[] ) throws Exception
    {
        System.out.println ( "Demo start at " + Instant.now ( ) );
        final long demoStartNanos = System.nanoTime ( );

        final int countTasks = 1_000;
        try (
                ExecutorService executorService = Executors.newFixedThreadPool ( countTasks ) ; // We want one task per thread. So one thousand tasks means one thousand threads.
        )
        {
            IntStream
                    .rangeClosed ( 1 , countTasks )
                    .mapToObj ( TenSecondTask :: new )
                    .forEach ( executorService :: submit );
        }

        Duration demoDuration = Duration.ofNanos ( System.nanoTime ( ) - demoStartNanos );
        System.out.println ( "Demo end at " + Instant.now ( ) + ". demoDuration = " + demoDuration );
    }
}

class TenSecondTask implements Runnable
{
    private final int sequenceNumber;

    public TenSecondTask ( final int sequenceNumber )
    {
        this.sequenceNumber = sequenceNumber;
    }

    @Override
    public void run ( )
    {
        final long tenSecondsInNanos = Duration.ofSeconds ( 10 ).toNanos ( );
        final long taskStartNanos = System.nanoTime ( );
        long countLoops = 0;
        while (
                ( System.nanoTime ( ) - taskStartNanos ) < tenSecondsInNanos
        )
        {
            countLoops++;
        }
        System.out.println ( "Task # " + this.sequenceNumber + " in thread ID " + Thread.currentThread ( ).threadId ( ) + " done at " + Instant.now ( ) + ". Loops: " + String.format ( "%,d" , countLoops ) );
    }
}

My results showing a wide range of over a hundred thousand to over seven million. Total time elapsed is about 20 seconds, same as your code.
Demo start at 2024-02-15T09:24:13.773544Z
Task # 6 in thread ID 26 done at 2024-02-15T09:24:23.779903Z. Loops: 328,186
Task # 11 in thread ID 31 done at 2024-02-15T09:24:23.812401Z. Loops: 349,456
Task # 13 in thread ID 33 done at 2024-02-15T09:24:23.839549Z. Loops: 356,229
Task # 20 in thread ID 40 done at 2024-02-15T09:24:23.883941Z. Loops: 379,757
…
Task # 991 in thread ID 1019 done at 2024-02-15T09:24:33.561808Z. Loops: 981,788
Task # 992 in thread ID 1020 done at 2024-02-15T09:24:33.566229Z. Loops: 1,034,678
Task # 993 in thread ID 1021 done at 2024-02-15T09:24:33.572045Z. Loops: 1,172,157
Task # 994 in thread ID 1022 done at 2024-02-15T09:24:33.576395Z. Loops: 1,067,262
Task # 995 in thread ID 1023 done at 2024-02-15T09:24:33.582312Z. Loops: 1,034,725
Task # 996 in thread ID 1024 done at 2024-02-15T09:24:33.586528Z. Loops: 1,134,316
Task # 997 in thread ID 1025 done at 2024-02-15T09:24:33.592593Z. Loops: 1,112,738
Task # 998 in thread ID 1026 done at 2024-02-15T09:24:34.158249Z. Loops: 6,455,185
Task # 999 in thread ID 1027 done at 2024-02-15T09:24:34.158381Z. Loops: 6,484,593
Task # 1000 in thread ID 1028 done at 2024-02-15T09:24:34.168723Z. Loops: 7,411,728
Demo end at 2024-02-15T09:24:34.168958Z. demoDuration = PT20.392301916S

By the way,  System.currentTimeMillis() was years ago supplanted by Instant.now(). Calling Instant.now captures the current moment with a resolution of microseconds rather than mere milliseconds in Java 9+ on implementations based on OpenJDK code base.
Comment: Personally, I don't agree with your closing comment. If millisecond granularity is enough, using `System.currentTimeMillis()` is good enough and has a lot less overhead than using `Instant.now()`.
Comment: @MarkRotteveel I agree. My comment was intended more generally, thus the use of "By the way". In my version of the Question's code, I used `System.nanoTime` which might have even less overhead than `System.currentTimeMillis`.
Answer: As is, your code does not work because the processor switches away to other threads during the execution of your thread.
One way to get what you want is to do a busy loop and keep checking how much time passed since the last iteration. If it is above a certain threshold, you assume a context switch happened so the time does not count. Example:
long passedTime=0;
long i=0;
long currentTime=System.nanoTime();
while (passedTime<usageTimeInMillis*1000*1000) {
    long nextTime = System.nanoTime();
    long increase = nextTime - currentTime;
    if (increase < 1000*1000) {
        passedTime += increase;
    } else {
        passedTime += Math.min(i>0 ? passedTime/i : 0, increase);
    }
    currentTime=nextTime;
    i++;
}

Also, note that I have used nanoTime to avoid unnecessary inaccuracies due to rounding.
Context switches generally take at least a couple of milliseconds by a large margin and checking the current time, performing a couple of additions, subtractions and conditional jumps takes in the tens of nanoseconds, so that it is clear whether there was a switch or not.
Answer: Another way to think of this problem is not think of the task in terms of threads and cores which java tries to abstract away. Think of it in terms of resources.
You have N resources you want each task to hold a resource for 10 seconds then release it.
A good representation of a resource is a Semaphore. With this we get to explicitly tell java when we want to release a resource. With a thread, either java (virtual threads) or the OS can decide to release a thread and do something else.
You only have to make some minor changes to get the results you expect. One of them being to import java.util.concurrent.Semaphore; then at the beginning of main.
Semaphore cores = new Semaphore(6);
When you create your threads.
threads[i] = new Thread(()->{
   try{
       cores.acquire(1);
       doSomething(10);
   } catch(Exception e){
       throw new RuntimeException(e);
   } finally{
       cores.release();
   }
}

Now when you run the tasks you'll see groups of 6 getting fired off every 10 seconds. These results could vary depending on the actual number of cores and threads.


Display dynamic message for updates/releases on a react redux app

Question: In my react + redux app, I want to dynamically display some notifications/message  about new features/updates as header on our react + redux app. This message to be displayed would be entered as input type text in one of the component (Alert.js) . I capture the entered value as props in this component and pass this props to a child component(Header.js) which just displays the message captured. Then i simply call the child component Header in App.js passing the required props..  The issue i am facing is when the app reloads the component re-renders,  the props value becomes undefined and the message that i want to display in header goes away. How do retain a object's value in store until the entered input value is not changed.  I am new to react and redux. Please help.
Thanks
Answer: You can set up an initial state for your reducer like so
<code>const initialState = {
  message: "Welcome back"
}

const alertReducer = (state = initialState, action) => {
    switch(action.type){
    case "NEW_ACTION":
       return action.payload
    default:
       state
    }
}
</code>
This will give your app predefined data to be used in your components. To have dynamic data that you can preserve though, you're going to have to integrate a database like MongoDB or Firebase. That way you can pull data like "most recent alerts" and etc. Otherwise, there is no way for you to effectively persist data solely on React and Redux. Maybe local storage, but that data will only exist on your computer.
Comment: Thanks @yourfavoritedev for your quick response. That really helped. So you mean for dynamic data i will have to persist the entered input dispatching an action that just stores the entered input in database. And then on page load, dispatch another action that loads the data from database, using store.dispatch. Right?
Comment: @PingPong that is exactly what I mean.


Is it possible to declare a variable in the conditional of an if expression in Rust?

Question: In Go, we can declare a variable inside the conditional of an if expression. This variable will be valid inside the if scope, and not outside of it. For example:
func main() {
    if n := 4; n != 0 {
        fmt.Printf("%d is not zero", n)
    } else {
        fmt.Printf("%d is zero", n)
    }

    fmt.Printf("%d", n) // error, n doesn't exist here!
}

Is there a similar syntax in Rust?
Comment: See also [Possible to combine assignment and comparison in an expression?](https://stackoverflow.com/q/40397672/155423)
Answer: Rust does have if let expressions:
if let n = 4 {}

println!("{}", n); // error: cannot find value `n` in this scope

These are primarily used for pattern matching:
let optional_num = Some(1);

if let Some(num) = optional_num {
    println!("optional_num contained", num);
} else {
    println!("optional_num was None");
}

There is an RFC for if let chains that would allow for something like this:
if let n = 4 && n != 0 {
    println!("{} is not zero", n);
}

println!("{}", n); // error, n doesn't exist here!

However, the variables declared in if let chains are scoped only to the if statement, not the else, so your example would not be possible:
if let n = 4 && n != 0 {
    println!("{} is not zero", n);
} else {
    println!("{}", n); // error, n doesn't exist here!
}

Comment: I don't think your assertions as to the behaviour of `if let` chains is correct, it doesn't match the desugaring provided in the RFC, and doesn't make much sense (as it straight would not work if the pattern were failible and failed).
Comment: @Masklinn Thanks for pointing that out, I updated my answer
Answer: I feel like what you're trying to do in your code more closely aligns with a match statement. Something like this:
match 4 {
    n @ 0 => {
        println!("{} is zero", n);
    },

    n => {
        println!("{} is not zero", n);
    }
}

Or, more generically, if you want to test some arbitrary boolean expression based on n:
match some_expression {
    n if some_boolean_function(n) => {
        println!("{} meets the requirements", n);
    },

    n => {
        println!("{} does not meet the requirements", n);
    }
}

Answer: You can always define a new scope using curly braces:
fn main() {
    {
        let n = 4;
        if n != 0 {
            println!("{} is not zero", n);
        } else {
            println!("{} is zero", n);
        }
    }

    println!("{}", n); // error, n doesn't exist here!
}

If you felt strongly enough about it, you could wrap that in a macro:
macro_rules! thing {
    ($($s:stmt);+ , $e:expr) => {{
        $($s)+
        $e
    }};
}

fn main() {
    thing!(let n = 4, if n != 0 {
        println!("{} is not zero", n);
    } else {
        println!("{} is zero", n);
    });

    println!("{}", n); // error, n doesn't exist here!
}


Why is this section on the measure 'grouped' with a 3?

Question: Beginner warning: this is probably very trivial :-)
I was advised as a beginner to study and play music that I like, so I can see similarities and differences. I a beginner, but very keen you see, however, I have come across a weird kind of 'grouping' and don't quite know why it is there.
Do they change the way in which they are played at all?

Am I being really dumb in not understanding what it is for?
I have to admit, note duration, especially dots and ties is something I am currently trying to learn.
Many thanks
Answer: Those are called triplets. They add up to two of the base value. So triplet quavers add up to one crotchet. (Triplet eighth notes add up to one quarter note).
The rest there would make it especially confusing for a beginner to audiate but fear not. With practice it will become clear.
This is an explanation of triplets and their sound as well as some other things.
EDIT:
No you're not being dumb. It is something that could easily confuse anyone.
In the bars where you have the triplets you notice that there are 6 sets of quarter notes even though it is in 4/4 time. So each set of three is played as two resulting in the 6 notes being played in the same time as 4 would be.
Comment: It doesn't break convention it is the convention. And it has been there for forever. Bars and rhythm are measures of time. The time signature says the value of time in each bar. So 4/4 means 4 quarter note beats per bar. This means that in each bar the equivalent of 4 quarter notes should be played. In this case the first set of three notes are played in the space of two quarter notes. So the equivalent of 2 quarter notes are passed. Then the second set of three does the same. So the same amount of time (4 beats) passes. So it is ok.
Comment: [here](https://www.youtube.com/watch?v=sI3n_35K5F8) is another simpler expanation. Shorter too.
Comment: To your edit: how is it not so that, that is permitted? Does that not just break convention? Have triplets been included in music for sometime now?


Unicorn error while hosting a Rails app with NGINX

Question: All of a sudden my app stopped working and these are the last lines I am getting from
unicorn.log
unicorn worker[0] -D -c /home/deployer/apps/myapp/current/config/unicorn.rb -E production: relocation error: /lib/x86_64-linux-gnu/libssl.so.1.0.0: symbol CRYPTO_memcmp, version OPENSSL_1.0.0 not defined in file libcrypto.so.1.0.0 with link time reference
E, [2013-02-28T18:32:49.240524 #23929] ERROR -- : reaped #<Process::Status: pid 26634 exit 127> worker=0
I, [2013-02-28T18:32:49.240810 #23929]  INFO -- : worker=0 spawning...
I, [2013-02-28T18:32:49.255824 #26647]  INFO -- : worker=0 spawned pid=26647
I, [2013-02-28T18:32:49.256438 #26647]  INFO -- : Refreshing Gem list

and production.log
[...]
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml
Connecting to database specified by database.yml

Last thing I did was a very little and inoffensive cap deploy, after the app stopped working I also try a cap deploy:rollback but the error is still there. I'm new to unicorn, what's going on here please?
Comment: It happened to me today. The problem was a syntax error in a controller. Check out the unicorn.log file.
Answer: Maybe it was some kind of VPS failure, from my admin panel I saw that the CPU usage was at max for no reason, so I shut it down and then restarted it and now it is working again...
Comment: Rebooting isn't really a "solution" -- you don't know what caused the problem (or the CPU spike), so you can't prevent it from happening again...


HTML table to Drupal table

Question: How can I translate this to drupal table?
http://www.bootply.com/sXmuAJQjO4
I know how to do simple tables and the header and first row I can do also with this code:
$title = '

Table Title

';

    $header = array(
        array('data' => ' '),
        array('data' => 'Job Name'),
        array('data' => 'Description'),
        array('data' => 'Provider Name'),
        array('data' => 'Region',),
        array('data' => 'Status'),
    );

    #'data-toggle' => 'collapse'
    $row = array(
        'data' => array(
            array('data' => '<button class="btn btn-default btn-xs"></button>'),
            array('data' => 'OBS Name',),
            array('data' => 'OBS Description'),
            array('data' => 'hpcloud'),
            array('data' => 'nova'),
            array('data' => 'created'),
        ),
        'class' => array('accordion-toggle'),
        'data-toggle' => 'collapse',
        'data-target' => '#demo1',
    );
    $rows[] = $row;

But I can't add the hidden row. Can anyone help me?
Thanks!
Answer: For the hidden row, you need a second table which would look like:
// This is the hidden table
$table_hidden = '
';
$table_hidden .= theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));
$table_hidden .= '
';

$row2 = array(
  'data' => array(
    array(
      'data' => $table_hidden,
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Option 2, a more module-clean way would be to use hook_theme function and create a simple template file where additional markup is placed like so.
function YOURMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'any_name_you_like' => array(
      'template' => 'hiddentable', // This called hiddentable.tpl.php
      'arguments' => array('table' => null),
    ),
  );
}

Then in your page callback or wherever, you would just need to use your declared theme function like so.
$table_hidden = theme('table', array('header' => $header_hidden, 'rows' => $rows_hidden));

$row2 = array(
  'data' => array(
    array(
      'data' => theme('any_name_you_like', array('table' => $table_hidden)),
      'colspan' => '12',
      'class' => array('hiddenRow'),
    ),
    array('data' => 'OBS Name',),
  // more array data here
);

Now in your hiddentable.tpl.php

  <?php print $variables['table']; ?>

Comment: Thanks Leolando Tan. I thought that the first variable you define (the one with the div) could be made in a more drupal way. That was my problem. If it's ok to do it like this or if it's meant to be like this, fine for me :)
Comment: Oh! My bad! I edited my post to add a second option. Please take a look and if it satisfies your need give it an up vote. Thanks! :)
Comment: You're very welcome! Glad to help! :)

HTML table to Drupal table


What does the y-axis of a normal distribution represent?

Question: In a normal distribution ,as far as I know distribution represents frequency of sth.But then how come normal distribution y-axis becomes

If distribution y-axis doesnt represent frequency, the what is central limit theorem.The central limit theorem y-axis represents the frequency of mean samples.Shouldnt it represent the above formula to satisfy a normal distribution
Comment: What? Normal distribution doesn't represent frequency on the y-axis, but rather density. Frequency only works for discrete distributions. CLT is unrelated here.
Comment: You really need to understand probability densities and distribution functions before you can understand what the central limit theorem says
Comment: The central limit theorem says, the sample means frequncy if plotted will follow normal distrbution.So y-axis represents no of samples ryt? or does it represent the above formula?
Comment: No, we use the CLT to estimate the distribution of the mean. But the mean is a continuous variable and so will also be distributed on the real line ${\rm I\!R}$. Which means you will also get a density, not frequency.
Comment: But central limit theorem says we plot frequency in y-axis ryt?
Comment: There are two distinct questions here, so I have provided links to threads that answer each one separately.  There are many other posts on this site that speak to the issues raised in this question: consider conducting a search.
Answer: As you can see from the definition of the normal density, it is not dimension-less, but its measurment unit (dimension in the physical meaning) is the same as that of $1/\sigma$ which in turn is the same dimension as that of $1/x$. Integrating over $f(x)$ yields a dimensionless quantity: the probability of the region of integration.
The y-axis is thus "probabilty per measurement unit of x". This holds for every probability density, not only the normal density.


What is the gradient of $\frac{1}{2}(Ax)\cdot x$ if $A$ is a nonzero symmetric $3\times 3$ matrix

Question:
What is the gradient of $\frac{1}{2}(Ax)\cdot x$ if $A$ is a nonzero symmetric $3\times 3$ matrix?

Apparently the answer is simply $Ax$. Does anyone know why?
Comment: Assume $x$ is a column vector, otherwise it doesn't make sense to multiply matrix to a row vector due to the dimensions mismatch. Then $Ax$ is also a column vector, and again multiplying column vector to a column vector is undefined. You have two options:

1) Make it $\frac 12 (Ax)^T \cdot x$

2) or $\frac 12 (Ax) \cdot x^T$

In first case you'll get a number, so gradient of it will be a row vector. In second case, the product is a matrix, and as far as I remember its gradient is even bigger of a matrix.

In any case, you don't get $Ax$.
Answer: Yes, and it is not specific to the 3 by 3 case, it is any size square symmetric. So, could you please, please, please, actually write out the 1 by 1 case (where $A$ is just a number) and the 2 by 2 case, and write out the value of your expression and find the gradient in these two easy cases.
Comment: +1 Good to see you 'round! And I love your comments & answers (and wit!)
Answer: Claim:
Let $A$ be a $k x k$ square matrix, $x$ be a $k x 1$ column vector, and let $\alpha = (1/2) x
^TAx$ be the quadratic form associated with $A$ and $x$.
Find the gradient of $\displaystyle \alpha = \frac{\partial \alpha}{\partial x} \left(\frac{1}{2} \right) x
^TAx = \frac{1}{2}\left(A + A^T\right)x$.
Furthermore, if $A$ is symmetric, this derivative reduces to $\displaystyle \left(\frac{1}{2}\right) 2 A \cdot x = A \cdot x.$
Why is that last statement true (we were told something about nonzero symmetric matrices)?
Comment: Nice! +1 for good work and for effort!
Answer: Here is another way to see it:
Let $\phi(x) = \frac{1}{2} \langle Ax,  x \rangle$.
Then
\begin{eqnarray}
\phi(x+\delta) &=& \frac{1}{2} \langle A(x+\delta),  x+\delta \rangle \\
&=&  \frac{1}{2} \left( \langle Ax,x \rangle + \langle Ax,\delta \rangle + \langle A \delta,x \rangle + \langle A\delta,  \delta \rangle \right) \\
&=&  \phi(x) + \frac{1}{2} \left(   \langle Ax,\delta \rangle + \langle  \delta,A^T x \rangle + \langle A\delta,  \delta \rangle \right) \\
&=&  \phi(x) + \frac{1}{2} \left(   \langle Ax,\delta \rangle + \langle  A^T x, \delta \rangle + \langle A\delta,  \delta \rangle \right) \\
&=&  \phi(x) +    \langle \frac{1}{2} (A+A^T)x,\delta \rangle  + \langle A\delta,  \delta \rangle
\end{eqnarray}
It follows from this (since $|\langle A\delta,  \delta \rangle| \le \|A\| \|\delta \|^2$) that $\nabla \phi(x) = \frac{1}{2} (A+A^T)x$.


Do we need to increment thread-local variable atomically?

Question: Below is a function from LLVM's libcxxabi:
void *__cxa_current_primary_exception() throw() {
    //  get the current exception
    __cxa_eh_globals* globals = __cxa_get_globals_fast();
    if (NULL == globals)
        return NULL;        //  If there are no globals, there is no exception
    __cxa_exception* exception_header = globals->caughtExceptions;
    if (NULL == exception_header)
        return NULL;        //  No current exception
    if (!isOurExceptionClass(&exception_header->unwindHeader))
        return NULL;        // Can't capture a foreign exception (no way to refcount it)
    if (isDependentException(&exception_header->unwindHeader)) {
        __cxa_dependent_exception* dep_exception_header =
        reinterpret_cast<__cxa_dependent_exception*>(exception_header);
        exception_header = cxa_exception_from_thrown_object(dep_exception_header->primaryException);
    }
    void* thrown_object = thrown_object_from_cxa_exception(exception_header);
    __cxa_increment_exception_refcount(thrown_object);
    return thrown_object;
}

globals is a thread-local storage variable, and therefore the thrown_object is also specific for a thread. My understanding is that thrown_object is an exception thrown in a thread - each thread may throw its own exception.
But the function __cxa_increment_exception_refcount() performs increment atomically - why? What's the scenario that requires increment to be performed atomically?
Comment: Re, "globals is a thread-local...and therefore the `thrown_object` is also specific for a thread." I don't know LLVM's run-time support libraries, and I don't know whether or not `*thrown_object` could be shared with other threads, but you can't tell just from looking at the code sample above. The `__cxa_current_primary_exception()` function finds `*thrown_object` by following a chain of pointers, and just because `globals` itself is a thread local variable, that doesn't prove that the object it points to is not shared, and it doesn't prove anything about other objects further along the chain.
Answer: You can call std::current_exception and get a smart-pointer to the exception:

std::exception_ptr is a nullable pointer-like type that manages an exception object which has been thrown and captured with std::current_exception. An instance of std::exception_ptr may be passed to another function, possibly on another thread, where the exception may be rethrown and handled with a catch clause.
...
std::exception_ptr is a shared-ownership smart pointer.

Because std::exception_ptr can be passed to another thread the reference counter maintenance must use atomic increment/decrement.
The reference counter is embedded into the exception object, like for boost::intrusive_ptr and unlike std::shared_ptr.
Comment: Thank you, but I didn't get when we need atomic increment. Let's suppose that we caught an exception in a worker-thread and saved it in a global std::exception_ptr - do we need atomical increment in this scenario? Let's further suppose that we're passing saved global exception_ptr into another thread - do we need atomic increment now?
Comment: @embedc In case when _we caught an exception in a worker-thread and saved it in a global `std::exception_ptr`_ the worker thread may have a local copy that gets eventually destroyed and another thread may make another copy of the global one, simultaneously incrementing and decrementing the same reference counter. This is why the reference counter must be thread safe.


Likelihood of Poisson R.V with Bayesian Inference

Question: In Bayesian Inference.
Say I have a Poisson distributed R.V. K which denotes the observed number of some event over a specified time period.
The rate of this Poisson distribution is given by the linear model (with parameter vector $w \in \mathbb{R}^{D+1}$) as:
$$f(x;w) = w_0 + w_1x_1 + ... + w_Dx_D$$
The likelihood of the n'th data is given by:
$$p(k_n|x_n,w) = \frac{f(x_n;w)^{k_n} e^{-f(x_n;w)}}{k_n!}$$
For values of $k_n \geq 0$, where values $k_n < 0 = 0$.
How would I go about computing the likelihood of an entire data set given the above setup?
If I assume that $k_n$ is conditional independent given $x_n$ I would be able to compute the likelihood over the entire data set as the product of each individual data-point:
$$p(k|x;w) = \prod_{n=1}^n \frac{f(x_n;w)^{k_n} e^{-f(x_n;w)}}{k_n!}$$
Which could also be expressed as:
$$p(k|x;w) = \frac{f(x_n;w)^{K} e^{-n \cdot f(x_n;w)}}{k_1!k_2!...k_n!}, K = \sum_{i=1}^n k_i$$
But I am uncertain if this likelihood is correct (for the entire dataset) as I fail to incorporate the constraint $k_n < 0 = 0$ in the above.
So can I assume that the above likelihood indeed cover the entire dataset, or should I add the constraint saying this is only true for $k_n \geq 0$? And that any datapoints $k_n < 0$ would just be 0, and thus not change the product of likelihoods?
So what I really struggle with, is if I should somehow define for the constraint $k_n < 0$ what influence that particular data-point has on the likelihood estimation above (as this is a product of likelihoods, if $k_n < 0$ would equal $0$ then the product would also equal to $0$, as we would have some products of likelihood values times $0$).
Comment: What, exactly, is your question?
Comment: @jbowman if the above likelihood for the entire dataset is correct. What I am given is the likelihood of the nth data, I want the likelihood for the entire dataset. What I am uncertain about is whether or not the above computation is correct, as I feel like I am missing the constraint $k_n < 0 = 0$ in my likelihood expression?
Comment: @jbowman I edited the question a bit to make it more clear in the original post above.
Answer: If I understand your question correctly, your constraint is implied when you take the product to get the complete likelihood.  You could write it again explicitly if you like, which would be the best approach to avoid ambiguity. (But it is generally implied given we are talking about a Poisson likelihood.) It will be true that for any data point $k_i < 0$, the mass function will be zero too (I think you meant  $k_i$ rather than  $k_n$ -- the last data point.)
Comment: Thanks, that clarifies it for me. I was not sure if it indeed was the case that it would be implied, and that I could just compute the likelihood over the entire dataset as a product of $k_i \geq 0$. My concern was just how I would go about denoting this, if it would be sufficient to state that in case any points $k_i < 0$, then the mass function itself would also become $0$.


É possível criar um servidor remoto com MongoDB? De que maneira?

Question: A minha dúvida, para ser mais claro, se trata em criar um servidor com mongodb em uma hospedagem cloud (por exemplo) e acessa-la através de um outro servidor.
Exemplo:
Tenho uma app mobile.
Hospedei meu mongoDB numa hospedagem cloud (ubuntu).
Quero conectar minha app ao db no servidor cloud.
Isto é possível? De que maneira?
Eu estou ingressando neste aprendizado e a minha dúvida foi justamente criar um servidor com MongoDB de uma maneira que eu poderia acessa-lo remotamente.
Fora do "localhost", entendem? Diferente de todos os tutoriais que eu vi.
Answer: Desconsiderando as questões de firewall e segurança, a lógica para a conexão remota de um MongoDB para um MySQL, por exemplo, é a mesma.
No seu terminal, por sua vez, você vai usar o seguinte fragmento para fazer a conexão:
./mongo 192.168.0.1:27017

Se o IP ou o endereço do servidor estiver disponível e dentro dos conformes, a conexão vai ser feita com sucesso.
Em outras palavras, você vai levantar o banco de dados no seu cloud que está rodando fantasiosamente sobre o IP 22.214.171.124. Então, pra acessar esse "driver", você precisa somente apontar o acesso à 22.214.171.124. Por exemplo:
./mongo 220.127.116.11

Tecnicamente falando, se você tem uma aplicação, usará este endereço de IP para indicar onde o banco está localizado.


Parse error: syntax error, unexpected '$erro' (T_VARIABLE) in C:\xampp\htdocs\HITSS\cadastrar.php on line 26

Question: Estou com o erro do título no meu código, será que alguém pode me dar uma luz?
<?php $erro = array('1');

include("conexao.php");

    if(isset($_POST['Entrar'])) {

        //1 - REGISTRO DOS DADOS

        if(!isset($_SESSION))
            session_start();

        foreach ($_POST as $chave=>$valor) {
            $_SESSION[$chave] = $mysqli -> real_escape_string($valor);

        //2 - VALIDAÇÃO DOS DADOS

        if(strlen($_SESSION['login']) == 0)
            $erro[] = "Preencha a senha.";

        if(strlen($_SESSION['nome']) == 0)
            $erro[] = "Preencha o nome.";

        if((substr_count($_SESSION['email'], '@') != 1 || substr_count($_SESSION['email'], '.') < 1 || substr_count($_SESSION['email'], '.') > 2)
            $erro[] = "Preencha o e-mail corretamente.";

        if(strlen($_SESSION['nivel'] == 0)
            $erro[] = "Preencha o nivel.";

        if(strlen($_SESSION['cargo']) == 0)
            $erro[] = "Preencha o cargo.";

        if(strlen($_SESSION['nascimento']) == 0)
            $erro[] = "Preencha a data de nascimento.";

        if(strlen($_SESSION['admissao']) == 0)
            $erro[] = "Preencha a data de admissão.";

        if(strlen($_SESSION['senha']) < 8 || strlen($_SESSION['senha']) > 16)
            $erro[] = "Preencha a senha.";

        if(strcmp($_SESSION['senha'], $_SESSION['conf_senha']) != 0
            $erro[] = "Opa, as senhas estão diferentes.";

        //3 - INSERÇÃO NO BANCO

        if(cont($erro) == 0) {

            $sql_code = "INSERT INTO users (
                login,
                nome,
                email,
                nivel,
                cargo,
                dat_nasc,
                dat_adm,
                foto)
                VALUES(
                '$_SESSION[login]',
                '$_SESSION[nome]',
                '$_SESSION[email]',
                '$_SESSION[nivel]',
                '$_SESSION[cargo]',
                '$_SESSION[nascimento]',
                '$_SESSION[adimissao]',
                '$_SESSION[foto]',
                '$_SESSION[senha]'
                )";
            $confirma = $mysqli- >query($sql_code) or die($mysqli- >error);

            if($confirma) {
                unset($_SESSION[login],
                $_SESSION[nome],
                $_SESSION[email],
                $_SESSION[nivel],
                $_SESSION[cargo],
                $_SESSION[nascimento],
                $_SESSION[adimissao],
                $_SESSION[foto],
                $_SESSION[senha]);

                echo "<scrip> location.href='user_cadastro.php';</script>"
            }
            else {
                $erro[] = $confirma;
            }

        }
        else {
            foreach ($erro as $valor) echo "div class='erro'>"; echo "
"; "$valor
";
        }

    }

?>

Comment: Faltou `;` nessa linha? `echo " location.href='user_cadastro.php';"` ?
Answer: Você esqueceu de fechar alguns parêntesis. Veja as linhas abaixo:
Linha 26:
if((substr_count($_SESSION['email'], '@') != 1 || substr_count($_SESSION['email'], '.') < 1 || substr_count($_SESSION['email'], '.') > 2))
    $erro[] = "Preencha o e-mail corretamente.";

Linha 29:
if(strlen($_SESSION['nivel'] == 0))
    $erro[] = "Preencha o nivel.";

Linha 44:
if(strcmp($_SESSION['senha'], $_SESSION['conf_senha']) != 0)
     $erro[] = "Opa, as senhas estão diferentes.";

Já na linha 49, a função cont não existe. Provavelmente, você quer usar a função count, que serve para contar os itens de um array.
 if(count($erro) == 0) {

Linha 73, não use espaços no Object Separator
  $confirma = $mysqli->query($sql_code) or die($mysqli->error);

Na linha 86, você não usou ; no final da sentença:
 echo "<scrip> location.href='user_cadastro.php';</script>";

E, por fim, você não fechou o if que abriu na linha 6.
Com toda sinceridade, aconselho que você estude a melhor a sintaxe da linguagem, para não ficar perdido.
Dica: Use um editor de texto ou IDE que faça um lint do seu código, para saber se ele tem erro de sintaxe.
Para descobrir o erro, eu usei o site PHP Sandbox
Comment: Além de faltar um `;` na linha 85 e na linha 94 possuir um `foreach` mal formatado, com três instruções sem estar limitada por chaves e uma *string* perdida, provavelmente porque faltou um `echo` (e um elemento `` sem o `<` do início, que não é problema no PHP), e a ordem dos valores não faz muito sentido - colocar o texto de erro fora do elemento.


Why is my pre-built cloud foundry node app trying to fetch modules that are already in node_modules?

Question: I have a pre-built node app that must not attempt to access the network if npm install is run prior to startup - the intent is for everything to already be present in the node_modules directory. It is being deployed in a cloud foundry environment.
This is not a proxy problem - there must be no attempt to access registry url's during cloud foundry app staging. I'm looking for ideas why it's trying to do this.
When this app is deployed to cloud foundry, even though it detects the presence of the node_modules directory during staging, it still tries to retrieve basic dependency modules (like @node/types) that are already present in node_modules, and of course it times out trying to reach a registry that is not permitted in these environments. There are hundreds of other dependencies that it does not attempt to retrieve, but for some reason it thinks it does need some modules. For example:
   2021-03-17T16:29:57.71-0700 [STG/0] OUT        Installing any new modules (package.json + package-lock.json)
   2021-03-17T16:32:31.78-0700 [STG/0] OUT npm ERR! code ECONNREFUSED
   2021-03-17T16:32:31.78-0700 [STG/0] OUT npm ERR! errno ECONNREFUSED
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR! FetchError: request to https://<registry-fqdn>/@types%2flong failed, reason: connect ECONNREFUSED 10.x.x.x:443
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at ClientRequest.<anonymous> (/tmp/contents784086672/deps/0/node/lib/node_modules/npm/node_modules/node-fetch-npm/src/index.js:68:14)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at ClientRequest.emit (events.js:315:20)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at TLSSocket.socketErrorListener (_http_client.js:469:9)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at TLSSocket.emit (events.js:315:20)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at emitErrorNT (internal/streams/destroy.js:106:8)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at processTicksAndRejections (internal/process/task_queues.js:80:21)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!  FetchError: request to https://<registry-fqdn>/@types%2flong failed, reason: connect ECONNREFUSED 10.x.x.x:443
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at ClientRequest.<anonymous> (/tmp/contents784086672/deps/0/node/lib/node_modules/npm/node_modules/node-fetch-npm/src/index.js:68:14)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at ClientRequest.emit (events.js:315:20)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at TLSSocket.socketErrorListener (_http_client.js:469:9)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at TLSSocket.emit (events.js:315:20)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at emitErrorNT (internal/streams/destroy.js:106:8)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at emitErrorCloseNT (internal/streams/destroy.js:74:3)
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!     at processTicksAndRejections (internal/process/task_queues.js:80:21) {
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!   type: 'system',
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!   errno: 'ECONNREFUSED',
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!   code: 'ECONNREFUSED',
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!   parent: 'app'
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR! }
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR!
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR! If you are behind a proxy, please make sure that the
   2021-03-17T16:32:31.79-0700 [STG/0] OUT npm ERR! 'proxy' config is set properly.  See: 'npm help config'
   2021-03-17T16:39:12.54-0700 [STG/0] OUT npm ERR! A complete log of this run can be found in:
   2021-03-17T16:39:12.54-0700 [STG/0] OUT npm ERR!     /home/vcap/.npm/_logs/2021-03-17T23_32_31_800Z-debug.log
   2021-03-17T16:39:12.56-0700 [STG/0] OUT        **ERROR** Unable to build dependencies: exit status 1
   2021-03-17T16:39:13.07-0700 [STG/0] ERR Failed to compile droplet: Failed to run all supply scripts: exit status 14
   2021-03-17T16:39:13.09-0700 [STG/0] OUT Exit status 223
   2021-03-17T16:39:13.28-0700 [STG/0] OUT Cell 5cee670a-6f6c-4510-a274-5584f197038c stopping instance 59dda306-be2f-4d08-830c-77c08ffab3f5
   2021-03-17T16:39:13.28-0700 [STG/0] OUT Cell 5cee670a-6f6c-4510-a274-5584f197038c destroying container for instance 59dda306-be2f-4d08-830c-77c08ffab3f5
   2021-03-17T16:39:13.76-0700 [API/1] ERR Failed to stage build: staging failed

Any ideas?
Edit #1
Other facts:

the app is pushed as a zip archive
the zip file system includes the node_modules directory resulting from an npm install command run during the "build" to construct the zip
the zip file system includes package-lock.json (from source)
there is no .cfignore file anywhere in the zip archive
the zip 'build' used to be taking place on a windows machine, and did not previously have this problem when subsequently pushed to cf
the zip 'build' recently migrated to a gitlab ci runner from a k8s cluster, which may be using a centos-derived image
the buildpack version is 1.7.32
the version of node (14.14.0) on the build machine matches the version used by the buildpack, but the npm version (7.6.1) does not (buildpack uses 6.14.8)
changing the build image where the zip is assembled to Ubuntu Bionic Beaver (18.04.4 LTS) makes no difference
Answer: Not 100% sure this will resolve the issue, but here's what I've seen commonly trip people up trying to vendor Node.js dependencies:
First, review the instructions from the docs: https://docs.cloudfoundry.org/buildpacks/node/index.html#vendoring

Run npm install (you've done this)
Make sure you have a package-lock.json file (you probably have this). That locks in the versions to use and should guarantee what's in node_modules/ matches what will be installed. If you don't have this, you'll see Warning: package-lock.json not found. output from the buildpack.
Make sure you're pushing up package.json, package-lock.json, and the full node_modules/ directory, along with all your application code.

These are not documented, but some tips from what I've observed working with others on this:

Make sure you don't have a .cfignore file, as that could accidentally cause node_modules/ to not be pushed. You can typically tell if node_modules/ is not being pushed because the number of files & size of what is being pushed will be much, much larger with this. You will also see the message It is recommended to vendor the application's Node.js dependencies if the node_modules/ directory doesn't exist.

When you run npm install locally, you need to be running it in an Ubuntu Bionic VM or container. This is because NPM will often install modules that require native code. It will automatically handle this, but what's in node_modules/ is specific for the OS & architecture where you run npm install. Thus If you run npm install on a non-Ubuntu Bionic OS (say Windows or MacOS), it will compile the native code for your local machine. When you push this up, it won't match and NPM will try to reinstall the package which can trigger access to the Internet.

Make sure you're using the latest Node.js buildpack & Node.js version as possible. It always helps to have the latest code with bug fixes.

NODE_ENV=production will be set by the buildpack, and this can sometimes cause difference in behavior. It also skips installing dev dependencies. Not likely the issue here, but worth mentioning as this trips up some people.
Comment: thank you for the detail here - i'm most suspicious now of the difference in the build environment where the npm install is run
Comment: it's looking like the problem is coming from mismatched npm versions. if i re-generate package-lock.json and run the build using an npm version that matches what the buildpack uses, the problem goes away
Comment: Interesting, I've not seen that before. Thanks for sharing
Comment: This is an expected behavior as the app is recompiled/repackaged in a droplet by the used builpack while staging. You could run "cf buildpacks" to check the available buildpacks and specify the one which should be used with "cf push -b". If you don't find a proper version of the buildpack for your app, you can also use a url to specify a custom buldpack to be used in the staging process as described on https://cli.cloudfoundry.org/en-US/v7/push.html
Comment: in this case, it's just that the range of npm versions that our site's buildpack includes for offline usage doesn't include the version we were using for the 'build'. nothing about the buildpack is allowed to be retrieved from external networks, so it's just a matter of getting our cf infrastructure updated
Answer: This problem turned out to be caused by mismatched npm versions on the machine where the package-lock.json file is generated, the machine where the node_modules directory is populated for inclusion in the zip distribution (npm v7.x), and what the cloud foundry build pack is using (npm v6.x).
Changing the dev and build machines to use npm v6.x to generate both the package-lock.json file and populate the node_modules directory resulted in a successfully-vendored nodejs app.


Changing image tags and name with kustomization.yaml

Question: According to the official documentation I should be able to easily override the tags and name of my docker images using some nifty kustomization syntax. I have tried to reproduce this.
In my deployment.yaml I have the following:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    service: my-app
  name: my-app
spec:
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        service: my-app
    spec:
      imagePullSecrets:
      - name: my-docker-secret
      containers:
      - name: my-app
        image: the-my-app
        imagePullPolicy: Always
        ports:
        - containerPort: 1234
      restartPolicy: Always

In my kustomization.yaml I have the following:
bases:
- ../base
resources:
- deployment.yaml
namespace: my-namespace

images:
- name: the-my-app
- newName: my.docker.registry.com/my-project/my-app
  newTag: test

However, when I do this:
kubectl apply -k my-kustomization-dir

and wait for the deployment to spin up, and later do
kubectl describe pod/my-app-xxxxxxxxx-xxxxx

The events looks like this:
Events:
  Type     Reason                  Age                From                                              Message
  ----     ------                  ----               ----                                              -------
  Successfully assigned my-namespace/my-app-xxxxxxxxxx-xxxxx to default-pool-xxxxxxxxxx-xxxxx
  Normal   Pulling                 2s                 kubelet, default-pool-xxxxxxxxxx-xxxxx  pulling image "the-my-app"
  Warning  Failed                  0s                 kubelet, default-pool-xxxxxxxxxx-xxxxx  Failed to pull image "the-my-app": rpc error: code = Unknown desc = Error response from daemon: pull access denied for the-my-app, repository does not exist or may require 'docker login'
  Warning  Failed                  0s                 kubelet, default-pool-xxxxxxxxxx-xxxxx  Error: ErrImagePull
  Normal   BackOff                 0s                 kubelet, default-pool-xxxxxxxxxx-xxxxx  Back-off pulling image "the-my-app"
  Warning  Failed                  0s                 kubelet, default-pool-xxxxxxxxxx-xxxxx  Error: ImagePullBackOff

Indicating that this did not work as expected (it tries to pull the original name specified in deployment.yaml).
So my question is, what am I doing wrong here?
Comment: 1. can you reach your docker registry from cluster? 2. What version of Kustomize are you using 2 or 3?
Answer: You have to remove "-" in newName line under the images section. It should be like this, it is worked.
 images:
 - name: the-my-app
   newName: my.docker.registry.com/my-project/my-app
   newTag: test

Comment: I discovered this just minutes after posting original question. Thanks!
Answer: You can run kustomize build my-kustomization-dir to check if the image is replaced or not in the yaml file.This command lets you see what will be applied in your cluster.


Else vs new IF - Readability and Performance

Question: I'm working in C# using Visual Studio and have been going over my code trying to improve its readability. I came across this site, that lists 15 best practices. #7 - Avoid Deep Nesting, it talks about If statements and says instead of using Else, make another If statement.
This got me wondering about the difference in the instructions between the two. Would using additional If statements cost more performance than just using Else?
Any advice would be appreciated
Answer: The number of conditions evaluated in either case is the same, the only difference is the nesting. There will most likely be no noticeable difference in performance between the two, and there are different opinions about which one is "better" from a readability and best-practice point of view.

In the first example, each condition is evaluated until one returns false, unless they're all true, in which case the middle (most nested) if block will run.
In the second example, the inverse of each condition is evaluated until one returns true, unless they're all false, in which case the last if block will run.

Another way to write your test method to avoid nesting (depending on the actual language) is to combine the conditions with the '&&' operator
, which will evaluate them in order until one of them returns false (and if they're all true, then the code in the if block will run):
// Combine the conditions with '&&', which will evaluate
// evaluate them in order until one of them returns false
if (is_writable($folder) &&
    $fp = fopen($file_path, 'w') &&
    $stuff = get_some_stuff() &&
    fwrite($fp,$stuff))
{
    // ...
}
else
{
    return false;
}


How do I make a web interface for a socket server

Question: I've got a socket server running (it's something that's basically like a chat server).  Users can telnet into it, but I'd like to make a web interface.  This is the first time I've ever done something like this, so I'm not really sure where to start.  A few thoughts I've had:

Have some server-side Python (or PHP) on my webserver, which accesses the socket server.  I think I know enough about sockets to have Python interact with the server, but how do I go about getting the website that the user sees to update in real time?  Should I just have the website refresh few seconds?  I would prefer to do things this way if I can figure out how.
Write a Java applet that interacts with the socket server, and embed the applet in the website.  I would have to re-learn a language that I haven't touched in years, but my main goal here is learning -- so that wouldn't be such a bad thing.  The main problem I have with this is that it requires end users to have Java installed on their computers, which I'd rather not do.

Is one of these two solutions the right way to go?  Anybody know where I can find a good tutorial to get started?
Edit:  There's no real security concerns with exposing the server to the internet.
Comment: Is there any security concern exposing the "socket server" to the internet?
Answer: Easiest would be to use Python and HTTP::Server.  To make pages update automatically just add Meta refresh to your browser.  Or use AJAX to retrieve just the updated portions of your pages.


Determine whether $\int^{1/2}_0\frac{1}{\sin x\cdot \ln x}dx$ is convergence, absolute convergence or divergent.

Question: I'm trying to determine whether $\int^{1/2}_0\frac{1}{\sin x\cdot \ln x}dx$ is convergence, absolute convergence or divergent.
Let $f(x) = \frac{1}{\sin x\cdot \ln x}$, $f(x)< 0$ for $(0,0.5]$.
Therefore I assume I need to work with $-f(x) \ge 0$ in this question.
I'm trying to use the comparing rule without success to solve this.
I thought of using the function $h(x) = \frac{-1}{\ln x}$ which holds $f(x)>g(x)$ in the question's interval, although that didn't get me anywhere.
What are my options here?
Answer: $\sin{x}<x$ for $0<x<\pi/2$ (draw a picture to see this). So
$$ \frac{1}{\sin{x} \cdot (-\log{x})} >\frac{1}{x \cdot (-\log{x})}, $$
and this has antiderivative $-\log{(-\log{x})}$. This is finite when $x=1/2$ and diverges for $x \to 0$, so the original integral diverges.
Comment: The original integral is an improper integral because the integrand is unbounded as $x \to 0$, so you have to treat it as $\lim_{a \to 0}\int_a^{1/2}$. I have shown that $\int_a^{1/2} \frac{dx}{-\sin{x}\log{x}}$ is larger than an integral that can be evaluated exactly: $$\int_a^{1/2} \frac{dx}{x(-\log{x})} = \log{(-\log{a})}-\log{(-\log{(1/2)})}, $$ which diverges as $a \to 0$.
Comment: I'm not quite sure what you mean. $\log{x}$ is negative for $0<x<1$, so $-\log{x}$ is positive. Showing that $f(x) \to -\infty$ is the same as showing that $-f(x) \to +\infty$.
Comment: Is this advanced material? I'm not familiar with the antiderivative explanation. We have only learnt the comparing rule, and the theory of Derichlet and the theory of Cauchy's in class
Comment: Although those functions are negative. Therefore don't we need to examine the opposites, which are positive and: $\frac{-1}{\sin x \cdot(-\log x)} <\frac{-1}{x\cdot (-\log x)}$? For those functions the comparing rule doesn't neccessairly work


Does the team with the extra rest day perform better?

Question: In the World Cup 2014, the semi-finals were held on 8th/9th July, and the final will be on 13th July. This gives Germany an extra day to rest/prepare compared to Argentina.
This has been mentioned by the Argentinian coach, Alejandro Sabella:

Some of our players are sore, beaten, tired - the results of a war, so
  to speak. We have a final to play, with one day less to prepare and
  against a team like Germany, but with work, humility and seriousness,
  we'll do all we can to make it all the way to the top

Statistically, based on previous matches/tournaments, is there a proven advantage in having the extra preparation time?
Comment: From a quick wikipedia scan of World Cup Finals it seems the semifinals of '94, '86 and before were held on the same day, and since '90 the team with 5 rest days always **lost** to the team with 4 rest days except in 2006, where the final ended in a draw after extra time (with the "more rested" Italians winning the penalty shootout).
Comment: If the final were on the 10th, Germany would definitely have the edge. I'm not sure if there's such a difference, or any difference at all if we extend the delay to 5/4 days.
Comment: ^Seems like a solid enough response to be an answer, @arne.b
Answer: 1994 and before, World Cup semifinals often took place on the same day, so one team had only a few hours more preparation time than the other. When semifinals did not take place on the same day, the team with the extra rest day most often lost. Here is a list with the team with 5 days between semifinal and final first, team with 4 days second:
<code> 1966: West Germany - England      2-4 aet
 1990: Argentina    - West Germany 0-1
 1998: Brazil       - France       0-3
 2002: Germany      - Brazil       0-2
*2006: Italy        - France       1-1 aet (4-3)*
 2010: Netherlands  - Spain        0-1 aet
*2014: Germany      - Argentina    1-0 aet*
</code>
Only twice did the team with more preparation time win, and this team did not win in regular time.  The latter instance of the two also seems to be the only time when the later semifinal went into extra time while the earlier one did not.
The very first world cup final was four and three days, resp., after the semifinals, and also won by the team with fewer time to prepare.
<code>1930: Argentina    - Uruguay   2-4
</code>
Interesting side observation: The third place match was won by the team in the same semifinal as the eventual champion every time except 1990 (host Italy came third after being knocked out by eventual final loser Argentina) and 2014 (Netherlands, despite professing lack of motivation beforehand, beat Brazil, who had apparently not recovered from a severe semifinal loss against eventual champion Germany).
While these may not be enough observations to establish that less preparation time is actually useful, one can likely rule out a significant advantage. The results of the four most recent European Championships and Copa Américas is in fact even: 2 wins each for the team from the earlier semifinal, 2 for the one from the later one.
Comment: Good answer! Would have accepted earlier, but was in too much of a rush, betting my life savings on a win for Argentina ;-)
Comment: It might be worth adding to this answer that both these trends were broken in this year's World Cup final matches, now that those matches have been played.


Give the initial value ordinary differential equation that $y(t)$ solves

Question:
Let $x^{\prime}(t)=F(x(t), t) ;$ $ x\left(t_{0}\right)=x_{0} .$ Give the
  IV ODE that $y(t)=x\left(t+t_{0}\right)$ solves.

I am not sure how to approach this mainly because I am not sure exactly what it is that this problem is asking.
Comment: Looks to me like you're being asked to come up with an ODE for $y$ in terms of $x$ and $F$.
Comment: @amd I do see that. Any chance you could give a hint as to how to start?
Comment: Have you tried differentiating $y(t)$?
Comment: $y'(t)=x'(t+t_0)$ and also $y(0) = x(t_0)=x_0 $?
Answer: You are given that
$$x^{\prime}(t)=F(x(t), t) , ~~x\left(t_{0}\right)=x_{0}\tag{1}$$
and you have found that
$$y'(t)=x'(t+t_0),~~y(0)=x(t_0)=x_0\tag{2}$$
therefore by $(1)$
$$y'(t)=x'(t+t_0)=F\big(x(t+t_0),t+t_0\big)$$
Comment: I didn't think it would be this trivial. Sometimes it seems like the hardest problems are the trivial ones
Answer: The problem is asking for an IVP, that is, an ordinary differential equation of the given form, with an initial condition of the given form, whose solution is a translate of the solution to the given equation. In other words, they want you to perform $t\mapsto t+t_0.$


Feature importance/model exploration in a large survival model

Question: I've built very-well performing survival model (weibull proportional hazards model for interval censored data, modelled with IcenReg) with many covariates, some interaction terms and some splines. The model's coefficients are very hard to interpret, if not impossible- there's a lot of collinearity between the variables too.
I would like to show how the model makes decisions- e.g. how to split the data to get good separation of predicted risk?
My initial thoughts were decision trees- and they work to an extent. I get 4 sensible levels out of the tree if i play around with rpart::rpart.control, but it only splits according to three variables... What can I do to show how the model makes its predictions?
Answer: "Feature importance" isn't as well defined as you might hope. There are ways to evaluate the contributions of predictors to a model fit by maximum likelihood, like your icenReg Weibull model, but they typically don't extend well to new data.
For a predictor included in multiple coefficients, like a continuous spline fit, a multi-level categorical predictor, or a predictor involved in interactions, you can do a joint Wald test on all the coefficients involving it. That's sometimes called a "chunk test." That test uses the coefficient estimates and (the inverse of) the corresponding part of the coefficient variance-covariance matrix to evaluate whether any of the coefficient values is significantly different from 0. This answer provides some detail that you should be able to adapt to the coefficients (coef(fit)) and the variance-covariance matrix (vcov(fit) of your model.
The resulting test statistic under the null hypothesis is distributed as chi-square with a number of degrees of freedom equal to the number of coefficients. As the expected value of the statistic under the null equals the number of degrees of freedom, the chi-square statistic for the "chunk test" on the predictor, minus the number of degrees of freedom, is a reasonable choice for an overall estimate of a predictor's contribution to the model.
As Frank Harrell discusses in Section 5.4 of Regression Modeling Strategies, however, the rankings of predictors aren't typically stable over multiple data samples. Even models of repeated bootstrap samples from the same data set can provide wildly different "feature importance" rankings. Try that on your own data and modeling process.
If some of your variables are highly collinear, you might consider re-formulating your model to combine sets of highly related variables into single predictors for the model first. If you do that without considering the associations of those variables with outcome, you don't affect the interpretation of p-values and the like from the resulting model, while you cut down on the number of degrees of freedom used up in the modeling.
If there's a reasonable biological/clinical argument for combining multiple variables this way, that approach also simplifies model interpretation. Think, for example, about the "Tumor, Node, Metastasis" combinations used to evaluate overall disease Stage in cancer. Harrell discusses the principles of this "data reduction" in Section 4.7 of Regression Modeling Strategies and illustrates application later in the document.
The above assumes that you have a validated model to start with. With "many covariates, some interaction terms and some splines," there's a risk of overfitting the data unless you have a correspondingly large number of events in your data. It's the number of events, not the number of total cases, that provides power to a survival model.
As I recall, your data set has a large number of cases but with only a small percentage having the event. You typically need on the order of at least 15 events per coefficient that you are estimating to avoid overfitting. If your model is overfit, then any "feature importance" culled from it won't extend well to new data at all, even beyond the random-sampling and collinearity issues discussed above.