How many times has a 4 game sweep occurred during the Stanley Cup finals?

Question: After their win on June 9, 2014, the LA Kings are one game away from winning the Stanley Cup. If they win their next game, they will sweep the NY Rangers to win the Stanley Cup.
Since the adoption of the seven-game series in 1939, how many times has a 4 game sweep occurred during the Stanley Cup finals? Please list the team and the year of accomplishment.
Comment: For reference, the following years also contained sweeps during the Stanley Cup finals, but these finals were not won in 4 games: [1935](http://www.hockey-reference.com/playoffs/NHL_1935.html), [1932](http://www.hockey-reference.com/playoffs/NHL_1932.html), [1930](http://www.hockey-reference.com/playoffs/NHL_1930.html), [1929](http://www.hockey-reference.com/playoffs/NHL_1929.html)
Comment: In addition to @MASTERMIND_ED's comment, the best of 7 series were adopted by NHL starting 38-39.
Comment: [List of Stanley Cup Champions](https://en.wikipedia.org/wiki/List_of_Stanley_Cup_champions#NHL_champions_.28since_1927.29) on Wikipedia has also result of the series in the final.
Comment: Related, or maybe "anti-duplicate": https://sports.stackexchange.com/q/26049/3671
Answer: There have been 20 Stanley Cup finals sweeps. The list below is also available in this answer, at TSN, or any respected source that tracks NHL statistics.

Year
Winning Team
Losing Team

1998
Detroit Red Wings
Washington Capitals

1997
Detroit Red Wings
Philadelphia Flyers

1996
Colorado Avalanche
Florida Panthers

1995
New Jersey Devils
Detroit Red Wings

1992
Pittsburgh Penguins
Chicago Blackhawks

1988
Edmonton Oilers
Boston Bruins

1983
New York Islanders
Edmonton Oilers

1982
New York Islanders
Vancouver Canucks

1977
Montreal Canadiens
Boston Bruins

1976
Montreal Canadiens
Philadelphia Flyers

1970
Boston Bruins
St. Louis Blues

1969
Montreal Canadiens
St. Louis Blues

1968
Montreal Canadiens
St. Louis Blues

1960
Montreal Canadiens
Toronto Maple Leafs

1952
Detroit Red Wings
Montreal Canadiens

1949
Toronto Maple Leafs
Detroit Red Wings

1948
Toronto Maple Leafs
Detroit Red Wings

1944
Montreal Canadiens
Chicago Black Hawks

1943
Detroit Red Wings
Boston Bruins

1941
Boston Bruins
Detroit Red Wings
Answer: Here ya go!
<code>Year       Winning Team       Losing Team
1998    Detroit Red Wings   Washington Capitals
1997    Detroit Red Wings   Philadelphia Flyers
1996    Colorado Avalanche  Florida Panthers
1995    New Jersey Devils   Detroit Red Wings
1992    Pittsburgh Penguins Chicago Blackhawks
1988    Edmonton Oilers     Boston Bruins
1983    New York Islanders  Edmonton Oilers
1982    New York Islanders  Vancouver Canucks
1977    Montreal Canadiens  Boston Bruins
1976    Montreal Canadiens  Philadelphia Flyers
1970    Boston Bruins           St. Louis Blues
1969    Montreal Canadiens  St. Louis Blues
1968    Montreal Canadiens  St. Louis Blues
1960    Montreal Canadiens  Toronto Maple Leafs
1952    Detroit Red Wings   Montreal Canadiens
1949    Toronto Maple Leafs Detroit Red Wings
1948    Toronto Maple Leafs Detroit Red Wings
1944    Montreal Canadiens  Chicago Black Hawks
1943    Detroit Red Wings   Boston Bruins
1941    Boston Bruins       Detroit Red Wings
</code>
Comment: Can you add a source?
Comment: I like your answer, but please also include to source.


Investigate uniqueness of the following differential equation

Question: This is Problem 1.13 from Teschl's book (ODEs and Dynamical Systems). The equation is as follows:
$$
x' =
\begin{cases}
-t\sqrt{|x|}, &\text{ if } x \ge 0\\
t\sqrt{|x|}, &\text{ if } x \le 0.
\end{cases}
$$
It asks to show that the initial value problem $x(0) = x_0$ has unique global solution for every $x_0 \in \mathbb{R}$. There is a hint saying that if $x(t)$ is a solution so is $-x(t)$ and $x(-t)$, so it suffices to consider $x_0 \ge 0$ and $t \ge 0$. For $x_0 > 0$, I managed to find the solution
$$
x(t) =
\begin{cases}
(\sqrt{x_0} - \frac{1}{4}t^2)^2, &\text{ if } |t| \le 2x_0^{1/4}\\
0, &\text{ otherwise. }
\end{cases}
$$
It is easy to see that this is a solution by using the Mean Value Theorem when calculating $x'(t)$ for $t = \pm 2x_0^{1/4}$, because $x$ is continuous at these points and $x'(\theta) \to 0$ as $\theta \to t$. For $x_0 = 0$ the obvious solution is $x(t) = 0$ for all $t$. The problem is that I do not know how to show these solutions are unique.
If $x$ is a is solution and $x_0 > 0$, then by continuity there is an open interval $(t_1, t_2)$ containing $0$ where $x(t)$ is positive, and so it makes sense to write
$$
-s = \frac{x'(s)}{\sqrt{x(s)}},
$$
for $s \in (t_1, t_2)$, and to integrate both sides
\begin{align}
-\frac{1}{2}t^2 = \int_{0}^t -s\ ds = \int_0^t \frac{x'(s)}{\sqrt{x(s)}}\ ds = 2(\sqrt{x(t)} - \sqrt{x(0)}).
\end{align}
This yields $x(t) = (\sqrt{x_0} - \frac{1}{4}t^2)^2$ for $t \in (t_1, t_2)$. Assuming that $(t_1, t_2)$ is a maximal interval where $x(t)$ is positive, and since $(t_1, t_2) \subseteq (-2x_0^{1/4}, 2x_0^{1/4})$, we see by continuity of $x$ that $x(t_1) = x(t_2) = 0$ and thus $(t_1, t_2) = (-2x_0^{1/4}, 2x_0^{1/4})$. How do I show that $x(t) = 0$ when $t$ is not in this interval? I suspect the same technique in this last step can be used to show that $x(t) = 0$ when $x_0 = 0$.
Answer: Alright, I've done it. Suppose first $x_0 = 0$ and let $x(t)$ be a solution. Assume by contradiction that $x(t) > 0$ for some $t > 0$ and set
$$
d = \inf\{a < t: x(s) > 0 \text{ for every } s \in (a, t) \}.
$$
By continuity $d$ is well defined, $0 \le d < t$ and $x(d) = 0$. By the Mean Value Theorem, we see that
$$
x(t) = x(t) - x(d) = x'(\theta)(t - d),
$$
for some $\theta \in (d, t)$, so
$$
x(t) = -\theta\sqrt{|x(\theta)|}(t - d) \le 0
$$
which is a contradiction. If $x(t) < 0$ the proof should be analogous and we can do the same thing to finish what I wrote above for the case $x_0 > 0$.
Comment: Yes, this **part** is O.K. I would only define $d$ as the supremum of the set of those $a<t$ such that $x(a)=0$ (easier to show it is nonempty). Remember that you should also show that we have uniqueness at each point where the value of the solution is nonzero, and that any solution is global. Can you do that?
Comment: @user539887 What do you mean by "uniqueness at each point where the value of the solution is nonzero"? I have shown it is unique for every choice of $x_0$, isn't that all there is to it?
Comment: You showed only that the solution cannot branch at a point where its value is $0$. At other points it cannot branch, either, but here one needs to use, for example, the local Lipschitz continuity at such a point. Or, alternatively, you can argue that your arguments in the last paragraph of your question show that the obtained formula is the only possible.
Answer: To prove uniqueness, let's assume two solutions $x(t)$ and $y(t)$, $x(0)=y(0)=x_0>0$. Let $u=x-y$ with $u(0)=u_0=0$. We subtract the equations for $x$ and $y$ and obtain
$$
u'(t)=-t\frac{u}{\sqrt{x}+\sqrt{y}},
$$
which yields
$$
u(t)=u_0 \exp\left(-\int_0^t \frac{s}{\sqrt{x(s)}+\sqrt{y(s)}}ds\right).
$$
Since $u_0=0$, then $u\equiv0$.


Ajax callback never called / triggered

Question: I'm working on a payment gateway, so I've created a BasePaymentOffsiteForm form where I'm trying to make an ajax callback, but it is not working.
Can you help me to know what is wrong with my code?
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['content'] = [
      '#type' => 'container',
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    $form['content']['mobile_phone'] = [
      '#type'   => 'textfield',
      '#title'  => $this->t('Mobile phone'),
    ];

    $form['content']['validate_client'] = [
      '#type' => 'button',
      '#value' => $this->t('Validate Client'),
      '#ajax' => [
        '#callback' => [get_class($this), 'clientValidateForm'],
        'event' => 'click',
        'wrapper' => 'validate-phone-number',
      ],
    ];

    $form['content']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromUri($form['#cancel_url']),
    ];

    return $form;
  }

  public static function clientValidateForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Pay',
    ];
    return $form['submit'];
  }

It never gets in cientValidateForm method.
Comment: You have to add any form elements in the form definition. They cannot be added in the ajax callback.
Answer: You're never making it to your callback because you don't have your #ajax array defined correctly, callback should not be defined as a hashed key. Take a look at the Adding an AJAX event example on d.o.
This should work:
$form['content']['validate_client'] = [
  '#type' => 'button',
  '#value' => $this->t('Validate Client'),
  '#ajax' => [
    // Change the callback key and update your callback value.
    'callback' => [$this, 'clientValidateForm'],
    'event' => 'click',
    'wrapper' => 'validate-phone-number',
  ],
];

Also note that Jaypan is right, you can't define new elements in your validation callback so you'll have to change that too. You may want to set a $form_state value in your validation handler and use that to add your element inside your build method. You may also need to update the wrapper value in your #ajax definition to align with the other changes.
Comment: Thank you, it worked for me, I just add the # in callback index just for testing, but the use of $this without get_class was the solution.
Comment: Awesome! Feel free to mark this answer is accepted if it solved your problem.

Ajax callback never called / triggered


How secure is a headless linux server with passwordless sudoers accounts

Question: The only means of accessing the server console is via ssh, using keys. Also via exploits of various services the server is running.
My administrative account (belongs to sudo group) has no password, but root does.
Is that considered unsecure?
Comment: So you can basically `su sudoers` from any account on the system and then run `sudo su` without password?
Comment: Don't know about former (says "no password entry for 'sudoers'"), but for the latter: yes.
Comment: Does `su ${your_admin_username}` work? If yes you basically have root access from every account on your system.
Comment: Yes, it does. Please remember that this is a headless server - not meant for anyone to even have access to shell except for my administrative account. Also, one would have to know name of my account.
Comment: Could the one with the downvote explain the downvote?
Comment: Secure vs. insecure is not a binary affair. There are always ways to improve a system, and you should be striving to do that. IMHO it is foolish to not have a password on your user account.
Comment: By philosophy and design votes are anonymous and **neither voting [up](//$SITEURL/help/privileges/vote-up) nor voting [down](//$SITEURL/help/privileges/vote-down) requires any mandatory explanation**. The tooltip that appears when your mouse pointer hoovers over the down button states: *"this question does not show any research effort; it is unclear or not useful"*. Also questions can attract a down vote when not [well written](http://meta.serverfault.com/a/3609/37681), not quite [on-topic](http://serverfault.com/help/on-topic) or missing details.
Comment: @JennyD : agreed, but I googled on the subject and turned up nothing of use. I'm not really proficient at Linux and for a moment there it seemed a good idea as a key (as long as it's sufficiently protected) seems quite secure. I failed to realise that listing and impersonating users is easy in Linux (which sd40's answer explains well). This was a simple question which got a straight answer explaining why it's not a good idea. So, having an explained downvote would tell me what I did wrong asking the question. As it is, I still believe the question has its place here and the downvotes puzzle me
Answer: "Is that considered unsecure?"
Based on the information provided. I would have to say yes.
Here are some things I would be concerned about:

What's to prevent someone from going to the server location, attaching a monitor, putting the server into single user mode, and resetting the root password?
How are your ssh keys stored? Are they on an unencrypted laptop, flash drive, or other disk that could be easily stolen or misplaced?
Is there a drac or ilo connection on the server with default or weak passwords that would grant someone console access?
Is the console logged out? I've found many servers that when the console is accessed, the root user is still logged in from the last time it was accessed.
Having a user without a password and with sudo access is a huge security hole no matter how it's exploited.
Do you allow only key based authentication? If not, I would edit the ssh config to prevent password authentication attempts in case someone stumbles on your unprotected user account.
Configuring a password for your user account takes two seconds, just do it.
Comment: Thanks, this answers my question well. I thought using keys as a method of logging in would be secure, but forgot about all the other implications.
Answer: To sum up, you have an unprotected administrator user whose sole protection is that the username is uncommon (maybe). From this account, you can sudo without password so anyone who manages to run under your administrative user is essentially root.
/etc/passwd is readable by everyone which makes finding out the username fairly trivial so your administrator account basically has no security.
Like most systems, it is not designed to be accessed by anyone but its administrator(s). Unfortunately, like most systems, you have services exposed to the outside world and that makes your server vulnerable to a lot of potential attacks you (and most of the rest of the world) might not be aware of.
Granted, if you have no other users it lessens the risk but still, allowing to su to your administrator account which is in turn, capable of running root commands without protection is careless to say the least.
If you really can't stand the hassle of typing your sudo password, consider protecting your administrator user with a password, and removing the password prompt for your user in /etc/sudoers.
That still won't be great security, but at least your administrator account won't be as easily accessible.


Varnish on Debian - libvarnish.so.1 not found

Question: I'm trying to install Varnish on Debian 6.0.3 and am getting the following error when I try to start the server
/usr/sbin/varnishd: error while loading shared libraries: libvarnish.so.1: cannot open shared object file: No such file or directory
Runnig ldd 'which varnish' tells me this:
libvarnish.so.1 => not found
libvarnishcompat.so.1 => not found

I also found this question on the same topic, but my problem is that the file really is missing...
Answer: you need to run:
apt-get --reinstall install libvarnish1

Comment: `libvarnish1 is already the newest version.`
Comment: run command "updatedb", then run "locate libvarnish.so.1", and tell me what output you get.
Comment: Removed all varnish files, installed varnish again and the files are there now. Starting varnish words. Thanks for your input!


Is there any other way to create a "settings" node without having to create a Content Type?

Question: I need to create something like a node with settings. This will have custom fields, images, etc... Just like a content type, but without having to create one of them.
Why? I think it's strange having to create a content type when I need to create only one node with that structure.
I know this sounds weird, but just wonder if there is another way?
Thanks
Answer: The clean way is to create a custom module or theme with settings you need.  Examples For Developers shows you how to do it.
If you need settings, you need them because something will use them. So just adding a proper form shouldn't be too big overhead. And if you keep your settings in a way that makes possible for field to cease existing, you need to add more lines of code to safeguard against such situations. You don't want that. It's disaster waiting to happen.


Drush sql-sync failing with Ubuntu 14.04

Question: I'm having no luck with sql-sync, there's two seemingly unrelated errors it's throwing at me which I'll detail below.
I've been successfully sql-sync'ing the same site to another server, so I'm pretty sure it's the remote server, not the local server, that is causing the problems. The remote server MySQL version is: 5.6.19-0ubuntu0.14.04.1 (Ubuntu)
1) Adding the --create-db switch gives me:
ERROR 1044 (42000) at line 1: Access denied for user 'user'@'localhost' to database 'database'
2) Regardless of whether or not I use the --create-db switch, I always get this:
ERROR: ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mode is enabled and mysql is run in non-interactive mode. Set --binary-mode to 1 if ASCII '\0' is expected. Query: '��T'.

Any ideas?
Comment: Can you post the output of the command using the `-v` flag?
Answer: So it turns out I'd installed Drush 6 on the remote server, while my local version was Drush 7. Upgrading solved the problem.


Is the $\mathfrak m$-adic completion of a radical ideal again a radical ideal?

Question:
Let $(R,\mathfrak m)$ be a local (Noetherian) ring and let $\hat{R}$ be its $\mathfrak m$-adic completion. Let $I$ be an ideal of $R$ which is a radical ideal. Is it then also true that $\hat{I}$  (the $\mathfrak m$-adic closure of $I$ in $\hat{R}$) is a radical ideal?

I am asking this question being interested mainly in the case where $R$ is $\mathbb{C}\{x_1,\dots,x_n\}$ - the ring of convergent power series over $\mathbb{C}$ (and hence $\hat{R} = \mathbb{C}[[x_1,\dots,x_n]]$, the ring of formal power series).
Comment: But yes, this answers the case $n=1$ (which, however, is quite different from the general case) in the affirmative: $\mathbb{C}\{x\}$ is (for n=1) a principal ideal and its only ideals are $0$ and $$, and the completion of $$ is generated by $x^{n}$ in $\mathbb{C}[[x]]$.
Comment: I'm hampered a bit by not knowing about $C\{x\}$ . But maybe this will help: $C[[x]]$  is a chain ring with exactly two prime ideals $(0)$  and $(x)$  (the remaining ideals are $(x^i )$  and the whole ring, which are clearly not prime.) That means that the only radical ideals of $C[[x]]$  are those two prime ideals (since radical ideals are intersections of prime ideals.) Does it make sense that all radical ideals of $C\{x\}$  would get mapped to those two ideals? If not, then I think your question is decided.
Comment: Sorry, i meant the multivariate case, i.e. $x = (x_{1},\dots, x_{n})$.
Comment: OK: I guess it remains to be seen if requiring $n>1$ changes things so that it's possible. Seems unlikely though, if it doesn't work in the single variable case.
Comment: Yeah, this could be an edge case somehow. Maybe this ring really gets its act together after $n=1$ and magically gets better about where it sends ideals. Commutative algebra is pretty magical IMO :)
Answer: As  $\hat{R}/\hat{I}\simeq \widehat{R/I}$, you are asking whether $R/I$ is analytically reduced. This is true when $R$ is excellent.
It is known that $R=\mathbb C\{ x_1,\dots, x_n\}$ is excellent (EGA IV.7.8.4.v), so the answer to your question is yes in this case. But beware that there exist non excellent noetherian local rings (even discrete valuation rings).
Comment: Thanks for the answer! Do I get this right that this holds for arbitrary ideals (of $\mathbb{C}\{x_{1},\dots,x_{n}\}$)? So that in the process of "completion" all the possible nil-potent element of $R/I$ vanish?
Comment: Yes this holds for all $I$ in the right $R$. The completion for excellent local rings doesn't add nilpotent elements. But if you start with nilpotent elements in $R/I$, they will stay in the completion because the latter contains $R/I$.
Comment: So the ideal $I$ has to be a radical ideal ( which is equivalent to $R/I$ being reduced) or otherwise $\widehat{R/I}$ will contain the nilpotent elements of $R/I$?
Comment: @Sebastian: Yes, absolutely.


pip freeze call with subprocess - No such file or directory

Question: I am trying to write a requirements.txt file from within a Python script (Python 2.7, Ubuntu 14.04). Following the suggestion here I tried
import subprocess

with open("requirements.txt", "w") as f:
    subprocess.call(["pip freeze"], stdout=f)

but for a reason I don't know I get an error:
OSError: [Errno 2] No such file or directory

The folder where the script is run is writeable. What can cause this problem?
Answer: Try this instead:
import subprocess

with open("requirements.txt", "w") as f:
    subprocess.call(["pip", "freeze"], stdout=f)

The "No such file" it means is "pip freeze". The example you cited didn't spell out how to pass command line arguments.


Allow user to change views template

Question: I have a view configured with a custom template. Now I need to represent the same information arranged in two different ways. What I want is for the user to have an option to change between the three different templates. This doesn't seem to out of the ordinary but I am having trouble finding an example.
Using Drupal 7.
Comment: Which views template are you using?  I'm sure you know, but there are quite a few templates that could be used to modify the output of a view.
Comment: If these are page views, eg `www.example.com/path/to/view`, you could set up multiple page displays, eg, `www.example.com/path/to/view/viewed/differently` and `www.example.com/path/to/view/viewed/another/way` and then have templates for each page display that display it however you want.  Of course, it would be up to you to include links to those other paths on your page, but I hope that's trivial.
Answer: I would build the different displays as separate blocks and then use the quicktab module.
https://drupal.org/project/quicktabs
That way, it will be very easy to switch between the blocks.
Configuration in quicktabs:

Results:

Allow user to change views template


Hide a menu item for admin user

Question: How can I remove a menu item when admin is logged in?
I used the following code but it doesn't seem to work.
<code>
function mymodule_menu_alter(&$items) {
     $items['item_x']['access callback'] = 'mymodule_menu_access_callback';
     $items['item_y']['access callback'] = 'mymodule_menu_access_callback';
}
function mymodule_menu_access_callback() {
  global $user;
  if ($user->uid == 1) {
    return FALSE;
  }
  return TRUE;
}
</code>
Answer: User 1 bypass access controls, so that wont work. You could have 2 menus as blocks and use the block system to control which to use.
You could also use theming/CSS to hide the menu.
Answer: what googletorp says is true but even more generally, you can't remove permissions to anything in drupal once they've been granted to a user (and user 1 is given all permissions).
i guess it depends whether you're just trying to hide it from display, in which case what googletorp suggests will be sufficient, or if you're actually trying to revoke access to a url from admin users.
a simple workaround (in addition to the suggestions from googletorp) to stop admins visiting said page would be to create a redirect using Rules that sends users with the admin rule somewhere else on that page.
Answer: You could assign a specific permission to the menu item, and then give that permission to a role that your non-admin users have.
$items['item_x']['access arguments'] = array('my special permission for this menu item');
hook_menu http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7
This will work, but keep in mind uid 1 (aka super admin) bypasses access control.

Hide a menu item for admin user


If $\epsilon_i$ are IID, does this always imply that $y_i|x_i$ is IID?

Question: Consider the linear model $y_i = \beta^Tx_i + \epsilon_i$. If we assume $\epsilon_i$ are IID, then for MLE, it is claimed that $y_i|x_i$ is also IID for all $i$.
Does this always hold? If not, when does it break down?
Comment: Hi David: Yes, exactly. Since you're referring  to the non-time series formulation, you don't have to worry about it. my bad for lack of clarity there. I haven't read his answer carefully yet but , according to Ben, I'm wrong so make sure that you understand his answer. In my experience,  it's probably correct :).
Comment: That should be true as long as none of $x_i$ predictors are  lagged $y_i$. But, since you labelled them $x_i$, that's probably not the case.
Comment: @mlofton What do you mean by lagged $y_i$? Is that time series terminology where $x_i$ is some prior instance of $y$, e.g., $y_j$ such that j < i?
Answer: Marginal independence is a weaker condition than conditional independence, so the former does not imply the latter.  If you are willing to make the stronger assumption that $\epsilon_1,...,\epsilon_n$ are IID conditional on the design matrix $\mathbf{x}$ (e.g., by assuming that the error terms are not only IID but also independent of the explanatory variables), then $y_1,...,y_n$ are also IID conditional on $\mathbf{x}$.
In regression analysis, we always proceed conditional on the explanatory variables, so the stronger assumption is the one that is made.  (Usually this is an assumption that the error terms are IID and that they are jointly independent of the explanatory variables.)  Often the conditioning statement is accidentally omitted in the statement of assumptions, and this is annoying becuase it leads to this kind of issue.
Comment: @Ben: I see what you mean now by conditional independence but, if that assumption wasn't true ( the conditional independence assumption ), then the regression wouldn't meet the standard OLS assumptions. Still your point is well taken and I understand better now that there  can be a difference between marginal and conditional independence.Thanks for clarification.
Comment: gotcha. thanks for the thorough explanation. very insightful.
Comment: Is the stronger form of independence the usual assumption that we make in OLS regression?
Comment: Somewhat related question that I have is in MLE with IID normally distributed errors, it states therefore that $p(y|x)$ is also normally distributed $\sim \mathcal{N}(x^T\beta, \sigma^2)$. I don't quite understand this. Why does it have to be conditional on $x$? Why can't it be the joint distribution of $x$ and $y$ that is normally distributed?
Comment: @David: All regression results are conditional on the $x$ values, and we make no assumption about the distribution of those values.  To see why this does not imply joint normality, consider what happens when $x_1,...,x_n$ are Bernoulli random variables (which does not breach any regression assumptions).  How do you get joint normality then?
Comment: Ah I see. That makes sense. All classification results are also conditional on $x$ values right?
Comment: Not sure what you mean by "classification" so not sure.
Comment: @mlofton: Indeed --- the usual assumption is that the errors are IID *and independent of the explanatory variables*, which is sufficient to establish them as conditionally IID.  What happens in these cases is that people are just not all that careful in stating their regression assumptions, and in particular, they often omit the conditioning without realising that this is a requisite assumption.


How do I recover Windows 10 with files recovered from a drive

Question: I had a drive failure about 2 months ago on my custom built PC with Windows 10 (probably professional version).  It was a Seagate drive and they sent the drive to recovery and sent back a USB slimdrive with all of the files recovered.
My question is:  How do I now recover back to Windows 10?
I was hoping I could copy those files onto a new drive and boot up Windows, but that results in "No MBR Found".  I also tried booting from the USB slimdrive, but that results in a different message telling me to select a proper boot device.
Comment: This appears to be off topic here. You may be able to get help on our sister site, [su].
Answer:
How do I now recover back to Windows 10?

Download a fresh Windows Setup-Media and reinstall windows 10 from there on your new drive. When done, copy only the files you need back from the stick to your drive.
Comment: You need to re-install all the programs on top of the freshly installed Windows. The registry contains so much installation-specific information that it is impossible to copy.
Comment: How would the registry be transferred so that all of the programs still work?
Comment: You *could* try to copy your user profile back (\users\name), but I doubt this would make you happy.


How to use system variable @@dataset_id in BigQuery view

Question: BigQuery has session-bound (or script-bound) system variables, described here. Within a session, I can declare the value of one of those variables, e.g. with something like:
set @@dataset_id = 'my_dataset_id';

Now, I'd like to have a view (which I plan on running within a session) that includes something like:
create view foo
as
select ...
from @@dataset_id.my_table

... this doesn't work. Nor does any form of quoting around that variable. It appears use of that variable simply isn't allowed to help identify the namespace of my_table.
If that's true, I'm struggling to see the value of that variable at all. Does anyone know if I can use those variables as so, or how to prevent needing to namespace-bound all instances of my_table? I'd like to manage these query scripts outside of BQ itself, and ideally without templating in everywhere (e.g. {dataset_id}.my_table)
Answer: I have tried to replicate your concern,
Please try below:
set @@dataset_id = "SampleDataSetID";

EXECUTE IMMEDIATE format("""
CREATE VIEW sampleView1 as (
  SELECT
    *
  FROM
    %s.sampleTable

);
""", @@dataset_id);

I used EXECUTE IMMEDIATE to run the sql dynamically ( using the variable that we set to the session.)
Output:


python unpack into multiple optional variables

Question: In Perl, I can do
($x1, $x2, $x3, $x4) = (1, 2)

Then $x1 and $x2 are 1; $x3 and $x4 are 'undef'
Does Python has something similar to this
(x1, x2, x3, x4) = [1,2]

so that x1 and x2 are 1; x3 and x4 are None?
I tried above, Python gives me error:
not enough values to unpack (expected 4, got 2)

I tried to use * operator for optional unpacking
(x1, x2, *x3, *x4) = [1,2]

but * can only be used once.
Thank you for your advice.
Background: the List (array) on the right hand side can be any length between 1 and 4. I use [1,2] just for example.
Comment: There is nothing similar in Python.
Comment: sad but may be true. thank you wim
Answer: You could add a few Nones and sweep any excess ones under the carpet (using the brush symbol * and the carpet symbol _ :-):
x1, x2, x3, x4, *_ = lst + [None] * 4

Comment: this is indeed the best we can get in python


How prove this function inequality $xf(x)>\frac{1}{x}f\left(\frac{1}{x}\right)$

Question:
Let $f(x)$ be monotone decreasing on $(0,+\infty)$, such that
  $$0<f(x)<\lvert f'(x) \rvert,\qquad\forall x\in (0,+\infty).$$
Show that
  $$xf(x)>\dfrac{1}{x}f\left(\dfrac{1}{x}\right),\qquad\forall x\in(0,1).$$

My ideas:
Since
$f(x)$ is monotone decreasing, $f'(x)<0$, hence
$$f(x)+f'(x)<0.$$
Let
$$F(x)=e^xf(x)\Longrightarrow F'(x)=e^x(f(x)+f'(x))<0$$
so
$F(x)$ is also monotone decreasing. Since $0<x<1$,
$$F(x)>F\left(\dfrac{1}{x}\right)$$
so
$$e^xf(x)>e^{\frac{1}{x}}f\left(\frac1x\right).$$
So we must prove
$$e^{\frac{1}{x}-x}>\dfrac{1}{x^2},\qquad0<x<1$$
$$\Longleftrightarrow \ln{x}-x>\ln{\dfrac{1}{x}}-\dfrac{1}{x},0<x<1$$
because $0<x<1,\dfrac{1}{x}>1$ so I can't.
But I don't know whether this inequality is true. I tried Wolfram Alpha but it didn't tell me anything definitive.
PS: This problem is from a Chinese analysis problem book by Huimin Xie.
Comment: Note that $xe^{x}$ is an increasing function if $x\in\left(0,1\right)$ so $xe^{x}<\frac{1}{x}e^{1/x}$ and then your inequality is false (the inequality in the comment).
Comment: oh,this inequality is not true,that mean my idea is not usefull?
Comment: maybe this books problem is not true? maybe we can take countexapmle?
Comment: @MarcoCantarini, you are maybe wrong. See http://www.wolframalpha.com/input/?i=plot+e%5E%7B1%2Fx-x%7D-%5Cdfrac%7B1%7D%7Bx%5E2%7D+from+0+to+1.
Comment: To clearify the comment of @MarcoCantarini: $x\mapsto xe^x$ is increasing for _all_ $x>0$. Thus $xe^x<1/xe^{1/x}$ for $x\in(0,1)$. Isnt, however, the function one should study $x\mapsto xe^{1/x}$?
Comment: Oh.Now I also don't know this inequality is true?$$e^{\frac{1}{x}-x}>\dfrac{1}{x^2}?$$,$$\Longrightarrow \ln{x}-x>\ln{\dfrac{1}{x}}-\dfrac{1}{x},0<x<1?$$
Answer: A tentative of proof:
Put  $g(x)=x^2f(x)-f(1/x)$. We have
$$g^{\prime}(x)=2xf(x)+x^2f^{\prime}(x)+\frac{1}{x^2}f^{\prime}(\frac{1}{x})=A+B+C$$
with $\displaystyle A=x^2(f(x)+f^{\prime}(x))$, $\displaystyle B=\frac{1}{x^2}(f(\frac{1}{x})+f^{\prime}(\frac{1}{x}))$, and $\displaystyle C=x(2-x)f(x)-\frac{1}{x^2}f(\frac{1}{x})$.
You have proved that $A<0$ and $B<0$. We have
$$C =x(2-x)f(x)-\frac{1}{x^2}f(\frac{1}{x})=-(x-1)^2 f(x)+\frac{1}{x^2} g(x)$$
Hence $\displaystyle g^{\prime}(x)-\frac{1}{x^2}g(x)<0$. Put $h(x)=g(x)\exp(1/x)$, we have $\displaystyle h^{\prime}(x)=(g^{\prime}(x)-\frac{1}{x^2}g(x))\exp(1/x)$, and hence $h$ is decreasing. As $g(1)=0$, we have $h(1)=0$, $h(x)>0$ for $x\in (0,1)$, and  we are done.
Comment: wa! Very very Nice! Thank you+1
Answer: I think the answer by @Kelenner is really good. This answer is just to prove the inequality
$$
e^{1/x-x}>1/x^2,\quad 0<x<1.\tag{*}
$$
that was discussed in the post/comments. We apply the logarithm, and since the logarithm is monotonically increasing, the inequality $(*)$ is equivalent to
$$
2\ln x>x-\frac{1}{x},\quad 0<x<1.\tag{**}
$$
Let
$$
g(x)=2\ln x-x+\frac{1}{x}.
$$
Then $g(1)=0$ and a differentiation (and simplification) gives
$$
g'(x)=-\frac{(x-1)^2}{x^2}.
$$
Hence $g'(x)<0$ for $0<x<1$ (so $g$ is monotonically decreasing) and it follows that $g(x)>0$ for $0<x<1$ and thus that $(**)$ holds. But $(**)$ was seen to be equivalent to $(*)$, and so the inequality $(*)$ is true.
Edit: I updated the solution without the change of variable, since I don't think it simplified anything in the end.
Comment: Nice!Thank you very much


how to restrict access to wp-login.php by IP address on nginx

Question: I have the following configuration for my wp site which is running on nginx 1.8.1

location ^~ /wp-login.php {
        allow 10.0.0.0/24;
        deny all;
}
location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
}

When I opening http://example.com/wp-login.php from my LAN, it downloads php file instead of passing it to fastcgi. After that I added all fastcgi lines inside of wp-login.php location and it began to work.
location ^~ /wp-login.php {
        allow 10.0.0.0/24;
        deny all;
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
}

But is that the only way? Can I make a ordering of passing specific pattern on nginx?
Thanks beforehand.
Comment: What's the question exactly?
Comment: Can I make a ordering of passing specific pattern on nginx?
Comment: [Sure](http://nginx.org/en/docs/http/request_processing.html#simple_php_site_configuration).
Answer: Once nginx has selected a location block to serve a request, it generally stays within that location block. Only if there's some kind of internal redirect - i.e. you do a rewrite on the URI, try_files or index or error_page - then the request will be re-evaluated and a different location might end up serving the request.
Rather than trying to write your configuration to pass a request through multiple location blocks, you should instead consider using include and configuration snippets kept in other files so that configuration shared between multiple locations can be kept in a single file - it's simpler, is the same effort saving when it comes to duplicated configuration and it performs better than redirecting.


Thread1: EXC_BAD_ACCESS (code =1 address=0xe07eca10)

Question: I have a problem with a UIView. This is the code:
<code>@property ( unsafe_unretained, nonatomic) IBOutlet UIView *formView;

- (IBAction)createNewProfile:(id)sender {
   [self loadDialogForm];
}

-(void) loadDialogForm{
    NSLog(@"load form");
    CGRect frame = self.view.bounds;
    CGPoint center = CGPointMake( frame.origin.x +    ceil(frame.size.width/2),frame.origin.y + ceil(frame.size.height/2));
    CGFloat width = floor(1 * frame.size.width) - OFFSET * 2;
    CGFloat height = floor(1 * frame.size.height) - OFFSET * 2;

    _formView.frame=CGRectMake(OFFSET, OFFSET, width, height); //here the error EXC_BAD_ACCESS (code=1 address=0xe07eca10)
    _formView.center=center;

    [self.view addSubview:_formView];
    [self performSelector:@selector(initialDelayEnded) withObject:nil afterDelay:1];
}
</code>
by a NSLog the frame of _formView is x= 0, y=0, width=300, height=390. Why this error?
Comment: check that _formView is not nil
Comment: Put the line that's failing inside a @try/@catch section and log the exception (and its `callStackSymbols`) to get a better explanation of the problem.
Comment: try to use CGRect frame = [self.view frame];
Answer: Use
@property ( nonatomic,retain) IBOutlet UIView *formView;
instead of
@property ( unsafe_unretained, nonatomic) IBOutlet UIView *formView;
Comment: I'm using ARC that not want retain.
Comment: @ConicaDegenere Yes you do - or actually you want `strong` which is a synonym for `retain`.  As you have it, your view can be released while you still have a reference to it - that's what `unsafe_unretained` does (and the reason why unsafe is in there, because it isn't safe.


O que pode tornar uma expressão regular lenta?

Question: Já aconteceu aqui no Stackoverlow de eu ser recomendado por alguns usuários quanto a evitar o uso de regex, em alguns casos, pois a mesma pode ter uma performance indesejável.
Já ouvi também por aí que, depedendo da forma que uma expressão regular é construída (sendo que, para capturar alguma coisa desejada, pode haver muitas maneiras de fazê-lo com a expressão regular), ela pode ser mais lenta.
Considerando esses fatores:

O que faz com que a expressão regular seja mais lenta que outras formas de se trabalhar com strings?
Dependendo do que eu deseje fazer com expressão regulares, pode haver alguma forma de se fazer (com expressão regulares) com que ela se torne mais performática, apenas mudando sua construção?

Por exemplo, uma das expressões abaixo podem ser consideradas "mais rápidas" que as outras?
 // Apenas números. Qual é mais rápido?

'teste 123456 teste 123'.replace(/[^0-9]+/g, '')

'teste 123456 teste 123'.replace(/\D+/g, '')

'teste 123456 teste 123'.replace(/[^\d]+/g, '')

Comment: Relacionado http://pt.stackoverflow.com/questions/81426/regex-tempo-de-processo-de-replace-muito-alto
Comment: @WallaceMaxters, talvez esse conteúdo possa ser útil http://pt.stackoverflow.com/questions/5136/performance-de-substitui%C3%A7%C3%A3o-em-string/5239#5239, aqui ele compara o RegExp com outras formas.
Comment: Para teste de suas expressões você pode usar http://jsperf.com/
Comment: Eu usei muito as referências deste site. http://www.regular-expressions.info e para a pergunta acredito que aqui dá pra dar uma boa idéia do quanto Regex pode pesar para avaliar uma simples *string* http://www.regular-expressions.info/catastrophic.html
Comment: Relacionado: http://pt.stackoverflow.com/q/138705/101
Answer: Resumidamente

O quão especifica ela é.
O numero de quantificadores que esta usando.

O que é uma REGEX
Você deve lembrar que, indiferente da linguagem/biblioteca, regex são Autômato finito determinístico, que serão compilados e transformadas em uma maquina de estados.

Assim você deve ter em mente que ela analisa letra por letra (simbolo por simbolo), até verificar se a sentença é valida ou não.
Exemplo
Digamos que se tenha a seguinte regex a(b|c). É gerada uma maquina de estados bem simples.

O 1º estado diz de a letra/simbolo deve ser a, obrigatoriamente.
Caso passe pelo 1º estado o 2º estado pode ser b ou c.

Se qualquer um dos estados não for comprido ou nenhum dos próximos estados seja encontrado. A sentença é invalida.

ab, ac = Valido
ba = Invalido, já não compre o 1º estado que deve ser a.
aX = Invalido, X não esta nas possibilidade do 2º estado.

Quantificadores
A analogia dos quantificadores é bem simples.

Você gera um estado que aponta para ele mesmo, ou gera um "curto" para não passar por aquele estado (*, {0,).
No que eles interferem?
Aqui tem um pequeno resumo e um boa analogia (Em minha opinião).
Um quantificador vai disser quantas vezes aquele estado pode ser valido. Um estado mal planejado com quantificador infinito pode ser catastrófico. .*/.+, Exemplo disso aqui. (Aprendi na pratica)
O que ocorre é que ele simplesmente vai continuar seguindo o máximo que pode ate chegar no final da sentença. Quando ele chega no final, faz o caminho inverso, removendo caracteres e verificando se o próximo estado (2º) é satisfeito, no primeiro caractere que satisfaça o próximo estado (2º) ele continua (para o 3º).
Na maioria das vezes não se nota esses problemas pois trabalhamos com strings pequenas que o computador simplesmente vai e volta tão rápido que é quase imperceptível.
Exemplo
https://regex101.com/r/vrUk3U/1
Por isso ele parou na ultima virgula não na primeira.
Especificar
Lembre-se de especificar ao máximo o que você quer.
Um bom exemplo de especificação é o inicio ^.
Você também deve ter um mente que se você não especifica de onde ela deve começar, então ela simplesmente vai começar de qualquer lugar. Exemplo aqui.
Então para impedir que ela faça testes desnecessários o simples ato de ser especifico já a torna mais rápida.
Nota

Algumas REGEX são mais fáceis de se montar utilizando logica inversa. Em vez de pensar no que você precisa, pense no que não precisa.

Sobre os exemplos
'teste 123456 teste 123'.replace(/[^0-9]+/g, '')

'teste 123456 teste 123'.replace(/\D+/g, '')

'teste 123456 teste 123'.replace(/[^\d]+/g, '')

Em termos de REGEX você não vai ter diferença nenhuma, pois as três serão compiladas para [^0-9].
Você pode ter um diferença no tempo de compilação, na qual sua biblioteca vai demorar diferentes tempo para transcrever o que você esta dizendo.
Comment: Melhor explicação sobre regex que ja ví. Excelente.
Answer: Este link contem uma boa explicação a respeito, cujas ideias eu também explico aqui abaixo, com um exemplo que construí e rodei na minha máquina.
Entradas inválidas podem causar uma performance muito ruim com expressões regulares mal definidas. Um exemplo de expressões regulares mal definidas são as que reconhecem a entrada de mais de uma maneira possível, e, por consequência, tentam reconhecer entradas inválidas de várias formas possíveis.
De maneira geral, o tempo gasto para reconhecer uma entrada inválida pode aumentar de maneira exponencial com respeito ao número de caracteres n da  entrada
Exemplo
A expressão regular xx+y pode ser escrita também como (x+x+)+y . A primeira expressão traduz-se para um autômato finito determinístico, sem backtracking, enquanto que a segunda expressão utiliza backtracking. Quando uma entrada válida é reconhecida, não há problema, pois o autômato encerra a busca imediatamente. Quando uma entrada inválida é fornecida, no entando, o mecanismo de reconhecimento vai tentar todas as formas de reconhecimento possíveis, até ter certeza de que a entrada não pode ser reconhecida pela Regex.
Segue um exemplo de código e sua saída correspondente, na minha máquina. O exemplo é em C#, mas os conceitos são agnósticos de tecnologia:
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace TesteRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            string padraoMau = "(x+x+)+y";
            string padraoBom = "xx+y"; ;
            string[] arrayBom = new string[] { "xxy", "xxxxxxy", "xxxxxxxxxxxxxxxxxxxxy", "xxxxxxxxxxxxxxxxxxxxxxy", "xxxxxxxxxxxxxxxxxxxxxxxxxxy" };
            string[] arrayMau = new string[] { "xxx", "xxxxxxx", "xxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxx" };

        Console.WriteLine("---- Backtracking: sim; Entrada válida: sim ----");
        TestaRegex(padraoMau, arrayBom);
        Console.WriteLine("------------------------------------------------");
        Console.WriteLine("---- Backtracking: sim; Entrada válida: não ----");
        TestaRegex(padraoMau, arrayMau);
        Console.WriteLine("------------------------------------------------");

        Console.WriteLine("---- Backtracking: não; Entrada válida: sim ----");
        TestaRegex(padraoBom, arrayMau);
        Console.WriteLine("------------------------------------------------");
        Console.WriteLine("---- Backtracking: não; Entrada válida: não ----");
        TestaRegex(padraoBom, arrayMau);
        Console.WriteLine("------------------------------------------------");
        Console.ReadLine();
    }

    private static void TestaRegex(string padrao, string[] array)
    {
        Console.WriteLine("Tamanho da entrada  | Tempo gasto");
        Console.WriteLine("------------------------------------");
        Stopwatch sw = new Stopwatch();
        for (int i = 0; i < array.Length; i++)
        {
            sw.Start();
            Regex.IsMatch(array[i], padrao);
            sw.Stop();
            Console.WriteLine("                   " + string.Format("{0,2}", array[i].Length) + "|  " + sw.Elapsed.ToString("ss\\.ffffff"));
            sw.Reset();
        }
    }
}

}
Saída:
---- Backtracking: sim; Entrada válida: sim ----
Tamanho da entrada  | Tempo gasto
------------------------------------
                    3|  00.000347
                    7|  00.000021
                   21|  00.000003
                   23|  00.000002
                   27|  00.000002
------------------------------------------------
---- Backtracking: sim; Entrada válida: não ----
Tamanho da entrada  | Tempo gasto
------------------------------------
                    3|  00.000011
                    7|  00.000039
                   21|  00.594714
                   23|  02.359978
                   27|  38.033123
------------------------------------------------
---- Backtracking: não; Entrada válida: sim ----
Tamanho da entrada  | Tempo gasto
------------------------------------
                    3|  00.000043
                    7|  00.000005
                   21|  00.000014
                   23|  00.000017
                   27|  00.000024
------------------------------------------------
---- Backtracking: não; Entrada válida: não ----
Tamanho da entrada  | Tempo gasto
------------------------------------
                    3|  00.000008
                    7|  00.000007
                   21|  00.000019
                   23|  00.000020
                   27|  00.000024
------------------------------------------------

O único caso de performance sofrível foi o de entradas inválidas, numa regex com backtracking (38 segundos com backtracking versus menos de um milésimo para a versão sem backtracking, para um entrada de tamanho 27).
O problema é que o número de formas de tentar reconhecer um string inválida, na versão sem backtracking, está associado ao número de partições de um número inteiro , que é exponencial no tamanho da entrada, o que causa a performance ruim.
Solução: ao definir uma expressão regular, assegure-se de que há uma forma (ou o menor número de formas possível) apenas para reconhecer tanto entradas válidas quanto inválidas. Prefira expressões simples, como xx+y, ao invés de (x+x+)y .
No caso dos exemplos que você forneceu para comparação, eles vão possuir performance similar (boa).
Comment: Outro motivo para evitar regex é que alguns motores de reconhecimento são simplesmente ruins. A implementação de regex para Golang por exemplo não é muito performática atualmente.


How to calculate linearity to the logit when IV includes a meaningful zero (0) and is limited to 6 predefined levels

Question: I am calculating a logistic regression with the amount of letters of a word given (0-5) in a task as the IV and whether the corresponding word was recalled in a later test or not (0/1) as the DV. All words in the dataset are five-letter words.
I want to check the assumption that my continuous predictor lettersProvided has a linear association with the logit of the outcome.
This is usually investigated with the Box-Tidwell Test:
There are multiple ways to do this in R, here are two.

Calculating a regression with an added interaction term of the IV and the ln of the IV:

lessR::Logit(correctAnswer ~ ltrsProvided + ltrsProvided:log(ltrsProvided), data= myData)

In this case, a sifgnificant interaction term (p<.05) indicates non-linearity.

Using a dedicated function from the car package:

car::boxTidwell(rec_correct~ltrsProvided, data = myData)

However, both methods do not work with my data because it includes zero, for which the ln is undefined.
There are some questions on the network about the Box-Tidwell test, but none of those with answers talk about my problem specifically.
Some resources mention a transformation of the IV (only for the Box Tidwell, as the regression works fine with 0s in the data!), but what kind of transformation is that? Adding 0.0001 to each level of ltrsProvided enables calculation of the ln but seems weird as the variable cannot realistically include e.g. 1.0001. Others talk about dropping the zeros which is impossible for me because 0 is an important level in my IV.
Frequently, splining comes up to similar (but not the same) questions but I dont think its appropriate in my case (few levels) and I have no reason to suspect that there is no linear relationship.
tl;dr: In what way can I transform my continuous IV temporarily to conduct a Box Tidwell Test?
Example of a reduced version of my data:
ltrsProvided   correctAnswer
           1             1
           2             1
           3             1
           4             0
           0             1
           1             1
           5             0
           2             1
           0             1
           4             0

Code and Plot regarding @Demetri Pananos 's post and comment.
The relationship does not look linear at all...
vis_grouped_d <- grouped_d %>% mutate(prop = y/(n+y), prop_log = log(prop))
ggplot(vis_grouped_d) + geom_line(aes(ltrs_gvn, prop_log))

More information about the research design
Its basically a replication of McCurdy et al. (2021), but online. Its an experiments on the generation effect (content that you create yourself is remembered better than content you only read) and the generation constraint (the degree of the self generation might have an influence on the memory benefit from generation). In the experiment the subjects had to create and write down target words with the help of a cue and 0-5 letters of the target given to them. In a later test, their target words and some distractors were presented to them and they had to decide whether that word was created earlier (recognition correct; 0/1).
The ltrs_given levels 0-4 are basically the manipulation of the generation constraint while ltrs_gvn is the read control condition.
They used mixed effect logistic regression with random intercepts for subjects and words (Code and Data are available online). I want to use regular logistic regression because there are so few resources for mixed models.
Answer: I've never heard of a Box-Tildwell test.  There easier ways in my opinion to assess model fit.  Here is one way...
One approach you could use is a deviance goodness of fit test.  Roughly, this is an omnibus test for goodness of fit so you actually want to fail to reject the null.  Let me set up some fake data here
library(tidyverse)

set.seed(0)
N = 120
x = sample(1:5, size = N, replace = T)
eta = x - 0.8
p = plogis(eta)
y = rbinom(N, 1, p)
d = tibble(letters_provided=x, recalled=y)

There is a strong relationship between the letters provided and the probability of recall in this example. Note that the true effect really is linear.  To do the deviance goodness of fit test, first fit a logistic regression in which we group the data by the letters provided (very natural since you only provide a finite number of letters)
grouped_d = group_by(d, letters_provided) %>% summarise(n = n(), y = sum(recalled))

model = glm(cbind(y, n-y) ~ letters_provided, data = grouped_d, family = binomial())

and then analyze the residual deviance statistic
deviance_gof = function(model){
  # Deviance has asymptotic chi square distribution
  dev = model$deviance
  dof = model$df.residual
  # Manual calculation of the p value for the test
  p.value = pchisq(dev, dof, lower.tail=F)
  p.value

}

deviance_gof(model)
[1] 0.6443274

Failure to reject the test roughly means that the model is a good fit.  So, if you fail to reject this test, you can conclude that the assumption of linearity is good (or maybe more carefully, that you can not conclude that linearity is not a good assumption from the data.  It may be there are non-linear effects which require more data to estimate precisely).
If you crank up the sample size in this example, the deviance usually tends to the degrees of freedom which is the median for the chisquare.  Hence the p value will hover around if the model you've chosen is the right model.  However, more data can come back to bite since even modest non-linearity can be precisely estimated and ruin the test.  If you had lots of data an on the logit scale the data had functional form $\log(x/10) + 1.5$ then you would reject the null of the deviance goodness of fit test even though linearity is a fine assumption to make.
Its funny you mention splines and their inappropriateness.  If you have no reason to suspect a non-linear relationship, that means either the effect is 0 or it is linear.  If you're willing to assume it is linear, why would you want to test for a linear effect?  In my opinion, splines would be a good approach because in the worst case scenario you spend a few degrees of freedom to estimate a linear effect.  That isn't so big a deal as the other option; the effect is truly non-linear and you introduce a ton of bias by not modelling it as non-linear.  Additionally, you could perform a chunk test to determine if the non-linear terms reduce additional variation in the data.  THAT would be a hell of a way to address the assumption of linearity.  Here is how to do a chunk test in R with rms
model2 = lrm(recalled ~ rcs(letters_provided,3), data = d)
anova(model2)
               Wald Statistics          Response: recalled

 Factor           Chi-Square d.f. P
 letters_provided 7.82       2    0.0201
  Nonlinear       4.13       1    0.0422
 TOTAL            7.82       2    0.0201

You can see that the nonlinear test has a significant p value (although not too significant, so the result is suspect IMO and is likely due to the small sample size of 120) meaning that the non-linearities seem to result in a better fit.
TL;DR  Do a deviance goodness of fit test or do splines and do a chunk test for the non-linear terms.
Comment: The first method returns a p indicating high significance (1.608934e-17). That might be due to my N>3000, right? Do you know any citable resources?
You wrote: "If you have no reason to suspect a non-linear relationship, that means either the effect is 0 or it is linear." and " If you're willing to assume it is linear, **why would you want to test for a linear effect?**". My course resources simply say this assumption has to be checked. I'm only struggling because my IV includes a zero. From my understanding splines etc should be introduced if/once the assumption is violated...
Comment: Also, is the assumption of the linearity to the logit really a model fit indicator?
Comment: @polarlicht Correct, your large sample size is likely the culprit of the rejection.  Again, that isn't necessarily a bad thing.  Because you have such a large sample, group the observations by the number of letters held out.  Compute the proportion of correct recalls and plot the logit of the proportion.  Does the line look straight?
Comment: I added the code and the corresponding plot to my original post. It does not look look linear at all... (And not even fully monotone but that is probably negligible?)
Comment: @polarlicht How many in that last group
Comment: The n for all 6 groups ranges from 519 to 535. ltrs_gvn = 5 has 527.
Comment: Hmm, there seems to be a strong effect of leaving 5 letters out.  Is this not all the letters?
Comment: Its the other way round: All words used are five letter words, therefore the 5 means *no* letters were left out.
Comment: @polarlicht So if no letters are left out, shouldn't everyone recall the word?
Comment: I added some information about the research design to the post. Maybe that will clear things up!
Comment: @polarlicht email me.  I think this conversation needs to be taken offline so that I can properly grasp what is going on.  You can find contact info in my profile.


Calculting the infimum

Question: Consider the maps $u, \phi:\mathbb{R}^n \to \mathbb{R^n}$. Let $\mathcal{F}$ be some class of functions and consider the quantity
$$\inf_{u \in \mathcal{F}} \left( \frac{|u|^2}{2}+u\cdot\phi\right) .$$
Assuming that $-\phi \in \mathcal{F}$, I guess the infimum will be attained at $u=-\phi$ as this is a parabola. Is this observation correct and can something be said if we consider
$$\inf_{u \in \mathcal{F}} \left( \frac{|u|^{2n}}{2n}+u\cdot\phi\right) $$ instead?
Answer: I'll answer your first question in the positive, by proving that $-\phi$ is indeed the minimizer under the assumption that $-\phi\in\mathcal{F}$.
Consider the functional $\mathscr{J}:\mathcal{F}\to\mathbb{R}$ given by
$$\mathscr{J}[u]=\frac{\lVert u\rVert^2}{2}+\langle u,\phi\rangle.$$
We know that
$$\mathscr{J}[-\phi]=\frac{\lVert\phi\rVert^2}{2}-\lVert\phi\rVert^2=-\frac{\lVert\phi\rVert^2}{2}.$$
Consider now some $h:\mathbb{R}^n\to\mathbb{R}^n$ such that $-\phi+h\in\mathcal{F}$. Then
$$\mathscr{J}[-\phi+h]-\mathscr{J}[-\phi]=\frac{\lVert -\phi+h\rVert^2}{2}+\langle -\phi+h,\phi\rangle+\frac{\lVert\phi\rVert^2}{2}=\frac{\lVert\phi\rVert^2+\lVert h\rVert^2-2\langle\phi,h\rangle}{2}+\langle h,\phi\rangle-\frac{\lVert\phi\rVert^2}{2}=\frac{\lVert h\rVert^2}{2}\geq0.$$
From this it follows that
$$\mathscr{J}[-\phi]=\min_{u\in\mathcal{F}}\mathscr{J}[u].$$
Comment: Thank you, do you think if  this result can be generalised to $\inf_{u\in\mathcal{F}}(L(u)+u\cdot \phi)$ for some nonlinear $L$ with some properties?
Comment: @Alex I wouldn't count on it, since a big reason behind it working here is the relationship between the inner product and the norm induced by it. So of it did generalize lile that, I imagine the conditions on $L$ would have to be quite demanding

Calculting the infimum


Uploading files into SVN repositories in the VisualSVN Server web interface

Question: Why isn't it possible? It would be a great feature.
https://demo-server.visualsvn.com/!/#
Comment: File upload in the web interface of VisualSVN Server is available beginning with version 5.1. Please see my answer below.
Answer: Update September 2022
Beginning with version 5.1, VisualSVN Server supports uploading files in the web interface. See the article KB206: Uploading files in VisualSVN Server Web Interface for more information.

Outdated answer
You could use your Subversion client such as TortoiseSVN or svn.exe to upload and modify data stored on VisualSVN Server. Current versions of VisualSVN Server do not support write operations in the repository web interface.
Comment: Uploading file via web interface would be fantastic.


FormIt - redirect hook issue

Question: ISSUE:  I'm using FormIt and the redirect hook is not working for me.
It is redirecting to http://www.example.comPageName.html instead of http://www.example.com/PageName.html. It is not placing the forward slash after the page name.
Has anyone seen this issue before?
Here is my FormIt snippet.
[[!FormIt? &hooks=`email,redirect` &emailTpl=`MyEmailChunk` &firstname.lastname@example.com` &emailSubject=`Contact Us form submission` &redirectTo=`35` &email@example.com`]]

Yes, the MyEmailChunk exists.
The email addresses are dummy values
The resource with id 35 is in the same context and is published and is hidden from the menus.
I'm using friendly urls.
If I try another resource it works.
Answer: URL generated in the following code
$url = $this->modx->makeUrl($this->formit->config['redirectTo'],$contextKey,$redirectParams,'full');

'full' means URL is absolute, prepended with site_url from config ( http://rtfm.modx.com/display/revolution20/modX.makeUrl ). Please check your site_url variable in /core/config/config.inc.php
Comment: What am I suppose to be looking for in particular?  I can see the code that sets the site_url;   $site_url= $url_scheme . $http_host . MODX_BASE_URL;.

$http_host is defined correctly but it doesn't have a forward slash at the end of it.   Should it?
Comment: What is the value of `MODX_BASE_URL` ? Looks like a problem with it.
Comment: The value of MODX_BASE_URL is $modx_base_url= '/';.   Is that correct?
Comment: http://forums.modx.com/thread/47544/formit-not-redirecting-properly-rc2?page=2#dis-post-460237 - here is solution
Comment: Thanks for your response and input.   Unfortunately nothing helped me.  I will try to roll my own form response handling code :(.
Answer: Actually the site_url variable needs to be checked in the System Settings.
Make sure you have a trailing slash.

FormIt - redirect hook issue


Regarding flag actions and rules integration

Question: I am using flags by the Flag module. I added two action on that flag through Flag actions:

The first one is to send an email to the site admin whenever the node is flagged.
The second is to do a Page Redirect. This action does not works and gives me an ajax error.

In my search I found this was an issue for flag module for Drupal 6. However, it still does not work. My version of Flag is 7.x-2.0 and I am using Drupal 7.
After trying out with action, I went for the better option, i.e, using Rules. I added a reaction rule with the action: A node is flagged under "my_flag" and the event : Page redirect. And I also checked the forced redirect. Its still not working.
Would really appreciate any help or suggestions regarding this.
Answer: I realise this is a long time ago but for anyone else who arrives here: you can't redirect when doing AJAX flagging, because the redirect applies to the AJAX call not the current page.
It's theoretically possible, with D7, to return a page redirect using AJAX commands but I'm not sure off the top of my head how you would achieve that in this case, or whether you'd need some modification to the Flag module code to allow it to occur.


Integrating a list from a private api to a ListView

Question: I'm having issues with it for some reason, while running the app none of the cands (the list of objects) listed in the apis response gets displayed in the ListView.
This is the response im getting from the api:
{
"currentPage": 1,
"totalPages": 1,
"totalResults": 4, // that's the amount of events in the list
"candList": [
{
"fname": "string",
"lname": "string"
}
]
}

I guess the issue starts somewhere in that part of code:
final num = getJsonField(listViewGetCandListByManagerResponse.jsonBody, r'''$.candList''',).toList();
if (num.isEmpty) {
return Center(
child: SworkerContainerWidget(
fname: GetCandListByManagerCall.workerfname(listViewGetCandListByManagerResponse.jsonBody,).toString(),
lname: GetCandListByManagerCall.workerlname(listViewGetCandListByManagerResponse.jsonBody,).toString(),),);
}
return ListView.builder(
                              padding: EdgeInsets.zero,
                              scrollDirection: Axis.vertical,
                              itemCount: num.length,
                              itemBuilder: (context, numIndex) {
                                final numItem = num[numIndex];
                                return InkWell(
                                  onTap: () async {
                                    await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            HistoryPageWidget(),
                                      ),
                                    );
                                  },
                                  child: SworkerContainerWidget(
                                    desc: GetCandListByManagerCall
                                        .workereventDesc(
                                      listViewGetCandListByManagerResponse
                                          .jsonBody,
                                    ).toString(),
                                    fname: GetCandListByManagerCall.workerfname(
                                      listViewGetCandListByManagerResponse
                                          .jsonBody,
                                    ).toString(),
                                    lname: GetCandListByManagerCall.workerlname(
                                      listViewGetCandListByManagerResponse
                                          .jsonBody,
                                    ).toString(),
                                    dateEvent:
                                        GetCandListByManagerCall.dateEvent(
                                      listViewGetCandListByManagerResponse
                                          .jsonBody,
                                    ).toString(),
                                  ),
                                );
                              },
                            );

I might be wrong with that as well but let me know.
The response I get while running the app:

dynamic getJsonField(dynamic response, String jsonPath) {
 final field = JsonPath(JsonPath).read(response);
 return field.isNotEmpty
  ? field.length > 1
     ? field.map((f) => f.value).toList() : field.first.value : null;
}

class GetCandListByManagerCall {
  static Future<ApiCallResponse> call({int? entityId}) {
     final body = {
             "token": "", //deleted in the post specifically
             "entityId": ${entityId},
             "pageNumber": 1,
             "rowsPerPage": 10,
             "search": ""
     };

     return Apimanager.instance.makeApicall(callName:'GetCandListByManager',....);
   } //the other parts in this line arent really helpful and have private info

   static dynamic workerfname(dynamic response) => getJsonField(response, r'''$.fname''',);
   static dynamic workerlname(dynamic response) => getJsonField(response, r'''$.lname''',);
}

if there is any missing information to understand the problem more deeply tell me and i'll provide it.
Comment: could you please include getJsonField?
Comment: https://docs.flutter.dev/cookbook/networking/fetch-data
Comment: @eamirho3ein updated the post with it
Comment: where other place you are using candList ?
Comment: @eamirho3ein if you are referencing the cantList[] itself then there is no other place except that line of code. if you mean GetCandListByManager then there are a few usages
Comment: do you have any class model to pars the json you get from api? if yes please include it too.
Comment: I'm not really familiar with `JsonPath`. But my guess is that you need to leave out the `[]`. I think most flutter developers don't even use it. flutter's built-in json decoding works great. Don't really need `JsonPath`
Comment: @eamirho3ein i've updated it as you requested (tell me if thats what you intended), i've also noticed the comment of Ivo and i've tried it, which made the result a bit better but still not ideal as you can see
Comment: could you please also include the part that have api call?
Comment: Yes i've added the relevant parts of it @eamirho3ein
Answer: First create class model like this:
class CandModel {
  final String firstName;
  final String lastName;

  const CandModel({
    required this.firstName,
    required this.lastName,
  });

  static CandModel fromJson(Map<String, dynamic> json) {

    return CandModel(
      firstName: json['fname'],
      lastName: json['lname'],
    );
  }
}

then pars your api like this, instead of this:
final num = getJsonField(listViewGetCandListByManagerResponse.jsonBody, r'''$.candList''',).toList();

use this:
final data = listViewGetCandListByManagerResponse.jsonBody['candList'] as List;
   List<CandModel> cands = data.map((e) => CandModel.fromJson(e)).toList();

then use it in you list view like this:
SworkerContainerWidget(
    desc: GetCandListByManagerCall.workereventDesc(
         listViewGetCandListByManagerResponse.jsonBody).toString(),
    fname: cands[index].firstName,
    lname: cands[index].lastName,,
    dateEvent:GetCandListByManagerCall.dateEvent(
          listViewGetCandListByManagerResponse.jsonBody).toString(),
)


Expo Document picker does not give back the correct uri

Question: So I am trying to use the expo document picker (https://docs.expo.io/versions/latest/sdk/document-picker/) to let the user select an image from their phones file system and display it on the screen. It was working quite recently until I noticed that the promise it sends back stopped returning the correct uri. Before it was returning a uri starting with file:///data/ where as now it returns a uri starting with /data. This new type of uri does not display on the screen and I am wondering how I get back to the old one? I am using await DocumentPicker.getDocumentAsync to get the file in the first place.
Comment: Even prepending "file//" is not working - I am having the same issue after updating from expo SDK 38 to SDK 42
Comment: Check out [this](https://snack.expo.io/@kartikeyvaish/document-picker-example) snack. Let me know if you get the desired result by this.
Comment: Thanks, it works
Comment: nvm its not a code issue it's an import/library version thing. There were some warnings about document picker and a few other libraries and as soon as I updated them it went back to the /data URI format.
Answer: I had the exact same problem after upgrading from expo 38 to 42. I did a workaround using expo-file-system.
First I set the copyToCacheDirectory option to false
const result = await DocumentPicker.getDocumentAsync({
        type:'*/*',
        copyToCacheDirectory: false,
      });

That would save the file to the conten:// file space. Once we have the file we can copy it to our file:// location:
const uri = FileSystem.documentDirectory+result.name;

await FileSystem.copyAsync({
   from: result.uri,
   to: uri
})

Now you should be able to use uri (which includes the file:// path) without problems.
Answer: I have same problem from expo SDK 38 to SDK 42,
I find a workaround from here
const encode = uri => {
  if (Platform.OS === 'android') return encodeURI(`file://${uri}`)
  else return uri
}
...
<Button
  onPress = { async () => {
    let result = await DocumentPicker.getDocumentAsync({ type: '*/*' })
    if (result.type === "success") {
      console.log("getDocumentAsync", result);
      Alert.alert(
        "upload file",
        `Whether to upload ${result.name}`,
        [
          {
            text: "Cancel",
            onPress: () => {},
            style: "cancel"
          },
          {
            text: "OK",
            onPress: () => dispatch(action.sendFile(encode(result.uri)))
          }
        ],
        { cancelable: true }
      )
    }
  }}
/>

it work for me!
Answer: I you want the file to be accessible for using in WebView, You can do this
const result = await DocumentPicker.getDocumentAsync({
     type: "application/pdf",
     copyToCacheDirectory: false,
   });

This is will give you a uri like this
{
...,
"uri": "content://com.android.externalstorage.documents/document/home%3Ayour-file.pdf",
}

and you can access the file by passing it as uri
{{
          uri: uri,
        }}


Using findBy with same attribute but multiple values

Question: I have a Product domain:
Product {
   String name
}

Now I need issuedProductInstance and requestedProductInstance. For that I used findBy as
def find(String issuedProduct,String requestedProduct){
    Product issuedProductInstance=Product.findByName(issuedProduct)
    Product requestedProductInstance=Product.findByName(requestedProduct)
}

In this way the method hits DB two times. Is there any way by which I can find both products by executing only one query.
Answer: Don't know about grails, but you just need the following query:
select p from Product p where p.name in (:names)

Of course, this query could return 0, 1 or 2 products, and you have to iterate through the list to know which is the one with "issuedProduct" as name, and which is the other one.
Comment: Yes, this will work. We can write it as Product.findAllByNameInList([issuedProduct,requestedProduct]).          But I want to show difference error message when issuedProductInstance or requestedProductInstance is null and this query will not return the null object.
Comment: If it returns an empty list, then both of them don't exist. If it returns a list of size 1, then one of them doesn't exist. If it returns a list of size 2, then both exist (assuming the name is unique, of course).


Derivative of function and simplification

Question: I'm attempting to find the derivative of the following function:
$$\frac{e^x - e^{-x}}{e^x + e^{-x}}$$
where I would use the quotient rule to find its derivative. In the end, I would obtain:
$$\frac{(e^x + e^{-x})^2 -(e^x - e^{-x})^2}{(e^x + e^{-x})^2}$$
However, I checked with the calculator online and I found out that the equation I current have above can be further simplified to:
$$\text{ Rewrite / Simplify }$$
$$=1-\frac{(e^x - e^{-x})^2}{(e^x + e^{-x})^2}$$
$$\text{ Simplify }$$
$$\frac{4e^{2x}}{(e^{2x} +1)^2}$$
I'm having issues understanding the simplification step above.
My biggest question is, in the second image above, why couldn't I have $(e^x + e^{-x})^2$ cancel out $(e^x + e^{-x})^2$ at the denominator, which would leave me with just $-(e^x - e^{-x})^2$? Could anyone explain the simplification step to me as I am very much confused.

P.S. pardon me but I couldn't understand the syntax on writing equations here so I would opt to use screenshot instead.
Comment: "Derivative of a function", not "derivative of an equation".
Answer: I think your issue is that the computation in the last "cartridge" should be decomposed into $2$ steps :
First step :
The first expression can be written, taking a common denominator :
$$\dfrac{(e^x+e^{-x})^2}{(e^x+e^{-x})^2}+\dfrac{(e^x-e^{-x})^2}{(e^x+e^{-x})^2}=\dfrac{(e^x+e^{-x})^2+(e^x-e^{-x})^2}{(e^x+e^{-x})^2}=\dfrac{4}{(e^x+e^{-x})^2}$$
Second step : Factor $e^{-x}$ in the denominator :
$$(e^x+e^{-x})^2=(e^{-x}(e^{2x}-1))^2=e^{-2x}(e^{2x}-1)^2$$
We have obtained a $(e^{2x}-1)^2$ as a factor in the denominator.
Getting rid of $e^{-2x}$ in the denominator by transforming it into $e^{2x}$ in the numerator, explains the final result with $4e^{2x}$ in the numerator.
Comment: thank you, it was a very nice explanation. I understand it now.
Answer: Hint: Use that $$a^2-b^2=(a-b)(a+b)$$
Answer: So it's not even about derivative, as your question is that why:
$$\frac{a - b}{a} \ne -b, a>0$$
Well, they are just not equal, because in general $a-b+ab \ne 0$


Linux and cocos2d: 'cc1plus': execvp: No such file or directory

Question: I am trying to build a cocos2d sample app for android on linux and i get the following error:
<code>stefanos@stefanos-MS-7250:~/cocos2d-1.0.1-x-0.11.0/Test1/android$ ./build_native.sh

    make: Entering directory `/home/stefanos/cocos2d-1.0.1-x-0.11.0/Test1/android'
    Gdbserver      : [arm-linux-androideabi-4.4.3] libs/armeabi/gdbserver
    Gdbsetup       : libs/armeabi/gdb.setup
    Compile++ thumb  : cocos2d <= CCConfiguration.cpp

arm-linux-androideabi-g++: error trying to exec 'cc1plus': execvp: No such file or directory

make: *** [obj/local/armeabi/objs-debug/cocos2d/CCConfiguration.o] Error 1
make: Leaving directory `/home/stefanos/cocos2d-1.0.1-x-0.11.0/Test1/android'
stefanos@stefanos-MS-7250:~/cocos2d-1.0.1-x-0.11.0/Test1/android$
</code>
I am running Ubuntu and i have gcc , g++ installed
SOLVED:
It build's fine with the r6 version of the ndk
Download it here :http://dl.google.com/android/ndk/android-ndk-r6-linux-x86.tar.bz2
Answer: Try to update cocos2d-x version 2.0, it has been release today, and use NDK 8. You must be out of date.
Using last version is better, 1.0 has a lot of bugs in Android. One of them with memory manager, it is very bad to release a game in Store.


Windows Forms UserControl overrides not being called

Question: I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in this link.
public ref class CTiledImgViewControl : public UserControl
{
...

virtual void OnPaint( PaintEventArgs^ e ) override;

...
};

And in my CPP file:
void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
    UserControl::OnPaint(e);
    // do something interesting...
}

Everything compiles and runs, however the OnPaint method is never getting called.
Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...
Comment: I have updated my answer after discovering a similar problem in my own work. I hope it helps.
Answer: The OnPaint won't normally get called in a UserControl unless you set the appropriate style when it is constructed using the SetStyle method. You need to set the UserPaint style to true for the OnPaint to get called.
SetStyle(ControlStyles::UserPaint, true);

Update
I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to OnPaint.
After digging around with Reflector, I discovered that OnPaint is only called if the clipping rectangle of the corresponding WM_PAINT message is not empty. My UserControl instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no OnPaint call.
I worked around this by overriding WndProc and adding a handler for WM_PAINT directly as I couldn't find another way to achieve what I wanted.
Answer: I solved the issue, in case anyone is interested. It was because my WinForms control was embedded in a ViewBox. I changed it to a grid and immediately started getting paint events. I guess when asking questions about WPF, you should always include the XAML in the question!


Fazer post com api aws

Question: Estou tentando fazer um Post para um serviço da AWS.
Nunca trabalhei com AWS e estou estudando alguns links e inincialmente estou a fazer um teste de conexão usando esse código:
private static async void SignInUserAsync()
{
    var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.GetBySystemName("us-east-1"));
    try
    {
        string Access_Key = "ZZZZZZZZZZZZOOOOOOO";
        string Secret_Key = "XXXXXXXXXXYYYYYYYYYYYYY";

        var authReq = new AdminInitiateAuthRequest
        {
            AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
            UserPoolId = Access_Key,
            ClientId = Secret_Key
        };

        AdminInitiateAuthResponse authResp = await provider.AdminInitiateAuthAsync(authReq);

        if (authResp != null)
        {
            Console.WriteLine("Autenticação ok!");
        }
        else
        {
            Console.WriteLine("falhou!");
        }

    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

Instalei o SDK:
AWS SDK para .NET
As seguintes extensões no VS2017:
AWS Toolkit for Visual Studio 2017
A dúvida é que não consigo fazer a autenticação com o AWS  pois retorna o erro 400, a chave e o código de acesso foi enviado pelo cliente:
Comment: alguns pontos me chamaram atenção: Você está tentando fazer uma autenticação de Administrador utilizando credenciais anônimas? Você já tentou com criar chaves e utlizar? outro material para sua referência: https://aws.amazon.com/pt/blogs/mobile/use-csharp-to-register-and-authenticate-with-amazon-cognito-user-pools/
Comment: Adrianojc você poderia esclarecer se é apenas o AmazonCognito que gostaria de interagir? Sendo assim quando comenta que quer "Fazer um post em um serviço" seria um requisição no AmazonCognito?
Answer: Cara poderia tentar utilizar esse metodo para autenticar ?
https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/M_Amazon_S3_AmazonS3Client__ctor_9.htm
AmazonS3Config config = new AmazonS3Config();

    _s3Client = new AmazonS3Client(
        "00000000000000000000", //ID_Access
        "0000000000000000000000000000000000000000", //Key_Access
        config
    );

Aqui se encontra toda documentação da AWS que está me ajudando muito até então
https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_S3_AmazonS3Client.htm
Comment: parece que o adrianojc quer autenticar no Amazon Cognito e não em um S3 diretamente, mas entendo que o Cognito pode ser um método de autenticação para o S3. Imagino que sua resposta não endereça a pergunta feita.

Fazer post com api aws


JavaFx. What property of Scrollpane defines how far it is scrollable independantly of screen size

Question: If I create a scroll pane, let's say i want to be able to scroll futher that the size of the screen, (till the eternity whatever) how would i define how far i can go.
I have a program with a scrollPane and when i just call the program i actually cannot scroll anywhere, only if i resize the window (make it smaller) i can scroll.
the question is: What property should i change to define how far the scrollPane can go.
Pane pane = new Pane();
final ScrollPane scrollable = new ScrollPane();

Scene scene = new Scene(scrollable, windowWidth, windowHeight);

Comment: Isn't this determined by the relative sizes of the scroll pane's content and the scroll pane's viewport? So you would just put something in the scroll pane that is bigger than the scroll pane itself?
Comment: Yes if you add a container and set it to the size you want to be able to scroll to whatever the size of the container is
Answer: Here is an example of what @James_D said its as big as the content inside
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage){
        VBox vbox = new VBox();
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setPrefSize(300,300);
        Label promptLabel = new Label("Keep Scrolling!!");
        vbox.getChildren().add(promptLabel);
        vbox.setMinHeight(3000);
        scrollPane.setContent(vbox);
        Scene scene = new Scene(scrollPane);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}


ODI | Decrypt a file Using DES

Question: I have a file encrypted using DES algorithm. I want to decrypt the file in ODI (Oracle data integrator) by writing procedure in Jython. I have explored the built-in functions, but I am unable to find one for decryption.
How can I do this?
Answer: You can use Python based libraries.
pyDes: http://twhiteman.netfirms.com/des.html
pycrypto: https://www.dlitz.net/software/pycrypto/
using DES/3DES with python

ODI | Decrypt a file Using DES


Suppose $F,G$ are a partitions on $A$,$B$ and $A \cap B=\emptyset$. Prove that $F\cup G$ is a partition of $A \cup B$

Question:
Suppose $F,G$ are a partitions on  $A$,$B$ and $A \cap B=\emptyset$
  Prove that $F\cup G$ is a partition of $A \cup B$.

My attempt:
To prove that $F \cup G$ is a partition on $A \cup B$, we need to show that:

$\bigcup \bigl(F \cup G \bigr) = A \cup B$
$\bigcup \bigl(F \cup G \bigr)$ is pairwise disjoint
$\forall X \in \bigcup \bigl(F \cup G \bigr) ( X ≠ \emptyset)$

1.
$(\rightarrow)$
Take $x \in \bigcup F \cup G$. Then exists some $X \in F$ or $X \in G$, such that $x \in X$.
If $X \in F$, then $x \in A$.
If $X \in G$, then $x \in B$.
It follows that $x \in A \cup B$, which means that $\bigcup F \cup G \subseteq A \cup B$.
$(\leftarrow)$
Take $x \in A \cup B$.
It follows that $x \in A$ or $x \in B$
If $x \in A$ then exists some $X \in F$ such that $x \in X$. And that means that $x \in \bigcup F$.
If $x \in B$ then exists some $X \in G$ such that $x \in X$. And that means that $x \in \bigcup G$.
Hence $x \in \bigcup F \cup G$
Since arbitrary element was considered, we have $A \cup B \subseteq \bigcup F \cup G $
Both directions were shown, thus we have our result $\bigcup F \cup G = A \cup B$
2.
Take arbitrary $X,Y \in F \cup G$
If $X,Y \in F $ then $X \cap Y = \emptyset$, because $F$ is a partition on $A$
If $X,Y \in G $ then $X \cap Y = \emptyset$, because $G$ is a partition on $B$
Suppose $X \in F$ and $Y \in G$
Take arbitrary $x \in X$. We know that $x \in A$, and $A \cap B = \emptyset$, hence $x \notin B$ and $x \notin Y$. Hence not a single element of the set $X$ is in $Y$, which means that $X \cap Y = \emptyset$
By the same reasoning, we can show that if $Y \in F$ and $X \in G$, we still have $X \cap Y = \emptyset$.
Since $X,Y$ were arbitrary, we conclude that $F \cup G$ is pairwise disjoint.
3.
Since $F$ is a partition on $A$, $\emptyset \notin F$
Since $G$ is a partition on $B$, $\emptyset \notin G$
Hence $\emptyset \notin F \cup G$.
We've shown that three properites hold, hence $F \cup G$ is a partition on $A \cup B$. $\Box$
Is it correct?
Answer: It's correct. Maybe it's just me but once you're comfortable with proofs, you don't need to tediously write every step. That is, your proof could be written as:

Every set in $F\cup G$ is nonempty: obvious.
$F\cup G$ is disjoint: there's only the case where $X\in F$ and $Y\in G$ (the other cases are obvious). If $X$ and $Y$ are not disjoint, then there is some $x\in X\cap Y$. Then $x\in A\cap B$, contradicting that $A$ and $B$ are disjoint.
We have that $\bigcup(F\cup G)=\bigcup F\cup\bigcup G=A\cup B$.


When can I use a custom field type instead of a custom entity?

Question: I come from an SQL background and I'm still navigating fields/entities. I have a custom entity (analysis) to record information about a laboratory sample (what it is, when and where it was taken, and what analysis method was applied to it). The analysis will return many independent results. I was thinking of making a second entity (results) with an entity reference to the analysis entity, the name of the chemical that was measured, and the concentration that was measured.
However, could I instead make a custom field_type that is combination of the chemical name and its concentration? Then I could include this chemical_result as a field in my analysis entity with
<code>->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
</code>
to include multiple chemical results in one analysis, right?
When is it appropriate to use a custom field versus an entity?
I also have an entity called "chemical" that has information on chemicals of interest. If I use an entity for my results, I know I can make an entity_reference to the chemical entity, which would allow some more complex queries down the road. Can I do the same with a custom field? If not directly, I'm assuming I could program the add_analysis form to only allow certain values for chemical name  when adding data to the result field, correct?
Comment: I'm not sure that storing the analysis data as a custom field type is going to be scalable. If you have many analysis items, then the results entity will load all of the analysis item data, which could have a performance impact depending on the size of the data. Entity reference will do the same except that the field data will be relatively small in comparison. Using views, it might not matter, because the entity references might load the entities anyway to view the data.
Answer: Custom entities and custom fields are not mutually exclusive, you can use them together.
You can build a custom field type with more than one property. See for example the Password field which defines three properties:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21PasswordItem.php/function/PasswordItem%3A%3ApropertyDefinitions/8.2.x
You can also extend the entity references field. See for example the File field:
https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Plugin%21Field%21FieldType%21FileItem.php/function/FileItem%3A%3ApropertyDefinitions/8.2.x
The File field adds two properties to the reference field. In your case you would add the properties chemical name and concentration to a reference field which points at the analysis entity.
Comment: You're suggesting something a little different that I was thinking. My thought was to make the analysis entity contain the sample information, and contain instances of results (chemical + quantity). It reads like your suggestion is to have two entities (analysis and results), where results uses a new field which combines a reference to the analysis, and the chemical. My idea would leave me with 1 entity and 1 custom field (or 2 entities and no custom fields), this is 2 entities and 1 custom field. What is the advantage of this over the original plans?
Comment: Extending entity_reference is a great idea either way.
Comment: I did not mean to suggest a data structure. I described how you can replace the second entity you mentioned in the question at the end of the first paragraph with a custom field.
Comment: Ahh, good. I'm used to thinking in terms of primary and foreign keys, so I was thinking you were suggesting that an alternate structure may have advantage despite reversed "directionality" of what I'm used to.


Redundant If statement warning

Question: if ( a > b) {
  return true;
}
return false;

With the above code Netbeans gives "Redundant if statement" warning and suggest changing it to :
return a > b;

I think the first version is easier to read and prefer using it in my code. I want to know if there is any disadvantages of it compared to the suggested one.
Comment: I would find such a warning annoying.  In the above simplistic case maybe the second form would be better, but any more complex at all and the first could be argued to be more readable.
Comment: I think is readability, I prefer the netbeans suggested code. You might want to compare the .class generated by both versions. I think they would be optimized to the same set of instructions.
Comment: I prefer the latter version, but you should be able to set your preference. If Netbeans doesn't have an option for this you should make a feature request.
Answer: This
if ( a > b) {
  return true;
}
return false;

consists in pushing the value of a on the stack, pushing the value of b on the stack, popping both and checking the result of >. If it's true, push the value of true on the stack, then pop it and return it. If it's false, branch to further down in the bytecode, push the value of false on the stack, pop it and return.
In the case of
return a > b;

you're pushing the value of a and b on the stack, then popping the values and pushing the result of > on those values onto the stack. Then popping that value and returning it.
So
return a > b;

is unnoticeably more efficient at the byte code level.
(IMO I find the second more readable and I believe most will, too.)
Comment: The efficiency here is irrelevant or, quite possibly, nonexistent once the JIT compiler gets finished with it. "We should forget about small efficiencies, say about 97% of the time" -- Donald Knuth
Comment: @ErikI Would you like me to remove the information about how the byte code is generated by the compiler or would you like me to emphasize the _unnoticeably_? I've gone ahead and done that latter in anticipation.
Comment: Agree w/ @DavidConrad: Don't worry about javac or the JIT compilers job, and more important: don't teach new programmers to do that. If you code is to slow, take a high level overview first, then measure, then optimize.
Comment: Hi and thanks for caring! My point was that I'm fairly certain that Java will optimize this away completely. Modern compilers are amazing. That said, I'll remove my downvote and leave you with figuring it out for now :-)
Answer: Your code does include some additional computations from compiler point of view. Need to allocate memory for booleans(that u r returning) and do a >b computation. A>b returns Boolean so if u return that it is easy.
They both have same from logic though.
Comment: See David Conrads comment.

Redundant If statement warning


Show that clu($B$) = empty set in a metric space $M$

Question:
Let $A$ be contained in $M$ such that $A$ is non-empty but clu($A$) is the empty set. Assume $A$ does not equal $M$. Let $y$ be an element of $M-A$ and let $B=A \cup \{y\}$. Show that clu($B$) is the empty set.

clu is the cluster point
If I am thinking about this right, $M-A$ is everything in $M$ that isn't in $A$ right?
Then the union of $y$ and $B$ just ends up being $M$ doesn't it?
Comment: clu(A) means what? I don't recognize the usage.
Comment: Can you define ${\rm clu}(A)$, please? I don't recall ever seeing this notation. And since you say that $A \neq \varnothing$, I assume that ${\rm clu}$ does not mean "closure", otherwise we'd have $A \subseteq {\rm cl}(A) = \varnothing \implies A = \varnothing$.
Comment: its what it says on the problem. I was hoping someone would recognize what it means....i've looked through my notes and can't find anything that uses it
Comment: By $\mathrm{clu}(A)$ you mean the set of all cluster points of $A$?
Comment: I think that might be it. I'm still trying to find it in my notes
Comment: clu is the cluster point yes
Answer: You have $A$ a subset of $M$ which has no cluster points. Then the problem assumes that $A$ is not $M$ so that is why a point $y$ in $M-A$, or more simply a point which is in $M$ but not in $A,$ may be chosen. The problem is then defining $B$ by taking $A$ and throwing in the extra point $y.$ In this case $B$ doesn't need to end up being all of $M$ (although it might be, if it happened that at the start $A$ contained all points of $M$ excepting for $y$).
Now note that a cluster point $z$ of a subset $C$ of $M$ must have a sequence of pairwise distinct elements of $C-\{z\}$ which converges to $z.$ Applying this to $C=B=A \cup {y},$ any such sequence of pairwise distinct terms from $B$ would eventually contain only elements of $A$ (since $y$ can only appear once). But then $A$ has a cluster point after all.
Comment: Alright I'll give it a try! Thank you!
Comment: I am confused on where z comes from in this. Could you explain it a bit more?
Comment: The use of $z$ here is just as a notation for a supposed cluster point of a general subset $C$ of the metric space $M$. [I called that $C$ so as not to confuse with either of already considered sets $A,B.$] Also note that the sequence of distinct points which approach $z$ must be points from $C$ in order that $z$ be a cluster point. Let me know if you need other details...
Comment: I'm still not entirely sure how to write this out as a proof
Comment: That's the hardest part for me is how to write it out and have it make sense
Comment: @Daniel If you can follow the outline in this answer, I think all you need to do is to fill in the descriptions, in your own words, of how it all fits together. Sometimes looking at proofs already done in the text you're using (or another text) can give a good idea of how to write up a proof of something.


and  tags in a text field of format Full HTML are not rendered in a field based view

Question: In latest Drupal 8, I've got a text field of format Full HTML that contains <form> and <input> tags (It's a MailChimp subscribe snippet). As long as I am editing the text in CKEditor in the backend, the form is displayed correctly. But as soon as I view tha page in the frontend, both tags are stipped out. I checked my text format/CKEditor settings to see if tags are stripped out there, but "Limit Allowed HTML Tags" is unchecked.
Does someone know what's happening here?
Edit: after checking out more, I realized that the text field is rendered inside a view (field based). When rendered as a node, the markup is perfectly rendered, just when rendered as a view, then the tags are stripped. I edited the question title to refelct this information.
Any suggestions how to render the tags inside a view?
Edit 2: the text field is rewritten in views (added some wrapper tags).
Comment: you can use webform create form include to content
Comment: What i suggest is : in views Format, do not use 'Fields' but instead use 'Content' with a custom view mode that renders the fields you want to dispaly.
Comment: did you click 'Source' in CKEditor before pasting the full html code ?
Comment: @izus sure, I pasted code while in source code mode.
Comment: Most often, you are unable to do this because it is not safe markup. I would suggest using webform as @vinhdv also mentioned.
Answer: I confirmed on 8.7 that the following basic snippet is able to be used in Full HTML out of the box:
<form><input checked="checked" name="gender" type="radio" value="male" /> Male

<input name="gender" type="radio" value="female" /> Female

<input name="gender" type="radio" value="other" /> Other</form>

It's possible your particular snippet is being hit by the "Correct faulty and chopped off HTML" Format setting, so try it without that and see if it lets the code stay. Of course, this is not an ideal setting for a commonly used text format filter, so this snippet may be better off in a custom plugin block, or creating a new text format w/ the "Correct faulty and chopped off HTML" turned off, that can be used sparingly as needed.
UPDATE based on Views usage:
If you're using rewrite, it won't be possible out of the box to have it not strip tags, it's something baked into Views. You can override it at the theme layer - if for example you are using the body field, you create a views-view-field--body.html.twig file in your theme, and then put the desired wrapper tags around the {{ output -}}, e.g.:

{{ output -}}

And turn off rewrite in Views UI.
Comment: after testing your snippet, I realized that the tags aren't stripped when the node is displayed with default view mode, but when the field is rendered inside a field based view, then tags are stripped out. I edited my question regarding this new information.
Comment: Updated my answer based on your edits - please let me know if this helps to solve your issue.
Comment: Thank you, I see the problem now. Didn't know that rewriting was the reason for stripping.