State of affairs of WebAssembly MVP in browsers

Question: https://webassembly.github.io/demo/ says: "Full execution semantics implemented." sounds like MVP is done, but what exactly is missing or am I doing anything wrong?
WAST:
(module
    (memory 1)

    (export "growMemory" $growMemory)
    (func $growMemory (param $0 i32) (result i32) (grow_memory (get_local $0)))

    (export "getMemorySize" $getMemorySize)
    (func $getMemorySize (result i32) (memory_size))
)

JS-Code:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'build/test.wasm', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
    var module = Wasm.instantiateModule(new Uint8Array(xhr.response));
    console.log(module.exports.getMemorySize());
    console.log(module.exports.growMemory(1));
    console.log(module.exports.getMemorySize());
};
xhr.send(null);

Chrome Canary loads the WASM file but grow_memory seems to be unimplemented:
65536
0
65536

And Firefox Nightly fails at loading:
TypeError: wasm validation error at offset 124: bad expression code

Also the page size seems to be 0x10000 instead of 0x1000. But I can't find it in the design or spec.
Answer: March 2017 update:
WebAssembly MVP has reached consensus:

WebAssembly CG members representing four browsers, Chrome, Edge, Firefox,
  and WebKit, have reached consensus that the design of the initial (MVP)
  WebAssembly API and binary format is complete to the extent that no further
  design work is possible without implementation experience and significant
  usage. This marks the end of the Browser Preview and signals that browsers
  can begin shipping WebAssembly on-by-default. From this point forward,
  future features will be designed to ensure backwards compatibility.
This consensus includes a JavaScript API and binary format
  accompanied by a reference interpreter. You can test out WebAssembly
  today using the Emscripten toolchain by following the developer's guide
  and reading more on MDN.
The next steps will be to form a W3C Working Group, to produce a
  specification for the initial version of WebAssembly, and to continue
  iterating on future features in the current Community Group. To get
  involved, you can join design discussions and contribute to the the
  WebAssembly GitHub project.

The current webassembly.org site documents the following next steps to follow right after MVP:

The WebAssembly community group and contributors plan to:

distill the design
  and spec interpreter repos
  into a single unified specification in the spec
  repo
propose a new charter for a W3C WebAssembly Working Group
graduate the WebAssembly LLVM backend from experimental to stable (and update Emscripten)
prototype additional WebAssembly integration into browser developer tools
Start work on post-MVP features

November 2016 update:
There's currently a browser preview, soliciting developer feedback. From webassembly.org:

The WebAssembly Community Group has an initial (MVP) binary format release candidate and JavaScript API which are implemented in several browsers. The CG is now soliciting feedback from the broader community as part of a Browser Preview period. The tentative goal of the CG is for the Browser Preview to conclude in Q1 2017, though significant findings during the Browser Preview could potentially extend the duration. When the Browser Preview concludes, the CG will produce a draft specification of WebAssembly and browser vendors can start to ship conforming implementations on-by-default.
Developers should be aware that between the Browser Preview and public launch of WebAssembly, there will be at least one breaking change which will require developers to update their toolchain and binaries. These changes will be announced ahead of time and are listed below.
See Getting Started to start experimenting and Feedback for how and where to direct feedback.

Original answer:
We synchronized on feature parity between browsers for the demos and intend to update all browsers + demos in lockstep from now on, towards MVP.
We have something that currently works, but it's not stable. As we work with larger and more diverse codebase we're hoping to kick the tires, see what could be improved, and gain confidence that post-MVP features will be implementable without headache. We also want feedback from developers to make sure what we've build is usable!
It's missing some features such as the API to the Wasm JavaScript object, memory and pointer sharing across Wasm instances. We're also not settled on the binary format, the biggest change for now is going post-order but there are plenty of smaller changes coming.
Browser integration is also lacking: we want to ship with view-source and likely some debugging support. There's also some perf tuning, and plenty of security testing.
To track those issues I recommend looking at the design and spec issue trackers.
On your specific problem, we haven't finished grow_memory in Chrome. Work has started though.
Comment: Thanks for the swift answer, I found the page size issue: https://github.com/WebAssembly/design/pull/442


Ordenação no Crystal Report com sub relatórios

Question: Eu tenho em meu relatório 2 subs relatórios mas eu quero ordenar pelo campo "Aluno" do Main Report mas não estou conseguindo, mesmo eu já trazendo da consulta ele ordenado com eu gostaria.

Eu tentei ordenar pelo Group Section do menu Insert mas também obtive sucesso.
Comment: Tentou ordenar pelo Record (registro) ?
Answer: Olá. Se eu entendi bem, você que ordenar pelo nome do aluno, certo? Nesse caso você deve agrupar pelo nome do aluno, e não pelo UserID.


How to separate columns values to create a new different column

Question: I have a dataframe which looks like this:

It kinda looks like a tuple. But what I want to do is to take all the values after the comma and put them into a new column called otros_casos. Therefore, my new df should look like this:

I don't need those values which have a 3 on it or have a nan. Here is the code I am using:
dic_cont = data.groupby(['resultado']).otro_caso.value_counts()
data_cont = pd.DataFrame([[key, dic_cont[key]] for key in dic_cont.keys()], columns = ['resultado', 'amount'])
data_cont

And here is how dic_cont looks like:

I would really appreciate your help guys. Thanks in advance.
Answer: using .str will unpack tuple
In [32]: df = pd.DataFrame({"resultado":[(1,pd.np.NaN),(1,1),(1,2),(2,1),(2,2),(
    ...: 2,pd.np.NaN),(3,1),(3,2),(3,pd.np.NaN)],"amount":[735709,688554,601864,
    ...: 1055853,693378,596613,196078,182715,122275]})

In [33]:  df['resultado'],df['otros_casos']=df['resultado'].str

In [34]: df = df.dropna()

In [35]: df[df['resultado'] !=3]
Out[35]:
   resultado   amount  otros_casos
1          1   688554          1.0
2          1   601864          2.0
3          2  1055853          1.0
4          2   693378          2.0

Comment: @brenda - yes, problem is solution working until upgrade pandas, then rather not use it.
Comment: I got `FutureWarning: Columnar iteration over characters will be deprecated in future releases.`, what is your pandas version?
Comment: @jezrael, it is `0.25.3`, did not try on the latest version


Is this proof of $\sum_{i = 1}^n a_i^k \leq (\sum_{i = 1}^n a_i)^k$ correct?

Question: I came across the following proof, and although I believe the result, something seems fishy and I can't put my finger on it.  The base case might not be enough, or we might have to consider various $k$ somewhere...or maybe I'm just paranoid !  So, does that make sense ?
Given a sequence $(a_1, \ldots, a_n)$ of positive integers, we show
$$\sum_{i = 1}^n a_i^k \leq (\sum_{i = 1}^n a_i)^k$$
for any positive integers $n$ and $k$, by induction on $n$.
If $n = 1$, then obviously $a_1^k \leq a_1^k$.  So assume truth for values smaller than $n$.  Then
$$
\sum_{i = 1}^n a_i^k = \sum_{i = 1}^{n - 1} a_i^k + a_n^k \\
\leq (\sum_{i = 1}^{n - 1} a_i)^k + a_n^k$$
by induction.  Now, setting $x = \sum_{i = 1}^{n - 1} a_i$ we get
$$(\sum_{i = 1}^{n - 1} a_i)^k + a_n^k = x^k + a_n^k \leq (x + a_n)^k$$
again by induction, and replacing $x$ by its values lets us conclude that
$$\sum_{i = 1}^n a_i^k \leq (x + a_n)^k = (\sum_{i = 1}^n a_i)^k$$
Comment: The case $n=2$ seems to be missing. But it is easy. (But then it all is, imagine expanding.)
Comment: Ah indeed the base case should be $n = 2$.  That's what was missing.  I was aware that this proof was overkill, but I had to determine if it was right or not.  So if nothing else is missing, the case is closed.  Thank you for your answer (you can post this as an answer if you want).
Answer: There is a gap, which is of the same kind as the "all horses are of the same colour" induction "proof." The case $n=2$ was not done, and it is essential for the induction step.
The case $n=2$ can be done using the Binomial Theorem. It can also be done by induction on $k$.
Comment: I don't get it. Why is a base case $n = 2$ necessary? The proof seems complete to me.
Comment: @user143882:  First, let us note that the result is clear (Binomial Theorem), so the only issue is a technical one about proof by induction. The point is that  the case $n=2$ has not been proved, since the next to last displayed line uses the case $n=2$. One way to view things is that if $k=4$, the case $n=1$ is true even if some of the $a_i$ are negative, while the case $n=2$ is not.
Comment: I think get it now. I was assuming $a ^ 2 + b ^ 2 ≤ (a + b) ^ 2$ had already been proved. You're viewing addition as a special case of sum. I was viewing addition as being defined before sum, and then sum being defined in terms of addition. In my view $a ^ 2 + b ^ 2 ≤ (a + b) ^ 2$ could have been proved before we got to the facts about sum. Maybe my view is the view the OP came across.
Comment: @user143882: Your last comment I think identifies the source of the problem. You are thinking that the induction is being done on the *exponents*. Actually, in the proof the exponent $k$ is fixed, and induction is being done on the number of terms.
Comment: No, I'm aware the proof is by induction on $n$. In the previous comment I meant to write $a ^ n + b ^ n ≤ (a + b) ^ n$, but made a mistake and wrote $2$ instead of $n$.

$$ ∑ _ {i = 1} ^ n a _ i ^ k = ∑ _ {i = 1} ^ {n - 1} a _ i ^ k + a _ n ^ k ≤ \left( ∑ _ {i = 1} ^ {n - 1} a _ i \right) ^ k + a _ n ^ k ≤ \left( ∑ _ {i = 1} ^ {n - 1} a _ i + a _ n \right) ^ k = \left( ∑ _ {i = 1} ^ {n} a _ i \right) ^ k $$
Answer: Alternately let $x_i = \dfrac{a_i}{\displaystyle \sum_{j=1}^n a_j}$, then $0 < x_i < 1$, and $\displaystyle \sum_{i=1}^n x_i = 1$. Thus we have:
$\displaystyle \sum_{i=1}^n x_i^k \leq \displaystyle \sum_{i=1}^n x_i = 1$ since $0 < x_i^k \leq x_i < 1$ for $\forall k \geq 1$


Calculate the trajectory integral given by the equations $x^2+y^2=z^2,y^2=ax$ from the point $(0,0,0)$ to $(a,a,\sqrt{2}a)$

Question:
Calculate the trajectory  integral $$I=\int_{\gamma}zdl$$ where $\gamma$ is a curve obtained by the intersection  of the surfaces given by the equations $x^2+y^2=z^2,y^2=ax$ from the point $(0,0,0)$ to $(a,a,\sqrt{2}a)$

** My attempt **
We need to parametrize the expression, note that the parametrization of $\gamma$ is given by $x=t$,$y=\sqrt{at}$,$z=\sqrt{t^2+at}$ where $t\in [0,a]$.
Now we find the derivatives of our parametrization $x^{\prime}=1$,$y^{\prime}=\frac{a}{2\sqrt{at}}$,$z^{\prime}=\frac{2t+a}{2 \sqrt{t^2+at}}$
now note that our parametrization is $C:[0,a]\rightarrow(t,\sqrt{at},\sqrt{t^2+at})$ where $C$ is injective trajectory, now we find
$||C^{\prime}(t)||=\sqrt{(x^{\prime})^2+(y^{\prime})^2+(z^{\prime})^2}$ and
$||C^{\prime}(t)||=\frac{1}{2}\sqrt{\frac{8t^2+9at+2a^2}{t^2+at}}$ now we substitute it in $I$ like a
$$I=\int_{\gamma}zdl=\frac{1}{2}*\int_{0}^{a}\sqrt{t^2+at}\sqrt{\frac{8t^2+9at+2a^2}{t^2+at}}dt=\frac{1}{2}\int_{0}^{a} \sqrt{8t^2+9at+2a^2}dt$$
Finally solving the latest integral we get
$$I=\int_{\gamma}zdl=\frac{1}{2}(\frac{1}{256}a\left(-72 \sqrt{2} \sqrt{a^2}+200 \sqrt{19} \sqrt{a^2}+17 \sqrt{2} a \log \left(8 \sqrt{a^2}+9 a\right)-17 \sqrt{2} a \log \left(4 \sqrt{38} \sqrt{a^2}+25 a\right)\right)$$
And like the intersection is two lines we multiply it by $2$ and we get
$$I=\int_{\gamma}zdl=(\frac{1}{256}a\left(-72 \sqrt{2} \sqrt{a^2}+200 \sqrt{19} \sqrt{a^2}+17 \sqrt{2} a \log \left(8 \sqrt{a^2}+9 a\right)-17 \sqrt{2} a \log \left(4 \sqrt{38} \sqrt{a^2}+25 a\right)\right)$$
Is my approach fine?  or probably I forget some detail.
I think that it wrong because usually when I apply a parametrization the integrand is much easy than it, and i had to compute the Integral in Wolphram Mathematica , because it is so much large.
Please any help, hit or comment are useful and appreciate .
Thanks so much for read me
Answer: Glanced at your solution and did not find anything out or ordinary or red flags.
But the surfaces look like cylindrical coordinates might be used that should simplify the computation. Try to use those.
Comment: Thanks I'm try to do your suggestion,
Answer: Whichever way you look at it, it is not going to be a straightforward integral.
Please note the intersection curve is given by as below and we have to integrate over this curve from point $(0,0,0)$ to $(a,a,\sqrt2 \,a)$.
$x^2 + ax - z^2 = 0 \implies (x+\frac{a}{2})^2 - z^2 = \frac{a^2}{4}$
This is equation of a hyperbola and I would consider hyperbolic parametrization instead.
$x = -\frac{a}{2} + \frac{a}{2} \cosh t = \frac{a}{2} (\cosh t - 1) = a \sinh^2 \frac{t}{2}$
$z = \frac{a}{2} \, \sinh t$
$y = a \, \sinh \frac{t}{2}$
where $0 \leq t \leq \sinh^{-1}(2 \sqrt2)$ (bound based on $0 \leq z \leq \sqrt 2 \, a$).
So $r(t) = (a \sinh^2 \frac{t}{2}, a \sinh \frac{t}{2}, \frac{a}{2} \, \sinh t)$
$r'(t) = (a \sinh \frac{t}{2} .\cosh \frac{t}{2}, \frac{a}{2} \, \cosh \frac{t}{2}, \frac{a}{2} \, \cosh t)$
$||r'(t)|| = \displaystyle \frac{a \sqrt {2 \cosh 2t + \cosh t + 1}}{2 \sqrt2}$
$I = \displaystyle \frac{a^2}{4 \sqrt2} \int_0^{\sinh^{-1}(2 \sqrt2)} (\sinh t \sqrt {2 \cosh 2t + \cosh t + 1}) \, dt = \frac{a^2}{4 \sqrt2} \times 8.22216 \approx 1.4535a^2$
Comment: Great work, now I´m analyzing your answer and try to bound it with my answer and compare, for the momen im only can say "nice solution" very clear.
Comment: Thanks so much, I´m glad with your answer every is better see other ways to do the same thing.
Comment: @BrienNavarro you are welcome
Comment: A least question. Can you explain me how do you get the hyperbolic  parametrization of the curve? or given me a link where i can read about it, im searching in google,but i dont get read some about it topic, exept the basic definitions about hyperbolic functions using exponential function.
Comment: @BrienNavarro pls see https://en.wikipedia.org/wiki/Hyperbola#Parametric_equations. It is given for $x^2/a^2 - y^2/b^2 = 1$. For us here, $a = b = a/2$. But for us the center of the hyperbola (where both asymptotes meet) is not at the origin but at (x = -a/2, z = 0). So you would see that adjustment in the parameterization.


Can't Make a Composite Key? Where am i going wrong?

Question: Im trying to make a many to many relationsship. A client needs to be able to have many administrations and an administration should be able to have many clients. My problem: In microsoft management studio the ClientId is somehow set to be the primary key, in the linking table. What am i doing wrong?
I have the following 3 models:
public class Client : IUser
{
    [Key, ForeignKey(nameof(User)), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public User User { get; set; }
    public IList<ClientAdministration> ClientAdministrations { get; set;}
}

public class Administration
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public IList<ClientAdministration> ClientAdministrations { get; set;}
}

public class ClientAdministration
{
    [key, Column(Order = 0)]
    public int ClientId { get; set; }
    public Client Client { get; set; }

    [key, Column(Order = 1)]
    public int AdministrationId { get; set; }
    public Administration Administration { get; set; }
}

In my Context.cs have defined the following relationsship:
modelBuilder.Entity<ClientAdministration>()
            .HasKey(ca => new { ca.ClientId, ca.AdministrationId });

        modelBuilder.Entity<ClientAdministration>()
            .HasOne<Client>(ca => ca.Client)
            .WithMany(c => c.ClientAdministrations)
            .HasForeignKey(ca => ca.ClientId);

        modelBuilder.Entity<ClientAdministration>()
            .HasOne<Administration>(ca => ca.Administration)
            .WithMany(a => a.ClientAdministrations)
            .HasForeignKey(ca => ca.AdministrationId);

Comment: Does the `ClientAdministration` table have any other columns? Or just the 2 key columns?
Comment: @jcruz No, just the two key columns :)
Comment: In that case you can omit the joining table all together from your C# code and use the fluent API configuration for this M2M mapping. See section "Configure a Many-to-Many Relationship using Fluent API" in the post: https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
Answer: According to this, the Key attribute defines the primary key.
In a linking table, both keys are foreign keys, not primary keys.


On the definition of Power-product of elements of ideal

Question: I am reading the paper Lefschetz Properties and Hyperplane arrangements by E. Palezzato and M. Torielli,(https://arxiv.org/pdf/1911.04083.pdf) and I am having problems finding the definition of power-product of an element of a monomial ideal. Does someone have a reference for that?
Thanks in advance.
Answer: A power-product in a polynomial ring is just a product of powers of the variables. In $\mathbb{Q}[x, y]$ the power-products are $1,x,y,x^2,xy,y^2,x^3,x^2y,\ldots$. A non-zero polynomial is a sum of power-products with coefficients (see Definition 2.3).
The word 'monomial' is often used for the same concept, but some sources use the words (and words like 'term') differently, sometimes including coefficients.
For a reference, you will find it e.g. in all books dealing with Gröbner bases. As I mentioned, the terminology sometimes differs (but from Definition 2.3 it is clear what is meant in your case).


mutate w for loop in R

Question: I have a data that looks like this...
df <- tibble (
  old_col = c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE))

... and I am trying to write a for loop that will add a variable that counts incrementally, changing each time there is a TRUE, so I end up with a df like this...
df <- tibble (
  old_col = c(FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE),
new_col = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3)

So far I have tried this code...

for(i in 1:nrow(df)){
  if(i==1){
   df$new_col[i]= 1 # For first point
  }
  else if(df$old_col[i] == "FALSE") {
   df$new_col[i]=df$new_col[i-1]
  }

  else {
   df$new_col[i]=2
  }

}

but the else part is wrong. I don't know what to put to make it count to 3 and then 4 next time there is a TRUE.
I am a loop newbie! thanks for your help!
PS if there is a tidyverse solution to this kind of problem, I'd love to hear about it.
Answer: You can take cumulative sum over logical values which will automatically increment for every TRUE value. Since the 1st value is FALSE we add + 1 to the output of cumsum.
df$new_col <- cumsum(df$old_col) + 1
df

# A tibble: 12 x 2
#   old_col new_col
#   <lgl>     <dbl>
# 1 FALSE         1
# 2 FALSE         1
# 3 FALSE         1
# 4 FALSE         1
# 5 FALSE         1
# 6 TRUE          2
# 7 FALSE         2
# 8 FALSE         2
# 9 FALSE         2
#10 TRUE          3
#11 FALSE         3
#12 FALSE         3

Using tidyverse :
library(dplyr)
df %>% mutate(new_col = cumsum(old_col) + 1)

Comment: ahhh of course, you can sum a logical- thats awesome! thanks!!
Answer: cumsum() is the standard way to go here. You could still use the loop just with minor modifications (I also added some simplifications/cleaning):
for (i in 1:nrow(df)) {
  if (i == 1) {
    # For first point
    df$new_col[i] = 1
  } else if (!df$old_col[i]) {
    df$new_col[i] = df$new_col[i-1]
  } else {
    df$new_col[i] = df$new_col[i-1] + 1L
  }
}

mutate w for loop in R


How to save upsetr graph as an image file from within function?

Question: UpSetR graphs are not saving properly when I call f. What is being saved to tmp.tiff is a blank image file. If I debug into the function, then it saves properly.
f <- function(tmp){
  tmp <- tmp %>%
    fromList() %>%
    upset()
  tiff(filename = 'tmp.tiff')
  tmp
  dev.off()
}

list(a = c(1, 1, 2, 6), b = c(2, 2, 3, 7)) %>%
  f()

I've saved the graph to a variable, called the tiff function for a file stream, called the graph variable and then dev.off(). What am I missing here?
edit:
#Calling tiff before upset does not work either.
f <- function(tmp){
  tiff(filename = 'tmp.tiff')
  upset(fromList(tmp))
  dev.off()
}

list(a = c(1, 1, 2, 6), b = c(2, 2, 3, 7)) %>%
  f()

Comment: You need to call `tiff` _before_ you call `upset`.
Comment: It is still saving a blank image for me.
Comment: If you just run `upset(fromList(YourData))` at the console (not in a function),  does that work for you?
Answer: if this is still a problem, I think you can find a solution here:
https://github.com/hms-dbmi/UpSetR/issues/115#issuecomment-1416486255
It seems that you need to print the plot to be able to save it inside a function. I don't know why, just came across it after reading this question.


eclipse "TERM environment variable not set"

Question: I have build a C program in Eclipse on Linux(Ubuntu MATE).
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int num = 100,d1,d2,d3;
  system("clear");
  while(num <= 500)
  {
    d1 = num % 10;
    d2 = (num % 100) / 10;
    d3 = num /100;
    if(num == (d3*d3*d3) + (d1*d1*d1) + (d2*d2*d2))
      printf("%d \n", num);
    num = num + 1;
  }
  return 0;
}

I don't get any error when I build it, but when I execute it by pressing the run button, it says

"Error exist in required project.Continue launch?"

Then I press the yes button and it gives following output in the Eclipse console:
153
370
371
407
TERM environment variable not set.

But when I execute this program in a real terminal then it runs fine and gives following:

here is output in text :-
153
370
371
407

But here the line "TERM environment variable not set." is not shown. It only occurs in eclipse terminal. Why is this happening?
Also can i use real mate terminal instead of eclipse console?
Comment: Post text as text, not images!
Answer: The output is probably from clear. In order to send the correct sequence to the terminal for clearing the screen, it needs to know the terminal type and uses the TERM environment variable for it. In eclipse, you don't have a real terminal and no TERM variable is set.
That being said, don't execute clear from your own program. It forks a process for no gain, is not portable to non-*nix platforms, breaks the assumption that a normal tool will just write output and not delete anything, and, as you see, depends on the environment.
If you really need control over the terminal as a screen, have a look at the curses library.
Comment: please ,i have added new line at the end of my question,can i use my real terminal instead of eclipse console in eclipse?if yes,then how?


notifyicon image looks terrible once image ends up in system tray

Question: I am using Visual Studio 2010, C#, on Windows 7.
I have added a notify control to my project and set it to an icon I have imported to the project. The icon image is really good looking if I just preview it, but once I run my code and see it in the system tray,  then it's really terrible, like the sides are dotted instead of straight lines and so on. I have tried 16x16, 24x24, 32x32 and 48x48 of the same file but I am having terrible results.
Have I missed anything?
myNotifyIcon.Icon = SysDir.Properties.Resources.icon2_32_ico_rgba;

Comment: Screenshot required.  Try limiting color content to 8bpp (256 colors).
Comment: what is the small icon size on this machine?
Comment: @Hans Passant : Its not just the color, but the size also that get deformed.
Comment: @David Heffernan: I called an API to check the size for icons, it said 16x
Answer: The problem with directly using the icon in your resources is that instead of choosing the right icon version in you icon file, the framework simply scales the default icon version to whatever size the notification area needs. That's why you are seeing jagged edges.
To get the best quality, you'll need to choose the right size in your icon by yourself.
First, instead of directly setting your NotifyIcon.Icon to an icon in your resources, create a new Icon instance. Doing so will allow you to choose a specific icon size in your icon resource. Using SystemInformation.SmallIconSize will get you the size the notification area needs.
So :
myNotifyIcon.Icon = new Icon(Properties.Resources.MyIcon, SystemInformation.SmallIconSize);

Now, SystemInformation.SmallIconSize always returns the right icon size, but only if your application is DPI-aware (otherwise, it always returns 16). If your application isn't DPI-aware, and it is used on a system where DPI-scaling is enabled, the line above will select the 16x16 icon in your resource, at it'll be scaled up to whatever size the notification area needs (in other words, ugly icon).
By making your app DPI-aware, SystemInformation.SmallIconSize will return the right size, taking into account DPI-scaling. For instance, if DPI-scaling is at 150%, SystemInformation.SmallIconSize will return 24 (16 × 1.5).
To make your app DPI-aware, simply add this to your app.manifest, inside the <asmv1:assembly> tag:
  <asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" >
    <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
      <dpiAware>true</dpiAware>
    </asmv3:windowsSettings>
  </asmv3:application>

Comment: Do you think this concept should be applied to WPF window icons? I've seen that in WPF the icons don't usually scale well despite me generating .ico files with ranges from 16x16 all the way up to 256x256.
Comment: Great, Thank you very much!
Answer: Edit:
The info I am linking seems to be suspect at this point.  Try it out, but if it isn't working, then I suggest you edit your question to post screenshots of all your experiments (each icon size and how it gets scaled).
Original:
32x32x256 is the right size and color depth according to this link:
http://www.hhhh.org/cloister/csharp/icons/
But you have to be very careful when constructing that image:

Take a 16x16x256 image, and get it to look nice
Double it to 32x32 (careful not to blur or resample if doing this in a paint program)

The reason is that Windows will "resize" the 32x32 image to 16x16 by simply throwing away 3/4 of the pixels.  The link above demonstrates this phenomenon with a couple screenshots:
Before:

After:

I'm not sure how much of the color-depth pickyness (256 colors only?)/resampling issues are still true on Windows 7, but it certainly seems to be the case on XP.
Comment: certainly should not be 32px. Should be the small icon size, typically 16px.on size, typically 16px.
Comment: @David: Yes scaling always leads to less than perfect results.  But according to that article, it scales it for you.  You don't have a choice - you just have to work around it.
Comment: @David: I won't argue with your experience or defend the article.  Just wanted to make sure you were disagreeing with the point I was making, rather than points I wasn't trying to make :)  I agree with Hans' "screenshot required" comment at this point.  Multiple...
Comment: This link seems to have more info on the various color depths and sizes, though no mention of the Notification Icon: http://msdn.microsoft.com/en-us/library/ms997636.aspx
Comment: I have tried just doing the 16x picture as the icon, and its looks "most" normal.
Comment: scaling small raster images leads to dreadful results. Always best to use the right size. I have some experience in this.
Comment: Not in my experience. Although that's with native API. I'd be astounded if C# wrapper differed. Give it the right size. I think the article you link to is utterly bogus.
Comment: Did anyone try this? Does this still work in Win10? I couldn't get it to work but maybe I just misunderstand something. It seems to me that windows is not using 'nearest neighbor' for rescaling.
Answer: I use NotifyIcon in a C# WinForms application and no matter what the icon I use contains, after 2 resolution changes it ends up blurry.
My best guess is, that windows doesn't actually rescale the original every time but rescales the (already rescaled) version from the icon cache.
The only solution I found so far was setting the icon again after a resolution/dpi change:
SystemEvents.DisplaySettingsChanged += (sender, eventArgs) => {
   trayIcon.Icon = MyIcon;
};

I tried all kind of resolutions and bit depths in the icons but they all got blurred eventually. Now I only use a single 16x16 32b image in the icon and so far it works great on all tested displays.


solve a trigonometric equation $\sqrt{3} \sin(x)-\cos(x)=\sqrt{2}$

Question: $$\sqrt{3}\sin{x} - \cos{x} = \sqrt{2} $$
I think to do :
$$\frac{(\sqrt{3}\sin{x} - \cos{x} = \sqrt{2})}{\sqrt{2}}$$
but i dont get anything.
Or to divied by $\sqrt{3}$ :
$$\frac{(\sqrt{3}\sin{x} - \cos{x} = \sqrt{2})}{\sqrt{3}}$$
Answer: Hint:
$$\sqrt3\sin x-\cos x=\sqrt2\iff \sin\frac\pi3\sin x-\cos\frac\pi3\cos x=\frac{\sqrt2}2$$
Comment: there are pitfalls the OP can make here, for instance, $\cos(x+\frac{\pi}{3})=\cos(\pi/4) \implies x = \pi/4 - \pi/3$. You should probably consider clarifying why that is invalid.
Comment: @Sabyasachi, I think the OP must give it a try. If (s)he has any dout (s)he can write back. The hint is, as far as I can see, enough to solve the problem for anyone knowing the basics.
Comment: Okay, yes I agree.
Answer: One of the R-Formulas, a set of formulas for combining such trigonometric expressions, says that
$$a\sin{x} - b\cos{x} = R\sin(x - \alpha)$$
where
$$R = \sqrt{a^2 + b^2}, \alpha = \tan^{-1}{\frac{b}{a}}$$
However, I doubt this solution expresses any room for creativity for this question specifically, as noted by Don Antonio's interesting observation.
Answer: A difficulty of this equation is that it contains both $\sin(x)$ and $\cos(x)$. You can use the trigonometric identity $\sin^2(x) + \cos^2(x) = 1$ to express $\sin(x) = \pm \sqrt{1 - \cos^2(x)}$ (or $\cos(x)$ as a function of $\sin(x)$), but it is very unwieldy because it introduces square roots (another difficulty) and you need to distinguish the intervals where $\sin(x)$ is positive or negative. It is simpler if you can recognize another trigonometric identity.
The equation looks a bit like $\cos(u) \sin(x) - \sin(u) \cos(x) = a$ for some values $u$ and $a$ to be determined, only with a multiplicative factor. If you had this, you could apply the sine-difference formula: the equation is equivalent to $\sin(x-u) = a$. Your idea to multiply by a constant was on the right; the other part of the puzzle is this identity which guides you towards a multiplicative constant that helps. The equation constrains $\dfrac{\cos(u)}{\sin(u)} = \dfrac{\sqrt 3}{1}$ which you should recognize as having the solution $u = \frac{\pi}{6}$. Since $\cos(\frac{\pi}{6}) = \frac{\sqrt 3}{2}$ and $\sin(\frac{\pi}{6}) = \frac{1}{2}$, multiply the original equation by $\frac{1}{2}$ to get
$$ \sin\left(x - \frac{\pi}{6}\right) = \frac{\sqrt 2}{2} $$
Alternatively, to find the multiplicative coefficient, you can remark that $\cos^2(u) + \sin^2(u) = 1$, while here you have $(\sqrt 3)^2 + (1)^2 = 4$. Thus you need to divide the equation by $\sqrt 4$ to get coefficients that are a (cos, sin) pair.
(Here I am essentially deriving the formula shown by Yiyuan Lee from a more common identity.)
Since $\frac{\sqrt 2}{2} = \sin(\frac{\pi}{4})$, the equation is equivalent to
$$
x - \frac{\pi}{6} = \frac{\pi}{4} + 2k\pi
\qquad\text{or}\qquad
x - \frac{\pi}{6} = \pi - \frac{\pi}{4} + 2k\pi
$$
i.e. $x = \frac{5\pi}{12} + 2k\pi$ or $x = \frac{11\pi}{12} + 2k\pi$.
Answer: HINT:
Weierstrass substitution is not a bad alternative either.
It will leave a Quadratic Equation in $\displaystyle\tan\frac x2$ on substitution  and rearrangement of the given relation.
Answer: $$\sqrt{3} \sin x - \cos x = \sqrt{2}$$
Dividing both sides by 2, we get
$$\frac{\sqrt{3}}{2}\sin x -  \frac{1}{2}\cos x = \frac{\sqrt{2}}{2}$$
By substituting $\cos 30^{\circ} = \frac{\sqrt{3}}{2}$  & $\sin 30^{\circ} = \frac{1}{2}$, we get
$$\sin x \cos30^{\circ}  - \cos x \sin 30^{\circ} = \frac{\sqrt{2}}{2}$$
Using the identity $\sin(A - B) = \sin A \cos B - \cos A \sin B$ and $\sin 45^{\circ} = \frac{\sqrt{2}}{2}$,
$$\begin{align*}\sin(x - 30^{\circ}) &= \sin 45^{\circ} \\ x - 30^{\circ} &= 45^{\circ} \\ x &= 75^{\circ}\end{align*}.$$
Also, we know that $\sin 135^{\circ} = \frac{\sqrt{2}}{2}$. Then,
$$\begin{align*}\sin(x - 30^{\circ}) &= \sin 135^{\circ} \\ x - 30^{\circ} &= 135^{\circ} \\ x &= 165^{\circ}\end{align*}.$$
Therefore, $x = 30^{\circ}$ and $x = 135^{\circ}$.


how to eager loading nested relationships in Laravel with custom query?

Question: I have a comments table, with theses fields: id, body, and parent_id. comments can have subcomments, that's why it is using the parent_id field, I would like to know how I can achieve this nested result:
[
    {
        "id": 1,
        "body": "test",
        "parent_id": null,
        "comments": [
            {
                "id": 2,
                "body": "test",
                "parent_id": 1,
                "comments": [
                    {
                        "id": 3,
                        "body": "test",
                        "parent_id": 2
                    },
                    {
                        "id": 4,
                        "body": "test",
                        "parent_id": 2
                    }
                ]
            },
            {
                "id": 5,
                "body": "test",
                "parent_id": 1,
                "comments": []
            }
        ]
    },
    {
       "id": 6,
       "body": "test",
       "parent_id": null,
       "comments": []
    }
]

Without using eloquent eager loading(with()), just using the query builder, thank you.
Answer: Since the possible answer could be too long, I am posting it directly as an answer. You could achieve this by creating a recursive method in your controller like below:
public function commentsLoop($comments, $parent = null)
{
    $result = [];

    foreach ($comments as $comment) {
        if ($comment['parent_id'] === $parent) {
            $subComment = commentsLoop($comments, $comment['id']);

            if ($subComment) {
                $comment['comments'] = $subComment;
            }

            $result[] = $comment;
        }
    }

    return $result;
}

And then, you can call it from your main method in your controller like below:
public function comments()
{
    $comments = DB::table('comments')->all()->toArray();

    return $this->commentsLoop($comments);
}

However, if you would use eloquent instead, creating a relationship to self in your model would be the answer.
Comment: it works, thanks, but I needed to adjust it a little bit, the ->toArray(); method returns an array of objects, so I needed to change it to this: $comment->parent_id.


Dividir argumentos com regex

Question: Eu tenho dificuldades com regex. Preciso apenas dividir uma string de entradas.
Input: "arg1 arg2 arg3 arg4"; Output: [arg1, arg2, arg3, arg4]

Input: "arg1 'arg 2' arg3 arg4"; Output: [arg1, arg 2, arg3, arg4]

Meu problema está no segundo exemplo. Pois quando o argumento está entre aspas, preciso mante-lo integro. E como estou usando a função explode do PHP, acabo tendo dois argumentos ([arg, 2]);
Comment: É php via linha de comando?
Answer: Supondo que o padrão seja arg sendo fixo :
$str = "arg1 'arg 2' arg3 arg4";
preg_match_all("~arg\d|'arg[^']+'~", $str, $matchs);

print_r($matchs[0]);

Caso não queira incluir as ' use : arg\d|(?<=')arg[^']+(?=')
Edição
Como comentado arg na verdade são argumentos de qualquer tipo:
Assim a regex teve se ser alterada :
Input : seed.php app:init "app" "/seed/" "Lucas Mahle"
Regex : ['"].*?['"]|[^ ]+
Comment: Não é fixo. Como ficaria? Um exemplo do input: 'seed.php app:init "app" "/seed/" "Lucas Mahle'
Comment: @lucasDotCom esse tipo de coisa deve ser especificado quando se fala de regex. So para saber você pode abrir com aspa simples e fechar  com dupla e vise versa?
Comment: @lucasDotCom Editei, veja se agora esta de acordo.
Comment: Guilherme, funcionou perfeitamente. Era apenas isso que eu precisava.
Answer: Não tenho conhecimento em PHP, mas criei um exemplo em javascript que talvez possa lhe ajudar a compreender a expressão regular (acompanhe os comentários no código):

function splitArguments(arguments) {
  return arguments.replace(
      /* procura tudo que está entre ' nos argumentos */
      /\'([^']+)\'/g, function(replacement) {
        /* procura espaço no que está entre ' e substitui por '__' */
        return replacement.replace(/ /g, '__');
      })
    // troca os espaços em branco dos separadores por ||
    .replace(/ /g, '||')
    // retorna o __ para espaço em branco dentro do argumento
    .replace(/__/g, ' ')
    // aplica split pelo novo separador de argumentos ||
    .split(/\|\|/g);
}

console.log(splitArguments("arg1 arg2 arg3 arg4"));
console.log(splitArguments("arg1 'arg 2' arg3 arg4"));
console.log(splitArguments("arg1 'arg 2' arg3 'arg 4'"));

Acredito que está atualização resolveu as falhas, se observar alguma falha em algum caso de teste comente.
Comment: Obrigado Fernando, seu código me serviu para outro problema.

Dividir argumentos com regex


What alternative I can use to SVG words cloud?

Question: Recently, I've designed a word cloud in Illustrator for a customer. It uses around 5,000 people's names in white on a colored background on a logo path, and includes a few vector logos. Each name is ridiculously small, and we want to be able to search on the cloud and find our name.
We've put it online as a SVG with success - but a 20M file can cause problems!
So everything would be fine until we reach 10,000 visitors at the same time, and make all our servers crash and timeout everyone.
So what is our alternative to make this fast, easy for visitors to use, and latency free? We think about Canvas, but not sure if it's simple to make a words cloud with [really (thing about following a logo path)] custom shape.
Comment: That's a big file! Does it need to be that complex, though? I mean, is a word cloud with 5000 elements useful? If you really can't simplify it, and you think people will want to download it even at that size, consider hosting it on a CDN.
Comment: unfortunately, yes the word cloud can't be simplified. We actually use a jpg and invite visitors to click on it, to download the file. But our customer isn't happy about this solution.
Comment: Well, even if each name is a modest 2K in size, that's already 10M, which imo is still too large. Could you do this in Flash or JavaScript, so that the customer can drill down to the part of the cloud they are interested in, using some sort of hierarchy? They can't possibly want to read all 5,000 items on the full thing `;)`.
Comment: @halfer What kind of name is 2k in size?
Comment: @Marcin - I was assuming glyphs would be rendered to paths. But you're right, they should just be text elements.
Answer: It sounds like you have 20Mb because the names are being stored/represented with paths. If you represent them as text, you will substantially reduce the size of the file, AND make it appropriately searchable.
Assuming 13 characters per name (including the space in between), UTF-8 encoding, and 10,000 names the names themselves should only take 127Kb. You may wish to experiment with transmitting the background of the SVG and the names (JSON?), and using a script to construct the cloud in the browser.
Edit: Even if you create a completely static SVG, representing the text as text will result in a substantial saving of space over the use of paths.
Comment: In illustrator you can prevent the text elements from being converted to paths in the save settings `Font Subsetting > None (Use system fonts)` http://i.stack.imgur.com/rAHmN.png


Issue with UITabBar button, TabBar button becomes un clickable

Question: I am creating a view with UINavigationBar and UITabBar. I have added a button on tab bar, on button click, i am hiding tab bar and show tool bar at the bottom. My code is written for current as well as previous iOS versions. I am using this code  self.edgesForExtendedLayout = UIRectEdgeNone; for iOS7 this is my code :
- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;enter code here
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;

//                         CGRect contentFrame = content.frame;
//                         contentFrame.size.height -= tabFrame.size.height;
                         content.frame = window.bounds;
                     }];

     if ([[[UIDevice currentDevice] systemVersion] intValue] < 7.0)
     {
    CGRect frame = tbl_AllFiles.frame;
    frame.size.height -=tabBar.frame.size.height;
    tbl_AllFiles.frame = frame;
     }

}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;

    if ([[[UIDevice currentDevice] systemVersion] intValue] < 7.0)
    {
    CGRect frame = tbl_AllFiles.frame;
    frame.size.height +=tabBar.frame.size.height;
    tbl_AllFiles.frame = frame;
    }

    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;

                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                         content.frame = contentFrame;
                     }];
}
- (void)loadToolBar {

    toolbar = [UIToolbar new];
    toolbar.barStyle = UIBarStyleBlackTranslucent;

    moveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [moveButton setFrame:CGRectMake(10, 10, 120, 25)];
    [moveButton setBackgroundColor:[UIColor redColor]];
    [moveButton setTitle:@"Move" forState:UIControlStateNormal];
    [moveButton addTarget:self action:@selector(moveFile_Folder:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *moveItem = [[[UIBarButtonItem alloc] initWithCustomView:moveButton] autorelease];
    moveItem.style = UIBarButtonItemStyleBordered;
    NSArray *items = [NSArray arrayWithObjects:moveItem, nil];
    toolbar.items = items;

    [toolbar sizeToFit];
    CGFloat toolbarHeight = [toolbar frame].size.height;
    CGRect mainViewBounds = self.view.bounds;

    if ([[[UIDevice currentDevice] systemVersion] intValue] < 7.0)
    {
        [toolbar setFrame:CGRectMake(CGRectGetMinX(mainViewBounds),
                                     CGRectGetMinY(mainViewBounds) + CGRectGetHeight(mainViewBounds) - (toolbarHeight),
                                     CGRectGetWidth(mainViewBounds),
                                     toolbarHeight)];
    }
    else
    {
        [toolbar setFrame:CGRectMake(CGRectGetMinX(mainViewBounds),
                                 CGRectGetMinY(mainViewBounds) + CGRectGetHeight(mainViewBounds),
                                 CGRectGetWidth(mainViewBounds),
                                 toolbarHeight)];
    }

    [self.view addSubview:toolbar];
    [toolbar bringSubviewToFront:self.view];

}

My issue is on button clicked hideTabBar and loadToolBar methods are called. Everything is working fine, except my button is un-clickable now on toolbar.
Please help me.
Comment: I am using that.    if ([[[UIDevice currentDevice] systemVersion] intValue] >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
Comment: No. Button is not clickable.If I set the frame of tool bar some above, then its clickable.
Comment: Can we have downloadable link for your code ?
Comment: on a side note, have you tried SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
Comment: Yeah, I know that why I showed you what I think its a cleaner method for doing the same thing. In regard to your question, can you get a NSLog from your button click?
Answer: i had a similar issue if your viewcontroller is not the root view controller iOS doesn't get the view frame.
Add this line to your viewcontroller in viewdidload,
self.view.frame = [UIScreen mainScreen].bounds;

hope it helps


model instance exists but is "saved" anyway

Question: My instance seems to be saved when I call the save method. The problem: the instance already exists in my database!
My model:
class DosIdModel(models.Model):
    dosId = models.IntegerField(max_length=7, primary_key=True)
    proposOrigine = models.CharField(max_length=4)
    proposAnnee = models.IntegerField(max_length=4)
    proposChrono = models.CharField(max_length=7)
    splitNumber = models.IntegerField(max_length=1, blank=True, null=True, default=None)

My view:
instance = DosIdModel()
instance.dosId=int(row[0])
instance.proposOrigine=row[1].strip()
instance.proposAnnee=int(row[2])
instance.proposChrono=row[3].strip()
instance.splitNumber=emptyOrVar(row[4], "int")
msg=(instance.dosId)

savedList=[]
errors_list=[]
try:
    print "exist: ", DosIdModel.objects.get(dosId=instance.dosId).dosId
    instance.save()
    print "saved"
    savedList.append(msg)
    print "end try"
except IntegrityError, e:
    print "except"
    error= "The row " + str(msg) + " already exists!!"

Result in the console:
exist:  104486
saved
end try

What is wrong?
Comment: Why is this a problem? Apparently there is already a record with that same `dosId`. So `.save()` will just update that record.
Comment: Sorry, no idea what that code snippet is attempting to demonstrate.
Comment: if you are working with data from forms, you would better use the integrated forms...
Comment: I thought the `save` method was for `INSERT` queries only. I use this code with an other model and it throws an `IntegrityError` if the object already exists. As pointed out by Kevin, the reason might be that I did not declare a `primary key` in my other model (I use the `auto primary key` created by Django).
Comment: So I ended up using `force_insert=True` (I don't want to do an `update`, just an `insert`).
Answer: Review the documentation on How Django knows to UPDATE vs. INSERT. Specifically:

If the object's primary key attribute is set to a value that evaluates to True...
  Django executes a SELECT query to determine whether a record with the given primary
  key already exists. If the record with the given primary key does already exist, Django
  executes an UPDATE query.... The one gotcha here is that you should be careful not to
  specify a primary-key value explicitly when saving new objects, if you cannot guarantee
  the primary-key value is unused.

You can get the behavior you're looking for by using instance.save(force_insert=True) -- that will force the INSERT which in turn should raise the IntegrityError you're expecting.
Note, however, that you're going against the grain. Here's what the docs say about force_insert:

It should be very rare that you'll need to use these parameters. Django will almost
  always do the right thing and trying to override that will lead to errors that are
  difficult to track down. This feature is for advanced use only.
Comment: Indeed, I had misunderstood the `save` method. I use this code for many models, with different `uniqueness` constraints, so I ended up using `force_insert=True`. Seems to work :). Thank you


Optimization of Mysql table size

Question: I am considering a problem.
In C language, we are suggested that the size of struct should be multiples of 2-byte.
e.q.:
<code>struct text{
   int index;//assume int is 4 byte.
   char [8] word;
}//alought text is only 12 bytes, compiler would assign 16 bytes for this struct
</code>
Therefore, I am wondering does the record size(thanks of Gordon Linoff) of MySQL encounter the same problem?
Moreover, how can I optimize MySQL via controlling table size?
Comment: Just as the compiler takes care of aligning things for you in C, the DBMS takes care of doing it in a database system.
Answer: First, you are referring to a record size and not the table size.
Second, databases do not work the way that procedural languages do.  Records are stored on pages, which are filled up until no more fit.  Then additional pages are used.  Typically, there are many records on a page.
You can get an idea of what a page looks like here.  They are complicated but basically hidden from the user.
It sounds like you are attempting "premature optimization".  This isn't quite the root of all evil, but it is a major distraction to getting things accomplished.  In other words, define the record as you need it defined.  Do what you want to do.  If you have performance problems, then fix those when they arise.
The size of a record is going to be the least of your problems.  Databases perform I/O in units of pages, so the difference between 12 and 16 bytes is meaningless for a single record.  You still have to read the entire page (which is much larger).
Comment: Hmmm, you are right. I was mixing up the concept of page and memory. Thanks for your answer!!

Optimization of Mysql table size


Remove first name using regular expression

Question: I want it to display "Dr. House" instead of Dr. Greg house and I am only allowed to modify "const re = /^(\w+.\s)(\w+\s\w+)$/;". Can anyone help me?
here is the code
const userName = "Dr. Greg House"; // Code will also be tested with "Mr. Howard Wolowitz"

/* Your solution goes here */
const re = /^(\w+\.\s)(\w+\s\w+)$/;
const result = re.exec(userName);

console.log(result[1] + " " + result[2]);

Comment: Regular expressions aren't designed for name parsing
Comment: In this regular expression, (\w) captures the first initial of the first name and (\w+) captures the last name. The result will display "Dr. House" for the given input. `^(\w+.\s)(\w)\w+\s(\w+)$`
Comment: I'd highly suggest you take a look at [Falsehoods Programmers Believe About Names – With Examples](https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/). Like the Painter, `Pablo Picasso`, his full name was `Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso`. Good luck matching that correctly with a regex.
Answer: Use capturing groups only for the words you need to keep:

const userName = "Dr. Greg House"; // Code will also be tested with "Mr. Howard Wolowitz"

/* Your solution goes here */
const re = /^(\w+\.)\s\w+\s(\w+)$/;
const result = re.exec(userName);

console.log(result[1] + " " + result[2]);
Answer: A .replace() combined with a .trim() will do the job just as well:

const names = ["Dr. Greg House", "Mr. Howard Wolowitz", "Dr. Amy Farrah Fowler"];
const res=names.map(n=>{
  return n.trim().replace(/\s+\S+/,"")
});

console.log(res);


How can I ensure that my simulation starts a new "time to failure" countdown only after the repair is complete?

Question: I am creating a simulation of a 2 machine system with a buffer in between with fixed processing speeds, failure rate and maintenance speeds (later I will change this to having some sort of distribution, but for now baby steps first). The steps are as follows:

An unlimited capacity of units is delivered to machine 1.
Machine 1 processes at speed s, fails after f minutes and is repaired
after r minutes. If buffer is full then Machine 1 stops.
Buffer gets filled by Machine 1 and emptied by Machine 2. There is a
max capacity.
Machine 2 processes at min(speed s, capacity buffer) fails after f
minutes and is repaired after r minutes. If buffer is empty then
Machine 2 stops.
Unlimited buffer capacity after Machine 2.

I have gotten quite far with all of the above points accounted for. The only thing is that the failures keep counting the failure time per multiple of the unit I give it and it does not start counting after the machine has been fixed again. So it might break at 7, is fixed at 11 but then breaks at 14 again instead of 11+7=18.
It seems like the failure is just on an infinite loop. Does anyone know how I can change this? My code is as follows:
import simpy
import random

# Machine 1
speed_1 = 2          # Avg. processing time of Machine 1 in minutes
# speed_1_stdev = 0.6  # St. dev. of processing time of Machine 1
MTTF_1 = 10          # Mean time to failure Machine 1
# fail_1 = 1/MTTF_1    # Parameter for exp. distribution
repair_1 = 3         # Time it takes to repair Machine 1

# Machine 2
speed_2 = 3          # Processing time of Machine 2 in minutes
# speed_2_stdev = 0.6  # St. dev. of processing time of Machine 2
MTTF_2 = 7           # Mean time to failure Machine 1
# fail_2 = 1/MTTF_2    # Parameter for exp. distribution
repair_2 = 4         # Time it takes to repair Machine 2

# Simulation time
time = 120           # Sim time in minutes

#---------------------------------------------------------------------
# Class setup for a Machine
class Machine(object):
    """
    A machine produces units at a fixed processing speed,
    takes units from a store before and puts units into a store after.

    Machine has a *name*, a processing speed *speed*, a preceeding buffer *in_q*,
    and a proceeding buffer *out_q*.

    Next steps:
    - Machine produces units at distributed processing speeds.
    - A machine fails at fixed intervals and is repaired at a fixed time.
    - Failure and repair times are distributed.
    """
    def __init__(self, env, name, in_q, out_q, speed, mttf, repair):
        self.env = env
        self.name = name
        self.in_q = in_q
        self.out_q = out_q
        self.speed = speed
        self.mttf = mttf
        self.repair = repair
        self.broken = False

        # Start the producing process
        self.process = env.process(self.produce())
        # Start the failure process
        env.process(self.fail_machine())

    def produce(self):
        """
        Produce parts as long as the simulation runs.
        """
        while True:
            part = yield self.in_q.get()
            try:
                # If want to see time {self.env.now:.2f}
                print(f'{self.name} has got a part')

                yield env.timeout(self.speed)
                if len(self.out_q.items) < self.out_q.capacity:
                    print(f'{self.name} finish a part next buffer has {len(self.out_q.items)} and capacity of {self.out_q.capacity}')
                else:
                    print(f'{self.env.now:.2f}  {self.name} output buffer full!!!')

                yield self.out_q.put(part)
                print(f'{self.name} pushed part to next buffer')

            except simpy.Interrupt:
                self.broken = True
                yield self.env.timeout(self.repair)
                print(f'{self.env.now:.2f} {self.name} is in fixed')
                self.broken = False

    def fail_machine(self):
        """
        The machine is prone to break down every now and then.
        """
        while True:
            yield self.env.timeout(self.mttf)
            print(f'{self.env.now:.2f} {self.name} is in failure.')
            if not self.broken:
                # Machine only fails if currently working.
                self.process.interrupt(self.mttf)
#---------------------------------------------------------------------
# Generating the arrival of parts in the entry buffer to be used by machine 1
def gen_arrivals(env, entry_buffer):
    """
    Start the process for each part by putting
    the part in the starting buffer
    """
    while True:
        yield env.timeout(random.uniform(0,0.001))
        # print(f'{env.now:.2f} part has arrived')
        part = object() # Too lazy to make a real part class, also isn't necessary

        yield entry_buffer.put(part)

#---------------------------------------------------------------------
# Create environment and start the setup process
env = simpy.Environment()
bufferStart = simpy.Store(env)  # Buffer with unlimited capacity
buffer1 = simpy.Store(env, capacity = 8) # Buffer between machines with limited capacity
bufferEnd = simpy.Store(env)  # Last buffer with unlimited capacity

# The machines __init__ starts the machine process so no env.process() is needed here
machine_1 = Machine(env, 'Machine 1', bufferStart, buffer1, speed_1, MTTF_1, repair_1)
machine_2 = Machine(env, 'Machine 2', buffer1, bufferEnd, speed_2, MTTF_2, repair_2)

env.process(gen_arrivals(env, bufferStart))

# Execute
env.run(until = time)

Comment: in fail_machine() take out the while so it executes only once.  then in produce() at the end of the except block add env.process(self.fail_machine()) to start the clock to next breakdown.
Answer: changed the fail_machine method from a infinite loop to generate just the next breakdown.  fail_machine still needs to be called from the init startup, but also now needs to be called from the end of the except block that handles the breakdown, restarting the countdown to next failure.
import simpy
import random

# Machine 1
speed_1 = 2          # Avg. processing time of Machine 1 in minutes
# speed_1_stdev = 0.6  # St. dev. of processing time of Machine 1
MTTF_1 = 10          # Mean time to failure Machine 1
# fail_1 = 1/MTTF_1    # Parameter for exp. distribution
repair_1 = 3         # Time it takes to repair Machine 1

# Machine 2
speed_2 = 3          # Processing time of Machine 2 in minutes
# speed_2_stdev = 0.6  # St. dev. of processing time of Machine 2
MTTF_2 = 7           # Mean time to failure Machine 1
# fail_2 = 1/MTTF_2    # Parameter for exp. distribution
repair_2 = 4         # Time it takes to repair Machine 2

# Simulation time
time = 120           # Sim time in minutes

#---------------------------------------------------------------------
# Class setup for a Machine
class Machine(object):
    """
    A machine produces units at a fixed processing speed,
    takes units from a store before and puts units into a store after.

    Machine has a *name*, a processing speed *speed*, a preceeding buffer *in_q*,
    and a proceeding buffer *out_q*.

    Next steps:
    - Machine produces units at distributed processing speeds.
    - A machine fails at fixed intervals and is repaired at a fixed time.
    - Failure and repair times are distributed.
    """
    def __init__(self, env, name, in_q, out_q, speed, mttf, repair):
        self.env = env
        self.name = name
        self.in_q = in_q
        self.out_q = out_q
        self.speed = speed
        self.mttf = mttf
        self.repair = repair
        self.broken = False

        # Start the producing process
        self.process = env.process(self.produce())
        # Start the failure process
        env.process(self.fail_machine())

    def produce(self):
        """
        Produce parts as long as the simulation runs.
        """
        while True:
            part = yield self.in_q.get()
            try:
                # If want to see time {self.env.now:.2f}
                print(f'{self.name} has got a part')

                yield env.timeout(self.speed)
                if len(self.out_q.items) < self.out_q.capacity:
                    print(f'{self.name} finish a part next buffer has {len(self.out_q.items)} and capacity of {self.out_q.capacity}')
                else:
                    print(f'{self.env.now:.2f}  {self.name} output buffer full!!!')

                yield self.out_q.put(part)
                print(f'{self.name} pushed part to next buffer')

            except simpy.Interrupt:
                self.broken = True
                yield self.env.timeout(self.repair)
                print(f'{self.env.now:.2f} {self.name} is in fixed')
                self.broken = False

                # change to restart next fail here instead of in a infinite loop
                self.env.process(self.fail_machine())

    def fail_machine(self):
        """
        The machine is prone to break down every now and then.
        """

        # no longer a loop, relies on breakdow logic to restart
        yield self.env.timeout(self.mttf)
        print(f'{self.env.now:.2f} {self.name} is in failure.')
        if not self.broken:
            # Machine only fails if currently working.
            self.process.interrupt(self.mttf)

#---------------------------------------------------------------------
# Generating the arrival of parts in the entry buffer to be used by machine 1
def gen_arrivals(env, entry_buffer):
    """
    Start the process for each part by putting
    the part in the starting buffer
    """
    while True:
        yield env.timeout(random.uniform(0,0.001))
        # print(f'{env.now:.2f} part has arrived')
        part = object() # Too lazy to make a real part class, also isn't necessary

        yield entry_buffer.put(part)

#---------------------------------------------------------------------
# Create environment and start the setup process
env = simpy.Environment()
bufferStart = simpy.Store(env)  # Buffer with unlimited capacity
buffer1 = simpy.Store(env, capacity = 8) # Buffer between machines with limited capacity
bufferEnd = simpy.Store(env)  # Last buffer with unlimited capacity

# The machines __init__ starts the machine process so no env.process() is needed here
machine_1 = Machine(env, 'Machine 1', bufferStart, buffer1, speed_1, MTTF_1, repair_1)
machine_2 = Machine(env, 'Machine 2', buffer1, bufferEnd, speed_2, MTTF_2, repair_2)

env.process(gen_arrivals(env, bufferStart))

# Execute
env.run(until = time)


Visualization for longitudinal lab tests

Question: I'm trying to meaningfully display longitudinal changes in lab test results to a lay (not necessarily stats literate) audience.

I currently show scatterplots with bands to indicate normal vs abnormal ranges but worry that I might not be conveying the magnitude of improvement/deterioration. All data points in the scatterplot are results for the same test and the methodology can be assumed to be identical.
I also worry that for patients with lots of data points, scatterplots can become noisy. I would appreciate feedback on appropriate visualization schemes for a lay audience.
Comment: Can you say more about your situation, your data, & the analysis / model? What is it you want them to understand after having seen your presentation?
Comment: The data is from patients who go in to get tested when there's a clinical indication (symptoms) and the analyses plan isn't finalized but will likely be simply comparing Mean +/- SD between periods (Ex years). After seeing the chart, I'd like them to appreciate whether they are trending upwards or downwards or not changing.
Answer: If you typically have enough data points, you might consider drawing a smoothed curve based on a flexible approach like LOWESS. That can help display trends in scatterplot data. You will have to determine curve-smoothing parameters to balance out emphasis of long-term trends over short-term glitches, and decide whether to use robust methods that might be less affected by outliers. I'd recommend showing the individual data points too, although perhaps with less emphasis than for the smoothed curve. Work to make sure that the trends of the curves you display actually correspond to your clinical decisions about trends; detecting trends in noisy data with few points is extremely difficult.


Unable to delete sheets that meet a condition

Question: I keep getting

runtime error 1004 - Application defined or object defined error

for the code below. Could you help me figure out why this is happening?
Option Explicit

Sub DeleteSheet()

Dim Sh As Worksheet

Application.DisplayAlerts = False

For Each Sh In ThisWorkbook.Worksheets
    If Application.WorksheetFunction.Search("Generation", Sh.Range("A1").Value, 1) = 1 Then
       Sh.Delete
    End If
Next Sh

Application.DisplayAlerts = True

End Sub

Answer: You can't delete a sheet which is also a control variable in a loop.  Use a counter instead to iterate through the sheets, then delete using the counter, eg
dim sheetCount
dim i
sheetCount = ThisWorkbook.Worksheets.Count
for i = sheetCount to 1 step -1
    dim sh as Worksheet
    set sh = ThisWorkbook.Worksheets(i)
    If Application.WorksheetFunction.Search("Generation", sh.Range("A1").Value, 1) = 1 Then
       ThisWorkbook.Worksheets(i).Delete
    End If
next i

Comment: Thank you, this was really helpful and easy to understand. Cheers!
Answer: Delete Worksheets Using an Array of Worksheet Names

I couldn't reproduce the exact error.
The covered scenarios producing errors were the following:

when generation was not found in cell A1,
the last sheet cannot be deleted,
when a sheet was very hidden.

VBA has its own FIND or SEARCH equivalent called Instr.
In the workbook containing this code (ThisWorkbook), it will delete all worksheets whose cell A1 contains a string starting with Generation.

Option Explicit

Sub DeleteSheets()

    Dim wsCount As Long: wsCount = ThisWorkbook.Worksheets.Count
    Dim wsNames() As String: ReDim wsNames(1 To wsCount) ' Worksheet Names Array

    Dim ws As Worksheet
    Dim n As Long

    For Each ws In ThisWorkbook.Worksheets
        ' Check if 'A1' contains a string starting with 'Generation'.
        If InStr(1, CStr(ws.Range("A1").Value), "Generation", _
                vbTextCompare) = 1 Then
            n = n + 1 ' next array element
            wsNames(n) = ws.Name ' write the worksheet name to the array
        End If
    Next ws

    ' Check if no worksheet name was added to the array.
    If n = 0 Then Exit Sub
    ' Resize the array to the number of found worksheets.
    If n < wsCount Then ReDim Preserve wsNames(1 To n)

    ' Delete the worksheets, without confirmation, in one go.
    Application.DisplayAlerts = False
    ThisWorkbook.Worksheets(wsNames).Delete
    Application.DisplayAlerts = True

End Sub

Comment: Pretty complicated, but an interesting way of working out the problem. It helped me sort out the issue I was facing. Thanks a ton!


What are some conditions that are sufficient for the following projection property?

Question: Let $X$ be a locally convex topological vector space, and let $f: X \times X \to [0,\infty]$.
Say that $f$ has the projection property if the following holds:

For all compact, convex $C \subseteq X$ and all $x \in X$, there exists a unique $p_x \in C$ (the "projection" of $x$ onto $C$) such that $f(p_x, x) \leq f(y, x)$ for all $y \in C$, and, moreover, if $x \in C$, then $p_x = x$.

I am wondering:

Are there some well-known conditions on $f$ that imply it has the projection property (e.g. $f$ is (strictly) convex and/or continuous in one/both of its arguments)? Can you point me to some references where the projection property and/or similar properties are studied?

If $f$ is continuous in its first argument, for example, then it achieves its minimum on every compact $C$. And if $f$ is also strictly convex in its first argument, then there is exactly one minimizer. But I don't see that these assumptions guarantee that the minimizer $p_x$ is $x$ whenever $x \in C$.
If possible, I would prefer not to assume that $X$ is metrizable.
Answer: One example of such a projection is the orthogonal projection. Notice that such $f$ is a function of $\mathbf{y}$, and $\mathbf{x}$ is merely a parameter. When the underlying space $\mathbf{X}$ is Euclidean, the orthogonal projection onto a set is defined as $$P_C(\mathbf{x})=\text{argmin}_{\mathbf{y}\in C}\|\mathbf{y}-\mathbf{x}\|.$$
Norm is a strictly convex function, but we require the domain to be convex in order to say convexity exists. Therefore when $C$ is a convex set, this $\text{argmin}$ exists and it is unique.
For such a projection, additional properties exist. Consider $\mathbf{y}\mapsto f(\mathbf{x}, \mathbf{y})=\text{argmin}_{\mathbf{y}\in C}\|\mathbf{y}-\mathbf{x}\|$, then following three claims are equivalent: \begin{align}&1)\; \mathbf{u} = P_C(\mathbf{x}) \\
&2)\; \mathbf{x}-\mathbf{u}\in \partial f(\mathbf{u})\\
&3)\; \langle\mathbf{x}-\mathbf{u},\mathbf{y}-\mathbf{u}\rangle\leq f(\mathbf{y}) -f(\mathbf{u}) & \forall \mathbf{y}\in \mathbf{X}
\end{align}
Another projection property is that $\mathbf{u}=P_C(\mathbf{x})$ if and only if $\langle\mathbf{x}-\mathbf{u},\mathbf{y}-\mathbf{u}\rangle\leq 0$ for all $\mathbf{y}\in C$.
Lastly, we have nonexpansivity and firm nonexpansivity. For all $\mathbf{x}, \mathbf{y}\in \mathbf{X}$:
\begin{align}&1)\; \|P_C(\mathbf{x})-P_C(\mathbf{y})\|\leq\|\mathbf{x}-\mathbf{y}\| \\
&2)\; \|P_C(\mathbf{x})-P_C(\mathbf{y})\|^2\leq \langle\mathbf{x}-\mathbf{y}, P_C(\mathbf{x})-P_C(\mathbf{y})\rangle
\end{align}
Comment: Thanks, but the restriction to Euclidean spaces is too restrictive for me. I'm interested in arbitrary locally convex TVSs.


If $u=\Psi^{-1}\circ L\circ \Phi$ then $\operatorname{rk}(u)=\operatorname{rk}(L)$.

Question: $u\in \mathcal L(E,F)$ with $E$ and $V$ finite vector spaces over $K$. If $\Phi:E\to K^n$ and $\Psi:F\to K^p$ are isomorphisms, and if $$u=\Psi^{-1}\circ L\circ \Phi,$$
with $L:K^n\to K^p$ linear, then $\operatorname{rk}(u)=\operatorname{rk}(L)$. I recall that $\operatorname{rk}(u)=\dim \operatorname{Im}(u)$.
How can I prove this result ? I tried to proove that $\operatorname{Im}(u)=\operatorname{Im}(L)$, but it didn't work...
Comment: $Im(u)$ can't be equal to $Im(L)$, because they don't belong to the same vector space in general. You can use for example obvious formulas like $rg(v\circ u) = rg(u)-\dim(ker(v)\cap Im(u))$.
Answer: $\newcommand{\im}{\text{Im}}$
$\im(u)$ and $\im(L)$ will indeed be isomorphic, but not equal in general.
Let $\{f_1,...,f_n\}$ a basis of $F$ and $\{e_1,...,e_r\}$ a basis of $E$. You will have that $$\{\Phi(e_1),...,\Phi(e_n)\}$$
is a basis of $K^n$. Suppose that $rg(L)=m$ and suppose WLOG that $$\{L(\Phi(e_1)),...,L(\Phi(e_m))\},$$
is a basis of $\im(L)$. Since $\psi^{-1}$ is bijective, then $$\{\Psi^{-1}L(\Phi(e_1)),...,\Psi^{-1}L(\Phi(e_m))\}=\{u(e_1),...,u(e_m)\},$$
is a basis of $\im(u)$.


XenServer bad network config during initial Pool Creation

Question: I believe I made a terrible mistake.
I had a XEN8.0 (Citrix Hypervisor) for tests running on a local machine here in the office. It has a local IP adress. Classic.
Then I wanted to move my VM guests to a dedicated server in the cloud. XEN installed, configured, cool.
Then, the transfer with in/export function in XenCenter of a guest was not working. Then I choose to create a pool, because I thought, that I simply can move the guest systems to the other server. You might know what happens.
Situation now:
XEN_1 in cloud, master, public accessible IP (new)
XEN_2 local, slave, local IP behind router (old)
XEN_1# xe pool-sync-database
You attempted an operation which involves a host which could not be contacted.

XEN_2# xe pif-list
The master reports that it cannot talk back to the slave on the supplied management IP address.
ip: 192.168.103.81

XEN_2# xe pif-list params=uuid,host-name-label,device,management
The host toolstack is still initialising. Please wait.

I assume, XEN_2 tells XEN_1 his IP which is not reachable for him and the so it's a deadlock situation.
Question: Is it possible to tell XEN_1 somehow the IP of my local router?
The very bad thing is, that the Local Storage of XEN_2 is not accessible and there is one guest system which has very very important content. So vanishing the whole system is not a real option.
Other Question: Is it possible to access guest data via SSH?
Any help is much appreciated! Thanks
Answer: Checking further you are having issues with network connectivity since XEN_2 local is not having static IP address.  You can have a  VPN solution and add both Citrix Xen servers with private networks in order to migrate the VM from the same pool.
Comment: Perfect. At first I have not believed in this solution, but actually it worked. It was a bit of a mess to establish the VPN connection as `vpnc` had to be compiled manually. Find details [here](https://discussions.citrix.com/topic/407119-bad-network-config-during-initial-pool-creation/).


How to use the Gradle Proguard Plugin as a Maven repository dependency? (Without referencing local folders.)

Question: In order to use the gradle plugin of Proguard, using the method presented in the Proguard Gradle manual one has to manually download Proguard and place it in a local folder. In particular the manual says:

One way is to add the following line to your build.gradle file

And the manual provides the following build.gradle
<code>buildscript {
    repositories {
        flatDir dirs: '/usr/local/java/proguard/lib'
    }
    dependencies {
        classpath ':proguard:'
    }
}
</code>
It is worth noticing that this is just 'One way' to add the proguard.
It can be made more parameterized by defining the path as a variable for easy migration from one proguard build to another but it is not so portable.
What is needed is to use proguard without having to configure the workspace of the programmer, preferable having proguard downloaded from a Maven repository.
This can save time and reduce errors in cases such as building the project in a CI (e.g. Jenkins) or if the project is used in different environments.
Answer: I came up with the following gradle script:
<code>    // Tell Gradle where to find the ProGuard task.
    buildscript {
        repositories {
            mavenLocal() //in case it is already downloaded
            mavenCentral()
        }//end repositories

        dependencies { classpath 'net.sf.proguard:proguard-gradle:6.0.3' }
    }//end buildscript
</code>
This approach is working OK and using proguard from the repositories seems to be fine. See also in sourceforge.
Justification: The '/usr/local/java/proguard/lib' folder contains just the jars of proguard, using the proguard-gradle as a dependency will fetch also other dependencies required.


Session values are getting populated only when the page is refreshed

Question: I have a webform. I provide default values to these webform using session token variables. These session variables are set using hook_form_alter(). The problem is that when users log in, and see the form, it is not populated. When they refresh the form, only the values get populated.
How can I solve this issue?
/** updates **/
I have custom module like
webform_options_form_alter(&$form, &$form_state, $form_id){
//here i set some values for session variables like.
$_SESSION['name']  = 'pradeep';
}

so in webform default value i put like %session['name']. This takes the value when page is refreshed.
I have the login form as block on the same page of the webform. As soon as the user logs in the webform should be filled with user data. This is not happening. When he refreshes the page after login only he sees his data.
Answer: It sounds like your problem is how/when the session variables are set (they are not available on the initial form load). You don't mention how this is done.
Some code example and greater details in your question will allow for a more detailed answer.


Não Limpar form após submit wordpress

Question: montei um formulário que valida dentro da função do wordpress
porem toda vez que eu faço o submit ele limpa todo o formulário e não quero que ele faça isso
estou enviado os dados por jquery dessa forma
form.submit(function (e) {
        var dados = {
            'action': 'acao_validador',
            'dados': $(form).serialize()
        };
        ajaxscript = { ajax_url: '/wp-admin/admin-ajax.php' };
        $.ajax({
            url: ajaxscript.ajax_url,
            data: dados,
            datatype: 'json',
            method: 'POST',
            success: function (response) {
                if (response.class == 'success') {
                    console.log(response);
                } else {
                    console.log(response);
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
        e.preventDefault();
        return false;
    });

Answer: Para resolver isso, faça que ao clicar no submit chama uma function que pega os valores dos inputs em questão no formulário antes de realmente enviar e depois é só atribuir os valores que foram pegos na function antes do envio e atribuí-los novamente no final
Exemplo que fiz:
HTML:

<form action="">
  <input type="text" value="" id="txt1">
  <input type="text" value="" id="txt2">

  <input type="submit" value="Try it" name="" id="btn">
</form>

JAVASCRIPT:

    var input1 = document.getElementById('txt1')
    var input2 = document.getElementById('txt2')
    var submit = document.getElementById('btn')

    submit.addEventListener('click', function() {
        var valueInput1 = input1.value
        var valueInput2 = input2.value
        alert('TESTE: Sim foi enviado com o submit e os valores são os mesmos de ok para ver')
    })
    input1.value = valueInput1
    input2.value = valueInput2

Testa ai, e espero ter ajudado
Answer: Basta colocar no form <form onsubmit="return false">

Não Limpar form após submit wordpress


Configure Multiple Domains and an IP Address with NGINX

Question: I've asked on the forums before but didn't get answer so I'm going to try again.
I'm trying to setup NGINX with PHPMyAdmin and I want to access the site via two subdomains and an IP address. The following URLs all lead to the same root folder:-

phpmyadmin.localhost (only accessible via the host machine)
phpmyadmin.ubuntu-pc.lan (accessible via other LAN machines)
192.168.0.123/phpmyadmin (accessible via other LAN machines)

This is my current server block
# PHPMyAdmin
#
server {
    listen 80;
    listen [::]:80;
    #listen 443 ssl;
    #listen [::]:443 ssl;

    root /var/www/html/phpmyadmin;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name 192.168.1.123 phpmyadmin.localhost phpmyadmin.ubuntu-pc.lan;

    location / {
        try_files $uri $uri/ $uri/index.php =404;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Could someone tell me how I achieve this?
UPDATE
The problem I have is when accessing the Ubuntu machine from another device on the LAN I'm unable to access the IP address with the trailing directory 192.168.xxx.xxx/phpmyadmin or the subdomain phpmyadmin.ubuntu-pc.lan.
Instead they're both accessible without the trailing directory and subdomain.
Comment: its unclear what you want to me. whats rhe error?
Comment: Do not use `.lan` as a fake local TLD, or any other for that matter. Register a domain name and use it as a suffix for all your internal resources.
Answer: You need to have separate server blocks for your config.
server {
    listen 127.0.0.1:80;

    server_name phpmyadmin.localhost;

    ...
}

server {
    listen 192.168.1.123:80;

    server_name 192.168.1.123 phpmyadmin.ubuntu-pc.lan;

    ...
}


ANCOVA with one factor/independent variable and two covariates in R

Question: I did a study in which participants were randomly divided into 3 conditions, each of which completed a different memory test (with different difficulty levels). Additionally, all participants did an IQ test.
I want to know if memory results are different depending on the test they did, while controlling for IQ and gender. So my covariates are IQ and gender, but it's important to note that there's also a correlation between them.
I have performed two separate ANCOVAs but I want to have them in a single one, if possible. My code currently looks like this:
aov(memory ~ IQ + condition, df)
aov(memory ~ gender + condition)
Note: Results from memory tests are discrete values ranging from 0 to 16. I have 433 participants and they were only tested once.
Comment: I don't think that `anova_test` is a function in the basic R packages. Please _edit the question_ to say what package provided that function. Also, please include in editing the question more details about the study: in particular, then nature of the "memory test" outcome (continuous, or successes/failures or...), how many participants, and whether individual participants were tested more than once. There should be no problem in accomplishing what you want if your study is large enough and the outcome values are handled properly, but the details are important for providing a good answer.
Comment: @EdM thanks for your comment, I have edited my question accordingly :)
Answer: There's no problem with having multiple covariates in ANCOVA, even though the emphasis in courses might be on single covariates. ANCOVA can be considered just a particular case of a regression model, where a categorical predictor is of main interest and you want to adjust for other categorical or continuous predictors.
There's also no problem in having correlated predictors. That might inflate the standard errors of the coefficient estimates for the correlated predictors, but with a randomized assignment of memory test type that shouldn't affect your main evaluation of memory test results versus memory test type.
The bigger problem here is the nature of your outcome measure, which is discrete with only 17 levels. That type of outcome is often hard to reconcile with the assumption of a normal distribution of observed residuals around model predictions, or more precisely, the normal distribution of coefficient estimates that a normal distribution of residuals helps ensure. The assumption about a normal distribution of coefficient estimates forms the basis of things like F-tests for evaluating statistical significance.
As you have a reasonably sized study, if your outcome measures are generally near the middle of the scale you might get away with the following simple model in R:
linModel <- lm(memory ~ condition + IQ + gender)

but you should then check carefully whether the assumptions are met, for example by examining the plots returned by plot(linModel).
If the assumptions aren't met, then you could consider modeling repeated bootstrap samples of the data to get more reliable estimates of coefficient standard errors. You also could consider ordinal logistic regression, which makes no assumptions about the spacing of outcomes along the scale, instead of an ordinary least-squares model.


`UnsafeCell` shared accross threads with no locking - this can cause UB right?

Question: Consider the following code:
use std::{cell::UnsafeCell, io, net::TcpStream, sync::Arc};

use native_tls::TlsStream;

#[derive(Debug)]
pub struct TcpStreamRecv(Arc<UnsafeCell<TlsStream<TcpStream>>>);

unsafe impl Send for TcpStreamRecv {}
unsafe impl Sync for TcpStreamRecv {}

impl io::Read for TcpStreamRecv {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        unsafe { &mut *self.0.get() }.read(buf)
    }
}

#[derive(Debug)]
pub struct TcpStreamSend(Arc<UnsafeCell<TlsStream<TcpStream>>>);

unsafe impl Send for TcpStreamSend {}
unsafe impl Sync for TcpStreamSend {}

impl io::Write for TcpStreamSend {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        unsafe { &mut *self.0.get() }.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        unsafe { &mut *self.0.get() }.flush()
    }
}

pub fn tcp_split(stream: TlsStream<TcpStream>) -> (TcpStreamSend, TcpStreamRecv) {
    let inner = Arc::new(UnsafeCell::new(stream));
    let send = TcpStreamSend(inner.clone());
    let recv = TcpStreamRecv(inner);
    (send, recv)
}

My reasoning is as folows:
Safe code can obtain a TcpStreamSend and a TcpStreamRecv with the same underlying TlsStream.
If each of these is sent to a separate thread, it is possible to call TcpStreamSend::write and TcpStreamRecv::read at the same time. Each of these functions obtains a &mut reference to the underlying TlsStream.
Therefore, since it is illegal to have 2 mutable references at the same time, this code can cause UB and should be considered unsound. Is this correct?
My coworker assured me that "if it works, it works", and the code indeed appears to function normally most of the time, apart from some random occasional panics. In my understanding, however, it can cause unpredictable problems anywhere in our codebase, and should be rewritten immediately. Did I miss something?
By the way, I did some research and the code seems to be inspired by this SO answer which is more convoluted, but, as far as I can see, equally bad.
Comment: The code is unequivocally UB.  However, it is strange that `&native_tls::TlsStream` doesn't implement `Read` and `Write` like `&std::net::TcpStream` does.  My best guess is that this is an oversight in the implementation of `native_tls`, but don't quote me on this.  It does unfortunately mean that you will have to wrap `TlsStream` in a `Mutex` if you want to share it across threads unless you switch to a different TLS crate.
Comment: To answer your second question: in production code, I've always seen a comment before `unsafe` blocks that explain why the unsafe requirement is upheld, and a comment before `unsafe` functions to explain what unsafe requirement must be upheld on call.
Comment: Contrary to what 2 commenters prior have stated your code does **not** include any UB in and of itself, though your assessment that it's *unsound* as it can be used to invoke UB from safe code (and very likely is being used in a way that does so) is very much correct.
Comment: @L.F. It is hard to impl `Read` and `Write` for `&TlsStream` because it is generic. It is possible, though, with HRTB.
Comment: Yes, this is indeed undefined behavior. You should use a mutex (or a read-write lock in some related cases). For future reference, if you are implementing some concurrency primitive that uses an underlying `UnsafeCell`, consider using [SyncUnsafeCell](https://doc.rust-lang.org/std/cell/struct.SyncUnsafeCell.html). The API is identical, but `SyncUnsafeCell` implements `Sync`, so you wouldn't have to manually implement unsafe traits for your own structs.
Comment: Yes, @cafce25's correction is what I meant to say - UB is invoked as soon as `read` and `write` are called synchronously on `send` and `recv`, which is most likely what the caller of `tcp_split` will do.
Comment: @MarkSaving I argue the opposite: you should use bare `UnsafeCell` and impl `Send` manually. For two reasons: the least important is that `SyncUnsafeCell` is nightly-only. The more important is that by writing `unsafe impl Sync` manually, you get the chance to write a `// SAFETY` comment explaining the safety rationale. The main reason for `SyncUnsafeCell` existence is for use in `static`s, to not have to write your own type.
Answer: Definitely unsound.
Simply having two overlapping &mut references in existence at the same time in Rust is undefined behavior, which will happen with this if two threads call read and write at the same time. This is a problem even for non-threaded code - Rust assumes that no &mut references can alias.
Splitting a TlsStream without a lock like this is just not possible. Even if the read and write implementations in TcpStream are independent, TlsStream may need to alter how it writes based on messages from the server (ex. rekeying), which will require that the reader alter state that the writer uses.


What is the purpose of multiple ethernet ports on my modem?

Question: My office has a static IP and I wanted to set up another one. After calling up my ISP and getting another static address, I tried to plug a second router into my NetVanta 838T modem, but could not connect to the internet. I tried the new router in the first plug and it worked, so I think the settings are correct.
I called up my ISP and they told me it was not possible to do this with the hardware I have.
Is this true, and if so, what is the purpose of having 4 ethernet ports on that modem?

Edit: Added in a switch between the routers and the modem and it accomplishes what we wanted, but I still don't understand the purpose of the extra ethernet ports on the modem.
Comment: I assume the piece of hardware that you have is a Modem / Router combo, probably offered _by_ your telco. If it is a combo device, then the _modem_ aspect is not actually exposed to you, the end user, but is instead hard wired to the 4 port [_switch_](https://en.wikipedia.org/wiki/Network_switch) available on the case.
Answer: The ethernet ports are for connecting multiple devices within your LOCAL network so they can communicate with each other.  The modem, assumingly, from your ISP provides ROUTING functions to the ISP from your network but only on the specific port that's allowed to do that.
The other ethernet ports would allow you to plug in say a PC, laptop and printer and them be all on the same subnet and be able to "talk" to each other.  Basically it becomes a "dumb" switch for you to have a local network without having an additional switch.
EIT
Straight from the NetVanta documentation:

The NetVanta 838T is a Carrier Ethernet Network Termination Unit (NTU)
  that     terminates up to eight e.SHDSL copper pairs.  Four 10/100
  Ethernet ports are provided for customer use.

So to reiterate what I said, they are for creating a LOCAL network (LAN) as opposed to adding an additional switch.
Comment: We put another switch in between the modem and the original router and it actually does what we originally wanted. Now we have two separate routers with different static, global ip addresses. I guess my original question still stands, though what is the purpose of those additional ports, if they are not acting like a switch? If I plugged in a computer into one of those ports would it attach to my local network? If so, which one?
Comment: @horriblyUnpythonic They should be acting like a switch. What you're reporting is very strange. Could you explain in more detail precisely how router 2 doesn't work? Does the port light come on? (It might be an MDI/MDIX conflict.)
Comment: It did come on, when I plugged in the second router, but the router didn't connect to the internet. It did work when router 2 was connected to the first port. Router 1 stopped working when plugged into any other port, although I didn't explicitly try various combinations of ports and the order in which they were connected. I thought it might be an MDI/MDIX thing (after finding out what that meant), but the doc here says that the ports should be 'auto sensing' and 'auto MDI/MDIX'. https://portal.adtran.com/pub/Library/Data_Sheets/Default_Public/61172838G1-8_NV838T.pdf


How can I reimplement this function as tail-recursion or otherwise use less memory?

Question: I need to recursively do the following calculation.
For any n between 1 and 30 I need to consider all possible combinations of addition or subtraction from 1 to n. So, for example if n = 5:
1 ± 2 ± 3 ± 4 ± 5 ± 6 = ?;

I need to find the number of possible expressions that equal the number itself. So for n = 5, only the following two expressions equal to 5:
5 = 1 + 2 + 3 + 4 − 5
5 = 1 − 2 − 3 + 4 + 5

My approach
I figured out how to create a recursive tree where each level of recursion will add or subtract the 'depth'. So as as result, at the final depth, the nodes will already have the calculated sum - all I have to do is check whether they equal to the initial number.
Recursive Tree Image
This works alright, but at larger numbers n>26 I suffer from huge memory consumption and the program takes too long. A little maths makes it clear why.
So how can I optimise this? I've been trying to turn it into tail-recursion but it's not working out for me... I simply don't understand how to implement that for when I have two recursive calls.
Here is my code:
Tree structure and creation function
typedef struct nodes {
    unsigned int value;
    struct node* pos;
    struct node* neg;
} node;

node* addNode(int data){

    node* newNode = (node*)malloc(sizeof(node));
    newNode->value = data;
    newNode->pos = NULL;
    newNode->neg = NULL;

    return newNode;
}

Function that builds my tree
node* buildTree(int depth, int data){

    node* nNode = addNode(1);

    if(depth==n+1){
        if(data == n) {
            result++;
        }
        return nNode;
    }

    else{
        nNode->pos = buildTree(depth+1,data+depth);
        nNode->neg = buildTree(depth+1,data-depth);
        return nNode;
    }
}

Global scope variables & main:
int result = 0;
int n;

int main(int argc, char **argv)
{
    scanf("%i",&n);
    buildTree(2,1); //build tree starting with recursion depth = 2, first node value = 1.
    printf("%i\n",result);

    return 0;
}

Please help — I've been stuck too long on this.
Comment: Why does your example with `n = 5` include `± 6`?  Either `n = 6` or you should drop that term, shouldn't you?
Comment: Is one of your problems that you unconditionally create a node but never free any node?  If you create a node on entry, shouldn't you free it before leaving?
Answer: I don't think you need a tree for this.
Some simple recursion should do:
#include <stdio.h>

void f(int current_sum, int current_depth, int target_depth)
{
    if (current_depth > target_depth)
    {
            // Here you have the final result for this path
        printf("%d\n", current_sum);
        return;
    }
    f(current_sum+current_depth, current_depth+1, target_depth);
    f(current_sum-current_depth, current_depth+1, target_depth);
}

int main(void) {
    f(0, 1, 3);   // I use n=3
    return 0;
}

Output:

6
0
2
-4
4
-2
0
-6

TIP: You can improve run time performance a lot by noticing that the last half numbers are the negative of the first half. Use something like:
    f(current_sum+current_depth, current_depth+1, target_depth);
    if (current_depth != 1)
    {
        f(current_sum-current_depth, current_depth+1, target_depth);
    }

to achieve that.
Comment: thank you, recursion just became much clearer to me because of this!


Test load on Web Server

Question: I want to benchmark my server to the best configuration for Apache and MySql. I want you to ask if do you know any script that simulates various users browsing on the website? PD: I'm using DebianThanks
Answer:
JMeter
Grinder
Apache
Benchmark (AB)
Answer: I'd suggest a cloud solution if you're planning to stress your application to the max.
Here's why, tools which are initiated by your workstation/server are limited to your local resources.
It can't be your just producing hits to simulate traffic, you have to keep in mind that browsers open simultanious connections to your Server (i think that would be 4 up to 6, correct me if i'm wrong).
There are a few cloud-stresstesting tools and all of them got some free options, but they get expensive. It's still a got option if you want to test the scalability of your application.
Some examples of Cloud stresstools

load impact
loadstorm
browsermob

and some more in depth comparision
http://www.brickyardtech.com/blog/2011/11/review-of-cloud-based-load-testing-services/

Test load on Web Server


Looking for the maximum and minimum of a modulus in the unit disk.

Question: I am struggling with something. I need to find the maximum and minimum value of $\left|z^{2 n+m}+i a z^{n+m}+z^{m}\right|$ when $\left| z \right| \leq 1$ (with $a\in\mathbb{R}$ and $m,n \in \mathbb{N}_0$).
I have reasoned like this, but I am not sure about my process. We are looking for the maximum value in the unit disk of $\left|f(z)\right|$, where $f(z) := z^{2 n+m}+i a z^{n+m}+z^{m}$. This function $f(z)$ can also be written as:
$$f(z) = z^m(z^{2 n}+i a z^{n} +1)$$
And since $z^m$ is the m-th power of a complex number, it is just escalating whatever is in the parentheses. Therefore, looking for $z$ that maximises $f(z)$ is equivalent to looking for the $z$ that maximises $|g(z)|$, with $g(z) := z^{2 n}+i a z^{n} +1$. Since $g(z)$ is a complex polynomial, it is analytic. And because we are looking at an analytic function in a closed set, the Maximum modulus principle implies that the maxima and minima will be reached in the border of the set (in the unit circle). So, if I find the condition that maximises $|g(z)|$, we can use that to determine the maximum of the original function. I know that all $z$ in the unit circle can be expressed as $z = \text{e}^{i\theta}$, and therefore:
$$g(z) = g(\text{e}^{i\theta}) = \text{e}^{2n\theta i} + ia \text{e}^{n\theta i} + 1$$
And the condition that would make the modulus maxima would be that both of those terms in the sum had the same phase, and this is where I think I am mistaken. I am not very sure how to proceed, or if these reasonings are correct.
Thank you all.
Answer: If $m \ge 1$ then clearly the minimum is $0$ (attained at $z=0$) and the maximum is attained on the unit circle; we can assume $n \ge 1$ (as if $n=0$ the function is constant on the unit circle, so there is nothing to prove) and since then $z^n$ covers the unit circle when $z$ covers the unit circle, one needs to find the maximum of $|w^2+iaw+1|$ for $|w|=1$
A simple computation gives:
$$|w^2+iaw+1|^2=(w^2+iaw+1)(\bar w^2-ia\bar w+1)=$$ $$=2+a^2+2\Re w^2 \le 4+a^2$$ with equality for $w=\pm 1$ so the maximum is $\sqrt {4+a^2}$
If $m=0$ (and $n \ge 1$ as $n=0$ gives a constant function), one notes that the quadratic $w^2+iaw+1$ in $w=z^n$ has roots that multiply to $1$ so they are either on the unit circle (this actually happens only for $a=0$), or one is inside, hence the minimum is still zero and the maximum is as above
Comment: What do you mean with "the function is constant on the unit circle and since then $z^n$ covers the unit circle when $z$ covers the unit circle"? What do you mean by covering?
Comment: If $n=0$ the function is constant on the unit circle being clearly just $2+ia$ (edited for clarity); if $n \ge 1$ the function $z \to z^n$ is surjective on the unit circle, so for our purposes it is enough to consider the function in $w=z^n$ which is a quadratic
Comment: Okay, I understand now. Thank you very much!
Comment: happy to be of help
Comment: Sorry, what is the second step of the "simple computation"? I do not understand how that is immediate (sorry, I am tired).
Comment: just multiply term by term using $w\bar w=1$ and notice that the terms with $iaw, -ia\bar w$ cancel out
Comment: Oh man, that's right, I thought this was some identity I wasn't understanding. Thanks!