JOB LINQ para atualizar valores no Banco de dados!

Question: Eu tenho um JOB no qual preciso atualizar todos os valores para o valor máximo que existe pra uma coluna, mas meu código não está funcionando.
Alguém pode me ajudar?
Meu código:
<code>List<SqlOnlyCostModel> costat = new List<SqlOnlyCostModel>();
foreach (var QuantityItem in all)
{
    int maxQtd = all.Max(x => x.QuantityItem);
    decimal maxPrice = all.Max(x => x.UnitPrice);
    string nCurrency = all.Max(x => x.Currency);
    string nCost = all.Max(x => x.Currency);
}

_dbEngContext.SaveChanges();
</code>
Comment: Lucas, traduza sua pergunta para português!
Answer: Considerando que você esteja utilizando um Model para esses valores atribuídos, seria algo como:
<code>//Your code
Context.Entry(ModelName).State = EntityState.Modified;
Context.SaveChanges();
</code>


Mixture model on binary + continuous data

Question: If I have a dataset of continuous variables (that I can assume are normally distributed), I can identify subgroups using a Gaussian mixture model and implement.
Likewise if I have binary data I can model it as a mixture of Bernoulli.
I can implement either of these models using likelihood EM approach, or MCMC (typically Gibbs) sampling.
However, if my dataset comprises both continuous and binary data, can a mixture model be defined? If so, how?
Comment: Yes, it can. I shall expand into an answer later. However, why would you not be able to define a mixture model? Consider the likelihood function for one person in either type of model: it's the product of all the probabilities that their indicators were equal to whatever was observed. Why can't this adapt to mixed types of indicators? Also see this answer: https://stats.stackexchange.com/questions/339936/mixing-variable-types-in-latent-class-profile-analysis
Comment: I'm unfamiliar with Bayesian implementations. I have fit a model in Stata with mixed types of indicators. I am almost sure that MPlus can do this also. I believe that the R package `flexmix` does; its function `FLXMVcombi` says that "This model driver can be used to cluster mixed-mode binary and Gaussian data. It checks which columns of a matrix contain only zero and ones, and does the same as `FLXMCmvbinary` for them. For the remaining columns of the data matrix independent Gaussian distributions are used ..."
Comment: Ah great, I didn't realise it was quite as straight forward as simply incorporating the different data type into the likelihood product. I'll check out that `flexmix` implementation, thanks!
Comment: I hadn't seen it done before or implemented in any general probabilistic programming frameworks. Do you know if any existing software can infer such models or do custom Gibbs samplers need to be written?
Answer: Yes, you can simply combine the two components of you make a simple independence assumption.
Then P(continuous, binary) = P(continuous) P(binary) and you already have the solution of the right hand side.
For binary variables I don't think you want to use a dependent model here, but it is equally easy to do for at least one or two variables.


Square root of determinant equals determinant of square root?

Question: Is it true that for a real-valued positive definite matrix $X$, $\sqrt{\det(X)} = \det(X^{1/2})$?
I know that this is indeed true for the $2 \times 2$ case but I haven't been able to find the answer or prove it myself for larger $X$.
Thanks a lot for any help.
Comment: How are you defining $X^{1/2}$? In general, $\det(AB)=\det(A)\det(B)$. So if $X^{1/2}\cdot X^{1/2}=X$ then $(\det(X^{1/2}))^2=\det(X)$.
Comment: Well that was easy. Thank you very much.
Answer: Call $Y = x^{\frac{1}{2}}$. Then $\det X = \det (Y^2) = (\det Y)^2$, so $\sqrt{\det X} = |\det Y|$. If $Y$ is positive definite, then $|\det Y| = \det Y$, and so we are done.
Comment: I appreciate all of the answers but this one was first. Thanks everyone for the help.
Answer: I assume you mean by $X^{1/2}$ a matrix $Y$ such that $Y^2=X$, in which case
$$\begin{align}
\det Y^2=\det X & \implies (\det Y)^2=X\\
& \implies \det Y=\pm\sqrt{\det X)}
\end{align}$$
Answer: If you know that $\det(AB)=\det(A)\det(B)$, then this is immediate, taking $A=B=X^{1/2}$. If you don't know that, there are several proofs suggested here.


dimension of column space and null space

Question: I am trying to answer a series of questions given the dimension of a matrix.
Suppose that $A$ is a $6 \times 12$ matrix.
The column space is a subspace of $\mathbb{R}^n$. What is n?
$n = 6$ because there can only be 6 pivot columns.
The null space is a subspace of $\mathbb{R}^m$. What is m?
$m = 12$? Not so sure about this question.
Is it possible to have rank = 4, dimension of null space = 8?
$rank \leq min(m,n)$ for $m \times n$ matrix,
rank + nullity = number of columns.
It is possible.
Is it possible to have rank = 8, dimension of null space = 4?
rank + nullity = number of columns
but $rank \nleq min(m,n)$.
It is not possible.
Are my answers valid for the three questions that I answered?
I am a bit confused with the second question.
Any help would be great.
Thank you for reading.
Answer:
The column space is a subspace of $\mathbb{R}^n$. What is n?
$n = 6$ because there can only be 6 pivot columns.

Your answer is technically correct, but misleading.  I would say the following: the column-space is a subspace that contains the columns of $A$.  Because the columns of $A$ each have $6$ entries, an element of the column space has $6$ entries which is to say that the column space is a subspace of $\Bbb R^6$.

The null space is a subspace of $\mathbb{R}^m$. What is m?
$m = 12$? Not so sure about this question.

Your answer is correct; here's a reason.  The nullspace of $A$ is the set of column-vectors ($k \times 1$ vectors for some $k$) $x$ satisfying $Ax = 0$.  However, in order for $Ax$ to make sense, the "inner dimensions" of $m \times n, k \times 1$ need to match, which is to say that $k = n = 12$.  So indeed, the nullspace is a subspace of $\Bbb R^{12}$.

Is it possible to have rank = 4, dimension of null space = 8?
$rank \leq min(m,n)$ for $m \times n$ matrix,
rank + nullity = number of columns.
It is possible.
Is it possible to have rank = 8, dimension of null space = 4?
rank + nullity = number of columns
but $rank \nleq min(m,n)$.
It is not possible.

Both of these are correct; I have nothing to add.


Show various nodes in different ways on home page in drupal7?

Question: I want to show nodes in different ways. For example, i want to show featured nodes, recent nodes. My question is that how we can show nodes in different ways on my home page.
See this demo site, i want my home page in drupal as like it.the problem is that how to manage nodes different ways as posts in WordPress.
thanks for the help
Answer: Welcome to Drupal StackExchange !
You can build various views of same content using Views module in Drupal. You can follow this link to know more about the views module and also Views Documentation in the project page.
Comment: link is not working dude


Why do NBA teams wear spanish jerseys?

Question: Several times, I have seen several NBA teams wear jerseys that say, "Los Lakers," "El Heat," and "Los Spurs" for example.

What is the motivation behind why NBA teams wear spanish jerseys?
Answer: Noche Latina, established during the 2006-2007 season, is a program by the NBA to celebrate Latin heritage for fans and players in Hispanic and Latin American communities.
Each season, selected NBA games contains Latin-themed activities, advertisements, and merchandise among other things in honor of "Noche Latina."
Teams who play in "selected NBA games" wear Spanish jerseys as part of the "Noche Latina" program.

Why do NBA teams wear spanish jerseys?


XSS attack vectors

Question: What are some common XSS vectors for websites aside from unsanitized input from text fields finding there way back into pages? Trying to prevent malicious access to csrf tokens in cookies. I'm escaping unsafe characters from text inputs (probably will end up adding that in Java servlets as well before database inserts or printing to UI). Where else should I be looking for XSS entering the site?
Answer: If I understand the question correctly, you mitigated some forms of reflected and stored XSS, by encoding user input from input fields on the UI.
You should be aware of a few things:

Not all user inputs are through UI input fields. Cookies and request headers are also examples of user input, and of course hidden fields or json/xml/any other type of parameters too. If your application processes any files or receives outside requests besides http, those too are user input. Even fields of your database are best treated as user input and encoded upon writing them to the page, especially if other components also write to the database.
Maybe it is already the case in your application, but to make this answer more comprehensive: XSS is more of an output issue, regardless of where user input comes from, the solution is output encoding most of the times (and not input validation / sanitization by itself, especially not with blacklists). There may be careful exceptions to this though, and of course input validation does indeed nicely complement proper output encoding.
The encoding method should be selected according to the context where the data is written (ie. you need different encoding when writing into a javascript block or plain html; also note that javascript blocks are not only inside script tags, but for example inside event attributes like onclick and others).
DOM XSS is entirely on the client, and must be mitigated there, in Javascript. See the relevant OWASP guides below.

The general OWASP XSS page is very useful.
They also have a few guides:

Stored and Reflected XSS prevention cheat sheet
DOM XSS prevention cheat sheet
Testing for reflected, stored and DOM XSS.

XSS attack vectors


Form nao descarrega da memória

Question: Ola pessoal preciso de ajuda. Meu form não descarrega da memória então não consigo chamá-lo de novo.
Segue código abaixo:
If formage=nil then
Begin

Crio o form e no onclose do form
Action:=cafree:
Formage:=nil

Alguém tem uma ideia???
Comment: De que maneira você cria o *Form*? Ou ele já é carregado na memória ao inicializar a aplicação? Outra pergunta, você o abre com `.Show` ou `.ShowModal`?
Comment: Entao crio o form em run com tform.create (self) ai exibo com show pq com modal nao consigo chamar outra tela....
Comment: Uma pergunta bem curiosa, você está usando ferramenta fmx para desenvolver aplicativos Android?
Comment: Repare na documentação da própria **Embarcadero** (http://docwiki.embarcadero.com/Libraries/Tokyo/en/FMX.Forms.TForm.OnClose) que o *caFree* já libera o *form* da memória. Então presumo que haja alguma outra coisa errada na forma que os *forms* estão sendo carregados para a memória.
Comment: Entao gente estou criando ele assim formage:=tformage.create (self); formage.show; lembrando q marquei ele pra ser criado em runtime....
Answer: Remova do procedimento OnClose os 2 procedimentos informados.
E após a exibição do Formulário (que logicamente ocorreu após a criação)
você aplica a destruição:
formage := Tformage.Create(Application);
formage.ShowModal;
FreeAndNil(formage);

Observe que após a Exibição é chamado o método de detruição! Esta é a meneira correta de controlar a memória.Lembrando que o Delphi é fraco nesse gerenciamento.
Ou seja, dentro do formulário formage você deve controlar a criação e destruição de suas variáveis.
Comment: O correto é o FreeAndNil(objeto);
Comment: O problema é se o programador não usa `ShowModal`, aí o controle de liberação de memória tem de ser diferente.
Comment: Sim, sem `ShowModal` ele perde o controle, teria que implementar um Timer e ficar pesquisando Variável X para saber se é hora do `FreeAndNil(formage)`. Ai é muita Gambiarra.
Comment: Ta entao cancelo o onclose... e destruo com o free.... e nao poderia ser com dispeseof??
Answer: Gente resolvi assim:
O formage cria o formaux...no formaux tem um button que faz o q preciso e chama de novo o formage.show; O formage volta pra tela....quando clico no checkbox ele verifica de novo se o formaux é nil e chama de novo fechando o ciclo..
Comment: Está muito confusa sua resposta, se conseguir melhorar a explicação facilitará bastante se outros usuários tiverem a mesma dúvida.
Comment: Me deparei com o mesmo problema e corrigi dessa maneira: https://pt.stackoverflow.com/questions/254155/erro-criando-novas-telas-no-delphi-para-android/254277#254277

Form nao descarrega da memória


IIS6 and Windows Server 2003 unable to access ASP.Net site through external IP Address

Question: When I access the site from the server itself (via remote PC) or within the network using the name of the machine I can access the site just fine, but when I try to use the external IP of the server I get generic errors
If I specify the path completely (i.e. https :// server/MYApp/Default.aspx) I get:
"The resource cannot be found." in a standard ASP.Net error page style
If I specify just the virtual directory  (i.e. https :// x.x.x.x/MYApp/) I get:
"The system cannot find the file specified."
I'm pretty sure that it is able to connect to the ip address since it's downloading the security certificate ok and it's coming back with an actual error page.
I'm not exactly sure which details will be most useful but I would appreciate any help if anyone has encountered a similar error before.
Answer: It sounds to me like your site is not set to listen on the external ip of the server, go into the site bindings and add that in. By the sounds of it, your default site is listening on that ip so you may need to either add a host header with this, or remove the ip from the default site.


Rota de view não consegue ser exibida em yii

Question: Boa tarde.
Eu estou aprendendo o desenvolvimento do framework YII do PHP
Estou seguindo um tutorial, em que a pessoa mostra como criar a rota e como cria-la.
Criei meu controler chamado HelloController dentro da pasta controllers
   <?php

namespace app\controllers;
use yii\web\Controller;

class HelloController extends Controller
{
    public function actionSaySonething()
    {
        return $this->render('teste',[

        ]); // TODO: Change the autogenerated stub
    }
}

Ai na pasta views criei uma pasta chamada hello com um arquivo chamado teste.php
teste.php
<?php

echo 'oi';

Reparei que as rotas são chamadas dessa forma:
http://localhost/basic/web/index.php?r=site%2Flogin

e funciona com os arquivos que vem com o yii, agora quando eu coloco
http://localhost/basic/web/index.php?r=hello%2Fteste

não encontra.
Answer: A rota no yii é configurada por padrão para ser chamada da seguinte forma controlador/ação ou modulo/controlador/ação.
Neste seu primeiro exemplo:
http://localhost/basic/web/index.php?r=site%2Flogin

A rota é o controlador site e ação é o login, se for olhar no SiteController vai existir uma ação chamada login.

No segundo exemplo:
http://localhost/basic/web/index.php?r=hello%2Fteste

Você está solicitando ação teste do controlador hello, ai que está o problema a ação declarada é a SaySonething e solicitando a teste que não existe.

A solução do problema é colocar na url controlador/ação da seguinte forma:
http://localhost/basic/web/index.php?r=hello%2Fsay-sonething


didBeginContact:(SKPhysicsContact *)contact not invoked

Question: I have created SKScene inherited class.
Problem is that on contact of physics body method
- (void)didBeginContact:(SKPhysicsContact *)contact

is not invoked
solution may be simple but  as beginner with sprite kit i am stuck with this.
Below is the code
#import "MyScene.h"
@interface MyScene ()
@property BOOL contentCreated;
@end
@implementation MyScene
- (id)initWithSize:(CGSize)size {
    self = [super initWithSize:size];
    if (self) {
        self.physicsWorld.contactDelegate = self;
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    }
    return self;
}
- (void)didMoveToView:(SKView *)view
{
    if (!self.contentCreated) {
        [self buildWorld];
        self.physicsWorld.contactDelegate = self;
    }
}

#pragma mark - World Building
- (void)buildWorld {
    NSLog(@"Building the world");
    SKSpriteNode * sprite1 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
    sprite1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
    sprite1.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) +100);

    SKSpriteNode * sprite2 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
    sprite2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
    sprite2.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 100);

    [self addChild:sprite1];
    [self addChild:sprite2];
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
    NSLog(@"contact");
}

@end

Thanks in advance.
Comment: @Alexander they do fall down to touch each other
Answer: From the SKPhysicsWorld documentation:

A contact is created when two physics bodies overlap and one of the
  physics bodies has a contactTestBitMask property that overlaps with
  the other body's categoryBitMask property.

You have to assign the physics bodies a categoryBitMask and a contactTestBitMask. You want to first create your categories:
static const uint32_t sprite1Category = 0x1 << 0;
static const uint32_t sprite2Category = 0x1 << 1;

Next, assign the category and contact test bit masks:
sprite1.physicsBody.categoryBitMask = sprite1Category;
sprite1.physicsBody.contactTestBitMask = sprite2Category;

sprite2.physicsBody.categoryBitMask = sprite2Category;
sprite2.physicsBody.contactTestBitMask = sprite1Category;

Note from the SKPhysicsBody documentation:

For best performance, only set bits in the contacts mask for
  interactions you are interested in.


How do I find these bounds using Chebychev's inequality and the Central Limit Theorem?

Question: Let $X$ have gamma distribution with parameters $\alpha=7$ and $\lambda=1$. Investigate the value of $F_X(10)$ using these methods:

Find a lower bound using Chebychev's inequality.
Approximate the value using the central limit theorem.
Comment: If this is homework, it should be marked as such. What have you tried so far? Do you know what Chebychev's inequality says? Do you know what the Central Limit Theorem says, and why it is (sort of) applicable in this case?
Comment: In what way can you think of your Gamma-distributed random variable as a sum of iid random variables?
Comment: I think I figured out finding the lower bound using Chebychev's inequality. The central limit theorem deals with zn converging with standard normal distribution. I thought I had to calculate zn, which means I need n. I don't understand what the value of n would be.
Comment: I used the equation z=mean of X-mu/(standard deviation/sqrt(n)) but I'm not sure what n would be.
Comment: Well, if W_i is the waiting time for the ith arrival, and X is the gamma random variable, X is the sum of w_i with i=1,2,...,7 but I'm still not sure how to use this
Answer: The central limit theorem says that the average of iid random variables $y_i$ having mean $\mu$ and variance $\sigma^2$ converges to a normal distribution with mean $\mu$ and variance $\sigma^2/n$.
You know that we can express the gamma-distribution random variable $X$ as
$$X = \sum_{i=1}^7 W_i $$
where $W_i \sim \operatorname{Exp}(1)$ has mean 1 and variance 1. That's a sum, not an average, but we can divide both sides by $7$ and then apply the CLT:
$$X/7 = \frac{1}{7}\sum_{i=1}^7 W_i \; \dot\sim \; \operatorname{Normal}(1,1/7).$$
So, multiplying by 7 again,
$$X \; \dot\sim \; \operatorname{Normal}(7,7).$$
Now you can use the normal CDF to approximate $F_X(10)$.
Note that we could have decomposed the Gamma into a sum of $k$ iid $\operatorname{Gamma}(7/k,1)$ random variables for any $k \in \mathbb{N}$ (this property of a distribution is called "infinite divisibility"). We could have ended up with a sum of 16 billion $W_i$ instead of just 7, but our end result would have been exactly the same. This illustrates the point that there isn't a magic number (30, often) after which the CLT "applies."
Comment: Apart from the (obvious) fact that these are both in $[0,1]$, there is no guarantee that the approximation of $F_X(10)$ by $F_Y(10)$ with $Y$ normal $(7,1)$ (and not $(1,7)$...) is good or not.
Comment: Thanks for catching that the mean should be $7$, not $1$, but it should be a $\operatorname{Normal}(7,7)$, not $(7,1)$. That there's no guarantee the approximation is good is exactly the point I was making in my last paragraph, but this is the approximation the problem asked for.


Don't see Mail System under Configuration

Question: I'm currently going through the prerequisites of Acquias configuring platform email
https://docs.acquia.com/cloud-platform/manage/platform-email/platform-email-configuration/#associate-domain
but I do not see the Mail System to check what our default Mail System is. Does this mean We are using a different one? I do see Nemo Integration but still expected to be able to access Mail System.

thanks
Answer: Looks like you don't have the Mail System module installed and enabled on your site. If you want to use only the default Drupal PhpMailer, then you don't need Mail System. You only need to use Mail System if you install a different mailer and want to use that different mailer.
Comment: Thank you, is there any way i can check and make sure i'm using the default Drupal PhpMailer?
Comment: Using drush from the command line, type `drush php-eval "foreach (\Drupal::service('plugin.manager.mail')->getDefinitions() as \$plugin) {print_r(\$plugin['class'] . \"\n\");}" ` which will show you the *available* mailers. Drupal core provides Drupal\Core\Mail\Plugin\Mail\TestMailCollector and Drupal\Core\Mail\Plugin\Mail\PhpMail, and if you only see these and you can be sure that PhpMail is the only mailer in use. If you see other options, then some other module is providing a mailer which *may* be used.
Comment: thanks but i seem to be getting the below error `In Drupal.php line 130:

  \Drupal::$container is not initialized yet. \Drupal::setContainer() must be
   called with a real container.`


Shuffle.js - looking for a way to filter using

Question: I've been playing with Shuffle.js and really like how smooth it is. I'm looking for a way to filter the results using SELECT form field.
Second part of my question: Is this even a good idea to use SELECT to filer? I have successfully figured out how to filter using an unordered list as the dropdown, but the problem is the selected term doesn't stay highlighted when it collapses... which is why I'm looking at SELECT. I appreciate any feedback!
Here's what my code looks like (bootstrap 3 + wordpress):

                Filter Field Notes Category

All

                    <?php foreach($custom_terms as $custom_term) { ?>

<a href="#" data-group="<?php echo $custom_term->slug ?>"><?php echo $custom_term->name ?>

                    <?php }  ?>

https://vestride.github.io/Shuffle/
------------------------UPDATE------------------------
So I've been searching for a couple of hours today and decided to give up on trying to use Select dropdown, and shifted my attention to trying to simulate it instead. This is a great workaround: http://jsfiddle.net/Starx/a6NJk/2/
It is quite a simple and elegant solution using jQuery and some JS. Just had to replace the data-group variables in each list item and it works great to filter with Shuffle.js. Hope this helps anyone looking to do the same!
HTML

[SELECT]

Option 1

Option 2

Option 3

CSS
ul {
  height: 30px;
  width: 150px;
  border: 1px #000 solid;
}
ul li { padding: 5px 10px; z-index: 2; }
ul li:not(.init) { float: left; width: 130px; display: none; background: #ddd; }
ul li:not(.init):hover, ul li.selected:not(.init) { background: #09f; }
li.init { cursor: pointer; }

a#submit { z-index: 1; }

JS
$("ul").on("click", ".init", function() {
    $(this).closest("ul").children('li:not(.init)').toggle();
});

var allOptions = $("ul").children('li:not(.init)');
$("ul").on("click", "li:not(.init)", function() {
    allOptions.removeClass('selected');
    $(this).addClass('selected');
    $("ul").children('.init').html($(this).html());
    allOptions.toggle();
});

$("#submit").click(function() {
    alert("The selected Value is "+ $("ul").find(".selected").data("value"));
});

Answer: I found a workaround and have edited my original post. Hope it helps!


Oracle SQL - Subtracting Date types

Question: I'm trying to project a column that subtracts an employee's start time from end time to get total hours worked.
Here's what I have:
select task_name "NAME", to_char(ses_start, 'DD-MON-RR') "DATE", to_char(ses_start,'HH:MI PM') "START", to_char(ses_end, 'HH:MI PM') "END",to_number(to_char(ses_end,'HH24:MI')) - to_number(to_char(ses_start,'HH24:MI')) "TOTAL"

The TOTAL column isn't working - is it even possible to do something like this? It worked up until I added that column, with output similar to:
TASK_NAME          DATE        START      END
----------------- ------------ ---------- -----------
create flyers     26-MAR-16    02:00 PM   04:30 PM
update website    28-MAR-16    11:00 AM   01:00 PM

So now I want a final column (preferably in hours):
TOTAL
-----
2.5
2

or, at least in hours&minutes (this is what I was trying to do)...
TOTAL
-------
02:30
02:00

Any suggestions?
Answer: you can substract Date types in oracle, it gives you a decimal number which is the duration in days
select
  task_name,
  to_char(ses_start, 'DD-MON-RR') DATE,
  to_char(ses_start,'HH:MI PM') START,
  to_char(ses_end, 'HH:MI PM') END,
  round((ses_end - ses_start) * 24, 2) DURATION_IN_HOUR
...

Oracle SQL - Subtracting Date types


How can I prove this sequence converges to 1?

Question: Suppose $0<a<1$ and define $a_n=(1+a^n)^n$, show that $a_n \to 1$ by using binomial expansion on each $a_n$ and compare to a geometric sum.
I know how to compute binomial on $a_n$ but I am really confused by "using binomial expansion on each $a_n$ and compare to a geometric sum".
Answer: I guess they've meant "to compare to a geometric sum", here's what you can do:
\begin{align} (1+a^n)^n &= \sum_{k=0}^n \binom{n}{k} a^{nk} = \sum_{k=0}^n \frac{n(n-1)\dots(n-k+1)}{k!} a^{nk} \le \\
&\le \sum_{k=0}^n \frac{n^k}{k!}a^{nk} \le \sum_{k=0}^n n^ka^{nk} \le \sum_{k=0}^\infty (na^n)^k = \frac{1}{1-na^n}\end{align}
For $0<a<1$ we have $$\lim_{n\rightarrow\infty} na^n = 0$$so $$ \lim_{n\rightarrow\infty} \frac{1}{1-na^n} = 1 $$
and using the squeezing $$ 1\le a_n \le \frac{1}{1-na^n}$$
we get $$ \lim_{n\rightarrow\infty} a_n = 1$$
Comment: That seem the most logical way to do it, why is $\sum_{k=0}^n \frac{n^k}{k!}a^{nk} \le \sum_{k=0}^\infty (na^n)^k$ true though?
Comment: $ \frac{n^k}{k!} \le n^k$, and additing more terms (all of which are positive) only increases the sum. I've added an extra step to make it clearer.


Ruby Qt documentation

Question: Where can I find the documentation for ruby qt?
(ex. rdoc)
Answer: There is also this http://techbase.kde.org/Development/Languages/Ruby
Answer: Well you can use the rbqtapi program to find which functions have been implemented, but it almost identically matches the Qt library. The only main difference is objects like QPushButton are actually named Qt::PushButton.

Ruby Qt documentation


Odd Corollary in Baby Rudin Chapter 2, Question 28

Question: I've finished all the questions in Chapter 2 of Principles of Mathematical Analysis by Walter Rudin (self study), but I have a question about Q.28, which reads:

Prove that every closed set in a separable metric space is the union of a (possibly empty) perfect set and a set which is at most countable. (Corollary: Every countable closed set in $\mathbb{R}^k$ has isolated points.)

It's easy to answer the question, given what's proved in Q.27, but the corollary is a bit weird. It looks to me as though it is just an immediate consequence of the fact that non-empty perfect sets in $\mathbb{R}^k$ are uncountable, which is proved in the main text. I don't see what it has to do with what is proved in this question.
Given how meticulous the book is, I suspect the apparent non-sequiteur means I'm missing something.
Comment: This is not a duplicate of the question linked to. The other question is not about how the corollary has nothing to do with the excercise.
Answer: An isolated point by def is a point that belongs to the set that is not a limit point. Suppose the closed countable set had no isolated points, then EVERY point of it is a limit point. Thus the set is perfect. But a non-empty perfect set in $\mathbb{R}^n$ is uncountable. Contradiction.
The separable space here is $\mathbb{R}^n$. The corollary is definitely sequitur.
Comment: But that doesn't use the main body of the question, to which it is supposed to be a corollary: "every closed set in a separable metric space is the union of a (possibly empty) perfect set and a set which is at most countable".
Comment: To be clear, I'm not saying I have difficulty seeing that the corollary is true - it's obviously true. I have difficulty seeing in what way it is considered to be a "corollary" of Q.28.
Comment: It does. The theorem says ANY closed set can be decomposed as such. But for a "closed" countable set, the perfect part is forced empty due to cardinality reasons. This means that a closed countable set is NOT perfect (nor does it have a subset that is nonempty perfect) and so it has isolated pts.
Comment: There's nothing in the result proved in Q.28 to say the countable part can't itself be perfect. An example is $\mathbb{Q}$, considered as a metric space in its own right. You can decomposing the whole of $\mathbb{Q}$ (closed) into the empty set and $\mathbb{Q}$ itself, which is both countable and perfect. To prove the corollary you need the additional fact that perfect subsets of $\mathbb{R}$ are uncountable. However, that is **all** you need (it's trivial to prove the corollary from it alone) and I still can't see how the decomposition in Q.28 contributes in any way.
Comment: My analysis was for $R^k$, not all separable metric spaces. In $R^k$, countable sets are not perfect. But I get what you are saying. The fact that perfect sets are uncountable was indeed enough to arrive at the conclusion and the theorem could have been bypassed.
Comment: (of $\mathbb{R}^k$, I mean)
Comment: "In $\mathbb{R}^k$, countable sets are not perfect." - yes, that's why I had to use $\mathbb{Q}$ as a metric space in its own right to make the point. I was just trying to show that the decomposition in Q.28 was extraneous and that what really matters is the uncountability of perfect sets in $\mathbb{R}^k$.


Jquery Trigger Method not working by Chrome

Question: Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$('#testFile').trigger("click");

<input type="file" id="testFile" />

IE works but Chrome does not.
Chrome version is 71. but version 81 is working.
Please help me.
Comment: There's nothing you can do about this not working in Chrome 71. However no one should be using that version
Comment: so here a little thing is not clear. when you want to perform this action? on window load?
Answer: In the console of the developer tools is the following warning:
jquery.js:8510 File chooser dialog can only be shown with a user activation.

A solution could it be to handle the trigger through the click on a button like this example

$(document).ready(function() {

  $('#testButton').on('click', triggerFile);

  function triggerFile() {
    $('#testFile').trigger("click");
  }

});

<input type="file" id="testFile" />
<button type="button" id="testButton">Test</button>


Database table - Converting Date to Number

Question: I am trying to convert a date to a number.
I need to have in my table a field with default value based on a date.
So if today is 23/01/2018, I want to have a number look like this 23012018.
Any ideas?
Answer: You can use the format command like this:
<code>=Format$(Date, "ddmmyyyy")
</code>
Comment: This will leave the data as a date type. If you want to store the information as a number you will have to convert it to a number, but if you do, it will remove any leading zeros. The other option is to change the formatted date type to a string type possibly using `cstr`


Finding a monotonically increasing sequence of integers

Question: I'm trying to find a monotonically increasing sequence of integers, the sequence should be increasing as slow as possible and it has couple of additional requirements:

$n_{i+1} \gt n_i$
$n_{i} + n_{j+1} \gt n_{i+1} + n_{j}$ where $i+1 < j$

As an example we may consider a sequence of positive integers.
$$
\left\{
n
\right\}^{4}_{n=1}
$$
If $i=1$ and $j=3$, $1+4 = 2+3$ which violates 2nd requirement.
The best what I was able to find so far is Fibonacci sequence which seems to work for both requirements if $i \ge 2$.
Comment: Since you point out that the sequence should be monotonically increasing, 1. should be $n_{i+1} > n_i$, I think. Also, I'm not sure what 'the sequence with the smallest memory consumption' means.
Comment: @Ruben You are right, fixed, thanks.
Comment: @Ruben The smaller amount of bytes it takes to store finite sequence the better it's in terms of memory consumption.
Comment: If you are looking for a finite sequence you could just look at an empty sequence. So I assume you are looking for an infinite sequence that increases, but as slowly as possible? Also, the second requirement is probably easier to understand if you write it as $n_{i + 1} - n_i \not = n_{j+1} - n_j $. I would expect $i < j$ or $i \not = \ j$ here as a condition, are you sure this is right?
Comment: @Ruben Yes, you are correct, infinite sequence, but it may be increased by $0.00000001$ which is slower than increasing by $1$, but takes more bytes to store. I've corrected 2nd requirement a bit. With $i + 1 < j$ I want to make sure, that there is no "overlapping" between $(i, i+1)$ and $(j, j+1)$.
Comment: You should clarify your question. Specifically, you need to specify which encoding you are using (or if you are free to pick any encoding), and you need to define 'the smallest memory consumption' more precisely.
Answer: If I interpret the "smallest memory" as a sequence that as many terms can be stored for a given memory size as possible. In other words, the sequence should be increasing as slow as possible while meeting the requirements. The OP is further 'implying' that (yeah, this question is really not clear at all) a step size smaller than 1 may take more memory, which means that he is thinking to store data in integer type, not in floating point.
As the sequence should meet $$a_n > a_{n-1}+a_{n-2}-a_{n-3},$$ the slowest sequence will be $$a_n = a_{n-1}+a_{n-2}-a_{n-3}+1$$
So $a_0,a_1,a_2\dots$ will be:
$$0,1,2,4,6,9,12,16,20,25,30,36,42\cdots$$
And it is observed that the steps are:
$$1,1,2,2,3,3,4,4,5,5,6,6\cdots$$
Therefore,
\begin{align}
&a_{n}-a_{n-1}=\lfloor \frac {n+1}2\rfloor, \quad \text{or}\\
&a_{2n}-a_{2n-1}=n\\
&a_{2n+1}-a_{2n}=n+1\\
&a_{2n}-a_{2n-2}=2n\\
&a_{2n}=\sum_{k=1}^n2k=n(n+1)\\
&a_{2n+1}=n(n+1)+n+1=(n+1)^2\\
\end{align}
Or, simply
$$a_n=\lfloor\frac {n+1}2\rfloor\lfloor\frac {n+2}2\rfloor$$
To check if this sequence meets your 2nd requirements (obviously it is increasing so it meets the 1st requirement), if
$$j>i+1 \rightarrow j\ge i+2$$
then
$$a_{j+1}-a_j=\lfloor \frac {j+2}2\rfloor>a_{i+1}-a_i=\lfloor \frac {i+2}2\rfloor$$
Comment: I've thought of this answer as well, but you can't represent an infinite sequence that goes to infinity with the usual integer representations, so technically this answer is not correct (not your fault, because the current form of the question is technically not answerable).


How do I loop over result rows and return calculated values?

Question: I cannot get proper results from View PHP field.
I've set up a Flipped Table view of entity form submission of which I'm trying to calculate "results" (sum and count(for avg)) with following code
<code>$results = array(); // For results
$static = get_object_vars($row);
dsm($static);
foreach($static as $key => $value) {
    if(strpos($key,'field_') !== FALSE){
        if($value !== NULL){
            $results[$static['entityform_id']]['count']++; // Count no. of fields
            $results[$static['entityform_id']]['sum']= $results[$static['entityform_id']]['sum']+$value; // Count sum of field values
        }
    }
}
return json_encode($results[$static['entityform_id']]);
</code>
which results:
<code>{"count":55,"sum":55}   {"count":55,"sum":110}  {"count":55,"sum":165}  {"count":55,"sum":220}
</code>
At this point I do not understand that why sum is always row index * sum? Eg.1 =55, 2=110, 3=165... All the submissions have the same fields and field values (clones) which explaines sums but I can't figure out that where this multiplication "logic" happens?
It seems like it is looping/counting all four result rows every time.
Answer: This is because $results[$static['entityform_id']]['sum'] already contains the sum result from previous loop result.
Thus it adds 55 for every row iteration.
Try adding the current array index to $results inside foreach loop.
Comment: How can it contain since entityform_id is different(1...4) and being used as an array index to separate calculated values for each submission? It should create new index and therefore value should be empty. But I'll try to use some other method for indexes and we'll see what then happens...
Comment: Correct me if i am wrong..
How can entity form id be different if you are iterating over the submissions of a particular form..
Comment: Yeah, I know. That's a bit misleading. In Views guidelines it is named like that as "entityform id" but the description states that it is actually submission ID. And I did verify it by debugging.
Comment: Okay, now that I tried to debug the actual field values it shows that all values are overriden. For the first submission value is 1 and so on until 4 (submission id). And to get these results I'm only using print function to view $row variable and not modifying any variable. Really weird...
Comment: Did you try creating views handlers for your entity fields ??

That way you can get more flexibility with operations and customizations on the fields.
Comment: Sorry, I have no idea about Views API or related handlers. Can I use it to create a field "instance" as part of each result row? By a quick review it seems like "adding new field to query" which is pointing into already available field entities. However, in my solution I need so to speak JIT or on-the-fly field that is calculated from available fields.


"\t" and  not working when I run my code

Question: <!doctype html>

    <?php
    echo "
your order is processed !!!!

";
    $akash = $_POST["tires"];
    $akash2 = $_POST["Oil"];
    $akash3 = $_POST["plugs"];
    $akash4 = $_POST["hello"];
    $write = "tires is  ".$akash."
" ."Oil is " .$akash2."\t" ."Spark plug is " .$akash3."\t". "address is  " .$akash4."
";
    $open = fopen("order.txt","ab");
    $write = fwrite($open,$write);
    ?>

Comment: In what way are they not working? How are you displaying your resulting text file?
Comment: `\t` is not html, `` is html, if you open the file in browser you will get linebreaks, if you open it in notepad you propably get `tabs`. To linebrake in notepad you need `\n` or better use `\r\n`. Also, its not very important but..., you dont close the handle from `fopen`. And why are you overriding your string with the write-state ?
Comment: tires is  4Oil is 2 litres Spark plug is 6 address is  email@example.com order was processed atSun Sep 2014              this is how my text file looks after i run my code
Comment: possible duplicate of [Create Carriage Return in PHP String?](http://stackoverflow.com/questions/15131619/create-carriage-return-in-php-string)
Answer: Try  /r/n rather
(it's a html tag will not work with txt)
$write = "tires is  ".$akash."\r\n" ."Oil is " .$akash2."\t" ."Spark plug is " .$akash3."\t". "address is  " .$akash4."\r\n";
$open = fopen("order.txt","ab");
$write = fwrite($open,$write);
fclose($open);

in my case output is:-
tires is  sdff
Oil is ddddd    Spark plug is fffff address is  ggggg

Comment: Thanks it works. But what does \r\n mean
Comment: \r - carriage return , \n - newline you need to accept/upvote helpful answers
Answer: you may want to drop the "b" in the fopen statement.
From the manual , option b is "binary" which is probably causing the error.

"\t" and  not working when I run my code


Determine if the integral $ \intop_{0}^{\infty}\left(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\right)dx $ convergent

Question: So, I need to determine if the integral $ \intop_{0}^{\infty}\left(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\right)dx $ convergent, for any $ C\in \mathbb{R} $.
I found that for C=1 the integral convergent. I think its easy to show that for $ C\leq 0 $ the integral will diverge, but I dont know how to determine for the rest of the real values.
Here's what I've done:
for any $ 0<t $
$ \intop_{0}^{t}\left(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\right)dx=\intop_{0}^{t}\frac{1}{\sqrt{x^{2}+4}}dx-\intop_{0}^{t}\frac{C}{x+2}dx=\intop_{0}^{t}\frac{1}{\sqrt{x^{2}+4}}dx-C\ln\left(t+2\right)+C\ln2  $
Now, we'll calculate the integral $ \intop_{0}^{t}\frac{1}{\sqrt{x^{2}+4}}dx $
$ \intop_{0}^{t}\frac{1}{\sqrt{x^{2}+4}}dx=\intop_{0}^{t}\frac{1}{2\sqrt{\left(\frac{x}{2}\right)^{2}+1}}dx $
And let $ \frac{x}{2}=\sinh u $
so $ dx=2\cosh udu $
and we get
$ \intop_{0}^{t}\frac{1}{2\sqrt{\left(\frac{x}{2}\right)^{2}+1}}dx=\intop_{0}^{aricsinh\left(\frac{t}{2}\right)}1du=arcsinh\left(\frac{t}{2}\right)=\ln\left(\frac{t}{2}+\sqrt{1+\left(\frac{t}{2}\right)^{2}}\right) $
In order to determine if the integal converges, its enough to calculate the limit :
$ \lim_{t\to\infty}\left(\ln\left(\frac{t}{2}+\sqrt{1+\left(\frac{t}{2}\right)^{2}}\right)-c\ln\left(t+2\right)\right) $
If c=1 then the limit will be 0, and thus the integral converge, because we'll have:
$ \lim_{t\to\infty}\ln\left(\frac{\frac{t}{2}+\sqrt{1+\left(\frac{t}{2}\right)^{2}}}{t+2}\right)=\ln\left(1\right)=0 $
How can I determine for $ C\neq1 $ ?
Is there a way to calculate the limit for $ C\neq 1 $ ?
Thanks in advacnce
Comment: $\displaystyle {1 \over \,\sqrt{\, x^{2} + 4\,}\,} - {C \over x + 2} \sim
{1 - C \over x} + {2C \over x^{2}} - {4C + 2 \over x^{3}}$ as $\displaystyle x \to \infty$.
Answer: $$I(p)=\int_{0}^{p}\left(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\right)dx=\sinh ^{-1}\left(\frac{p}{2}\right)-C (\log (p+2)-\log (2))$$ Using Taylor expansion
$$I(p)=(1-C) \log (p)+C \log (2)-\frac{2 C}{p}+O\left(\frac{1}{p^2}\right)$$ Then ... ??
Answer: Note
\begin{eqnarray}
&&\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\\
&=&\frac{x+2-C\sqrt{x^{2}+4}}{(x+2)\sqrt{x^{2}+4}}\\
&=&\frac{(x+2)^2-C^2(x^{2}+4)}{(x+2)\sqrt{x^{2}+4}(x+2+C\sqrt{x^{2}+4})}\\
&=&\frac{(1-C^2)x^2+4x+4(1-C^2)}{(x+2)\sqrt{x^{2}+4}(x+2+C\sqrt{x^{2}+4})}
\end{eqnarray}
If $1-C^2>0$ or $|C|<1$, then there is $N>0$ such that, for $x>N$,
$$ \frac{(1-C^2)x^2+4x+4(1-C^2)}{(x+2)\sqrt{x^{2}+4}(x+2+C\sqrt{x^{2}+4})}>0 $$
and
$$ (1-C^2)x^2+4x+4(1-C^2)=O(x^2), (x+2)\sqrt{x^{2}+4}(x+2+C\sqrt{x^{2}+4})=O(x^3)$$
which implies
$$ \frac{(1-C^2)x^2+4x+4(1-C^2)}{(x+2)\sqrt{x^{2}+4}(x+2+C\sqrt{x^{2}+4})}=O(\frac1x) $$
and hence
$$ \int_N^\infty\bigg(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\bigg)dx $$
diverges. So does
$$ \int_0^\infty\bigg(\frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}\bigg)dx. $$
If $1-C^2=0$, then $C=\pm1$. For $C=-1$
$$ \frac{1}{\sqrt{x^{2}+4}}-\frac{C}{x+2}=\frac{1}{\sqrt{x^{2}+4}}+\frac{1}{x+2}>\frac{1}{x+2}, $$
and hence the integral diverges.
For For $C=1$
$$ \frac{1}{\sqrt{x^{2}+4}}-\frac{1}{x+2}=\frac{4x}{(x+2)\sqrt{x^{2}+4}(x+2+\sqrt{x^2+4}))}=O(\frac{1}{x^2}) $$
and hence the integral converges.
Comment: For C=1 actually the expression you wrote is smaller than 1/x+2 and I showed that the integral converges for C=1. For the case $ 1-C^2 \neq 0 $ we cant use comparison test without proving that the functions does not change the sign starting from some point, thats where i couldnt finish the proof.
Comment: It is easy to fix. If $|C|<1$, there is $N>0$ such that $\frac{1}{\sqrt{x^2+4}}-\frac{C}{x+2}>0$ for $x>N$. Treat $|C|>1$ the same way.


[Webpack][React] On SSR with code-splitting how I can get the list of chunks needed by the page?

Question: I've a React application with perfectly working SSR and Webpack code-splitting.
My webpack.config.js looks like this:
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ServerMiniCssExtractPlugin = require("./server/utils/serverMiniCssExtractPlugin");

module.exports = [{
  name: 'react-app',
  mode: 'development',
  devtool: 'eval',
  cache: true,
  entry: {
    main: [
      'babel-polyfill',
      'webpack-hot-middleware/client',
      './react/index.tsx',
    ],
  },
  output: {
    path: `${__dirname}/dist/__build__`,
    filename: '[name].js',
    chunkFilename: '[name].js',
    publicPath: '/__build__/',
  },
  module: {
    rules: [{
      test: /\.(ts|js)x?$/,
      loader: 'babel-loader',
      exclude: [/node_modules/],
    }, {
      test: /\.scss$/,
      oneOf: [{
        resourceQuery: /^\?raw$/,
        use: [MiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: false,
            localIdentName: '[local]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }, {
        use: [MiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: true,
            localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }]
    }],
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        CLIENT: JSON.stringify(true),
      },
    }),
    new webpack.IgnorePlugin(/^vertx$/),
    new MiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "style.chunk.[id].css"
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /node_modules/,
          name: 'vendor',
          enforce: true
        },
      },
    },
  },
}, {
  name: 'server-side rendering',
  mode: 'development',
  devtool: 'eval',
  cache: true,
  entry: [
    './react/ssr.tsx',
  ],
  target: 'node',
  output: {
    path: `${__dirname}/dist/__server__/`,
    filename: 'ssr.js',
    publicPath: '/__server__/',
    libraryTarget: 'commonjs2',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  module: {
    rules: [{
      test: /\.(ts|js)x?$/,
      exclude: [/node_modules/, /.+\.config.js/],
      loader: 'babel-loader',
    }, {
      test: /\.scss$/,
      oneOf: [{
        resourceQuery: /^\?raw$/,
        use: [ServerMiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: false,
            localIdentName: '[local]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }, {
        use: [ServerMiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: true,
            localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }]
    }],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        SERVER: JSON.stringify(true),
      },
    }),
    new webpack.IgnorePlugin(/^vertx$/),
    new ServerMiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "style.chunk.[id].css"
    }),
  ],
}];

... and it generates chunks for both js and css that using the app are loaded correctly when moving from the different pages, all mapped with react-router.
The problem is that when I reload one of the pages the needed css chunks are loaded once rendered and not linked directly in the page from the SSR, so for a second I have FOUC.
Since I would like using React-Helmet to inject in the page head the needed css chunks when I SSR the app how I can get in the code the list of chunks file names that are needed for the page that I reload?
Let say that the page needs:
0.js
2.js
style.chunk.0.css
style.chunk.2.css
How I can get the list of these files so I can generate dynamically the links in the page head?
Thanks.
Answer: Use the webpack-manifest-plugin to generate a manifest.json file that will include a list of all your chunks.
In your webpack.config.js:
var ManifestPlugin = require('webpack-manifest-plugin');

module.exports = {
    // ...
    plugins: [
      new ManifestPlugin()
    ]
};

This will generate a manifest.json file in your root output directory with a mapping of all source file names to their corresponding output file, for example:
{
  "mods/alpha.js": "mods/alpha.1234567890.js",
  "mods/omega.js": "mods/omega.0987654321.js"
}


Generate new password for users periodically and notify user of new password

Question: I am running a private Drupal 7 site where all user accounts are created by admins and managers. I need to ensure that all users have access to the email account that their accounts were created with.
What is the best way to do the following:

Create a user account with an automatically generated password, and notify the new user of their password via email.
After a 4 week period, a new password must be generated for the user and set as their active password automatically. The user needs to be notified of their newly updated password via email, and the newly generated password must be used to access the site until it is reset again.

Are there any Drupal 7 modules that can help achieve this?
Any suggestions on building a custom module that can help resolve this?
Comment: Hate to be "that guy"...but if you're planning to send the password out over email, you'll never be ensuring anything. Far too easy to intercept
Comment: In many jurisdictions your plan is outright illegal. In some others, if you mail users' passwords you can't keep them responsible for anything they do - but they can hold *you* responsible for actions made using their accounts. What you plan to do is to **give away their passwords on regular basis**. You will be giving it to mailserver admins (both your and theirs), and potentially to anyone in the same open WiFi at coffe point your clients are. Not to mention anyone who can take a look at their screen over their shoulder. Are you damn sure that's what you want to do?
Comment: I don't mind "that guy" when he makes a lot of sense. What if its a one time login link instead of the actual password? The user is required to change their password imminently after log in through the link.
Comment: @user1732920 one-time login link is usually legal. But aren't you afraid it'll be a nuisance for your users?
Answer: This issue was talked about during the great Drupalgeddon. Because no such bulk reset tool existed for a site.
Here is a recently created tool to perform this task. Other such tools have existed since Drupalgeddon.
Mass Password Reset Module

This module allows users with "Administer users" permission to reset
  all user accounts and notify all users
Details
The module will reset the passwords of all users except the
  administrative superuser id 1. You can optionally reset the
  administrative superuser id 1. Once passwords have been reset, users
  will optionally receive emails using the Drupal password recovery
  email. The password recovery email content can be edited at the
  account settings configuration page.
Use Cases
You have a large number of user accounts pre-created and
  want to send password recovery emails to all users during a site
  launch. You need to quickly change all passwords on a site for
  security reasons.
Answer: You can use the Force Password Change module too. Read the description:

This module allows administrators to force users, by role, individual
  user, or newly created user, to change their password on their next
  page load or login, and/or expire their passwords after a period of
  time.
Comment: Interesting module suggestion, didn't know about this one yet (there are only 17K module, right?). Any idea how to "notify" the user(s) with this module (as in the question)? Or maybe something you could do in combintion with the [Rules](https://www.drupal.org/project/rules) module somehow?


Como criar e usar eventos personalizados

Question: Pesquisando encontrei Event e CustumEvent, ambas podem ser usadas para criar eventos, e para controlar inscrições, remoções e emissões do evento deve-se usar EventTarget, mas não entendi como funcionam, por exemplo, como eu poderia criar um evento personalizado de clique?
//Cria um evento de clique personalizado
const myClick = new Event('myClick');

//Alguma coisa para guardar as chamadas de "addEventListener"

//Adiciona um ouvinte do evento personalizado aos elmentos
myElement.addEventListener('myClick', event => console.log(event));
myOtherElement.addEventListener('myClick', event => console.log(event));

//Quando houver um clique na tela
window.addEventListener('click', function(event) {
    //Percorre uma lista onde ficaria armazenado os elementos que foram adicionado ouvintes do evento
    for(element of elementList) {
        //Se o elemento for igual ao elemento principal do clique na janela
        if (event.target === element) {
            //Dispara o evento customizado de clique
            element.dispatchEvent(myClick);
        }
    }
});

Estou no caminho certo? Como fazer para guardar as chamadas de addEventListener?
O exemplo é exatamente igual ao evento de clique que já existe, é apenas um exemplo. No momento quero saber apenas como se faz nos navegadores modernos, não estou preocupado com compatibilidade
Answer: Basicamente, para se criar um evento customizado e escutá-lo, você deve:

Criar o evento instanciando um novo Event. Como em new Event('eventName');
Disparar o evento usando o método dispatchEvent – disponível no protótipo de EventTarget, implementado por objetos como o Element. Para isso, passa-se a instância criada anteriormente ao dispatchEvent.
Escutar o evento usando o método addEventListener de algum Element.

O exemplo abaixo mostra todo o processo:

// Para criar o evento:
const myClickEvent = new Event('myClick');

const myDiv = document.querySelector('#my-div');

// Para ouvir o evento:
myDiv.addEventListener('myClick', function () {
  console.log('Evento customizado disparado!');
});

myDiv.addEventListener('click', function () {
  // Disparar o evento:
  myDiv.dispatchEvent(myClickEvent);
});

Minha div (clique)

Para saber mais, sugiro a leitura:

Criando e disparando eventos customizados (MDN)
CustomEvent
Comment: Porém dessa forma teria que adicionar dois eventos sempre, não seria automático. Por exemplo, supondo que eu queira adicionar um evento em três elementos, teria que adicionar também três ouvintes do evento de click normal nesses mesmo 3 elementos, se for assim seria melhor adicionar só um e encapsular o que tornaria o meu evento especial numa função que chamaria na primeira linha do callback do ouvinte
Comment: É o que você precisa fazer. Creio que não haja outra forma.
Answer: Se a ideia é disparar o evento myClick sempre que houver um click, você pode fazer o seguinte:
const myClick = new Event('myClick');

document.addEventListener('click', event => {
    EventTarget.prototype.dispatchEvent.call(event.target, myClick);
});

Assim, sempre que ocorrer o evento click, será disparado o evento myClick para o mesmo elemento.

const myClick = new Event('myClick');

document.addEventListener('click', event => {
    EventTarget.prototype.dispatchEvent.call(event.target, myClick);
});

const lis = document.querySelectorAll('li');

for (let li of lis) {
  li.addEventListener('myClick', event => console.log(event.target));
}

Item 1

Item 2

Item 3

Item 4

Item 5

Perceba que mesmo que todos os elementos
 possuem o evento myClick, apenas do elemento pressionado é disparado.

Porém, como o evento tratado é o click em document, só funcionará se o elemento pertencer a árvore de nós em document e o evento tratado se propagar por esta. Se o elemento não pertencer a árvore ou o evento não for propagante, a solução não funcionará. Por exemplo, veja abaixo o exemplo de um elemento que é criado dinamicamente e não é inserido na árvore em document. O evento click de virtual não será propagado até document e, portanto, não irá disparar o myClick.

const myClick = new Event('myClick');

document.addEventListener('click', event => {
    EventTarget.prototype.dispatchEvent.call(event.target, myClick);
});

const virtual = document.createElement('span');

virtual.addEventListener('myClick', event => console.log(event.target));
virtual.click();

Porém, se adicionar o elemento na árvore, document.body.appendChild(virtual), o evento click irá disparar myClick normalmente. Para eventos não propagantes, não funcionará mesmo que o elemento pertença à árvore de nós.
Comment: Acabei voltando nessa pergunta agora e apenas uma dúvida: tem algum motivo específico para utilizar o `call` (`EventTarget.prototype.dispatchEvent.call`) ao invés de simplesmente já aplicar a diretamente função `event.target.dispatchEvent`, que já é uma instância de `EventTarget`?
Answer: var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);

// parametro customizado
evt.foo = "bar";

//registrar
document.addEventListener("myEvent",myEventHandler,false);

//invocar
document.dispatchEvent(evt);

Este é apenas um exemplo simples, maiores detalhes em: http://www.kaizou.org/2010/03/generating-custom-javascript-events/
Comment: Sua resposta não adiciona nada a resposta já existente, além disso, assim como a outra, ela não responde a pergunta
Comment: O que falta para ficar completa?
Comment: A dúvida é como armazenar as chamadas de `addEventListener`
Comment: Defina o que é armazenar as chamadas de um evento. Seria saber quantas vezes um evento foi acionado?
Comment: Quando há uma chamada de `addEventListener`, é adicionado a uma lista para que depois seja executado o callback. Como pegar essa lista? Em algum lugar precisa ser armazenado, mas onde?
Comment: Veja se isso ajudaria, caso sim eu traduzo e coloco em minha resposta https://www.bitovi.com/blog/a-crash-course-in-how-dom-events-work
Comment: Sim, acho que é isso mesmo
Answer: Consegui fazer algo semelhante, talvez não seja a melhor maneira, mas funciona:

//Cria um evento de clique personalizado
const myClick = new Event('myClick');

//Salva a função em um lugar qualquer, no caso, escolhi o protótipo de EventTarget
EventTarget.prototype._addEventListener = EventTarget.prototype.addEventListener;

//Adiciona uma propriedade ao protótipo de EventTarget (poderia ser em qualquer outro lugar)
EventTarget.prototype.customListener = {
  myClick: []
};

//Altera a função addEventListener
EventTarget.prototype.addEventListener = function(type, listener, options) {
  //Se não houver a variável, a cria
  if (!EventTarget.prototype.customListener[type]) {
    EventTarget.prototype.customListener[type] = [];
  }

  //Adiciona o listener à lista
  EventTarget.prototype.customListener[type].push({
    element: this,
    callback: listener
  });

  //Chama a função antiga
  this._addEventListener(type, listener, options);
}

//Adiciona um ouvinte do evento personalizado aos elmentos
document.querySelector('button').addEventListener('myClick', event => console.log('Clicked on button'));
document.querySelector('a').addEventListener('myClick', event => console.log('Clicked on link'));

//A lista de eventos:
console.log(EventTarget.prototype.customListener)

//Quando houver um clique na tela
window.addEventListener('click', function(event) {
    //Percorre uma lista onde ficaria armazenado os elementos que foram adicionado ouvintes do evento
    for(listener of EventTarget.prototype.customListener.myClick) {
        //Se o elemento for igual ao elemento principal do clique na janela
        if (event.target === listener.element) {
            //Dispara o evento customizado de clique
            listener.callback(event);
        }
    }
});
<button>Click here!</button>

Click here too!

Vou implementar num projeto e depois postar um exemplo mais útil (talvez cross-browser também)


Jenkins - How to read the environment variables in groovy post build step

Question: I am trying to read the environment variables in Groovy Postbuild step. I am able to read the values of parameters passed to builds but unable to read the values of parameters which are set in one of my Execute Windows batch command.
In one example of my Execute Windows batch command I do this:
SET custom_param=myValue

if I use ${custom_param} in other jenkins steps/jobs, it gets my value. So I am sure it has the value. I just can't get it in groovy script
I have tried followings to do so, none of them have worked:

manager.envVars['custom_param']
build.buildVariableResolver.resolve('custom_param')
build.getEnvironment(listener).get('custom_param')

Any help here would be great
Comment: Try to echo it in another batch, it usually doesnt work. Check if EnvInject plugin can help.
Comment: Are you executing a "groovy script" or a "system groovy script"? Apparently the the groove script has no access to environment variables. More here: http://stackoverflow.com/questions/21236268/access-to-build-environment-variables-from-a-groovy-script-in-a-jenkins-build-st
Answer: (Assuming you're not running your script in groovy sandbox)

Try the bellow:
build = Thread.currentThread().executable
String jobName = build.project.getName()
job = Hudson.instance.getJob(jobName)
my_env_var = job.getLastBuild().getEnvironment()["YOUR_ENV_VAR"]

Answer: When you set some custom variables in your "Windows command batch" step, these variables are available only during this Jenkins step.
Once Jenkins move on the next step, your variables are lost...
If you want to set some variables permanently, you can try to use the SETX command:
What is the difference between setx and set in environment variables in Windows?
Answer: Groovy Post build step run as separate process. It has access to environment as normal JVM process.
You could use EnvInject plugin as a a build step.  Subsequent steps in build will able to read this via normal environment access (System.env in your groovy script)


Javascript fails to execute in headless Firefox

Question: I've setup a Ubuntu Server install with Firefox 3.6.22 and installed a headless test environment using the headless and watir-webdriver Ruby gems. When testing in desktop browser all seems to work but in the headless Firefox version the javascript just stops dead. Normal javascript pages work and load correctly, any idea what's happening?
Answer: Took a lot of debugging but it turns out that any console.log statements in your javascript will kill the headless firefox dead. Will investigate more to see if it's the old Ubuntu Firefox version or somewhere else in the chain.
Comment: `console.log` is only available as a built-in Firefox feature since 4.0: https://developer.mozilla.org/en-US/docs/DOM/console.log. Before that it was only provided by Firebug.


How were tuning/temperaments indicated on scores (if they ever were)?

Question: Bradley Lehman claims that the details of the intended tuning for the Well-Tempered Claivier are encoded in the squiggle at the top of the manuscript (related wikipedia link).
Are there other (claimed?) examples of common practice period manuscripts, or other documents that provide some  indications on how to tune the instrument?
(i.e. has someone found other similar cases?)
Alternately, have there been any papers that have research on how/where tuning indications were promulgated, but don't show anything similar to the squiggles approach?
(i.e. has someone looked and failed to find similar cases?)
Basically, I'm somewhat skeptical of the claims made at the link above, but would be more convinced if there were other cases where tuning indications were included on score, so that the WTC wasn't a unique case.
Comment: The link is dead...
Comment: The main link is slow, and may have a limit on the number of connections allowed, but it is alive.
Comment: I don't have a full answer, but I'm fairly certain I've seen similar squiggles in Bach manuscripts (most of which were probably made by Anna Magdalena) regardless of instrumentation. I've only heard it second-hand from the harpsichord professor at my college, but I think we already know or strongly suspect that Bach was using Werckmeister III or something very close to it.
Answer: "Are there other examples of common practice period manuscripts, or other documents that provide some indications on how to tune the instrument?"
I think you're mostly looking for examples of scores/manuscripts, but as far as "other documents" go, there are certainly period treatises that describe various temperaments. One such example is "Lettre touchant le cycle harmonique" ("Letter concerning the harmonic cycle") by Christiaan Huygens in 1691, which describes a 31-tone temperament, and contrasts it with what was called temperament ordinaire (the "ordinary temperament"). The later is described with sufficient mathematical rigor to correlate it to what we call quarter-comma meantone.
As a side note, there were also enharmonic keyboards that were invented during the Baroque, which have more than twelve pitches per octave (e.g. Nicola Vicentino's archicembalo). Inasmuch as these instruments use non-12-tone temperaments (and are often accompanied by a treatise describing how to tune them), any pieces written specifically for such an instrument could be considered a tacit indication of temperament.
As far as scores go, one of the earliest known pieces to specify an alternate tuning is the Renaissance chanson Seigneur Dieu ta pitié, written in 1558 by Guillaume Costeley (and inspired by Vicentino's archicembalo), which explicitly states that whole tones are to be divided into three equal parts, leading to 19-TET.


How to add js to H5P embed.php file?

Question: H5P module creates iframes and shows content in the iframe. I need to add a js file in the iframe, but I'm not able to do it.
In the documentation there is an example how to add js to h5p:
<code>/**
 * Add scripts to h5ps
 *
 * @param array $scripts
 *  Array of objects with properties path and version. Version is on the form
 *  ?ver=1.0.2 and is used as a cache buster
 * @param array $libraries
 *  Array of libraries indexed by the library's machineName and with an array
 *  as value. The value has the properties majorVersion and minorVersion
 * @param string $mode
 *  What mode are we in? Possible values are "editor", "div", "iframe" and "external"
 */
function hook_h5p_scripts_alter(&$scripts, $libraries, $mode) {
  if (isset($libraries['H5P.MultiChoice']) && $libraries['H5P.MultiChoice']['majorVersion'] == '1') {
    $scripts[] = (object) array(
      // Path relative to drupal root
      'path' => drupal_get_path('module', 'mymodule') . '/h5p-overrides.js',
      // Cache buster
      'version' => '?ver=1',
    );
  }
}
</code>
I have created a module, added that script in the .module file and created the overrides.js. But I am not able to get it working, the js file is not added.
What else should I add in the .module file than this script above?
Answer: You need to replace HOOK with your module name. As well as MYMODULE.

How to add js to H5P embed.php file?


Is the vector field conservative?

Question: $$\mathbf{v}=\left(\frac{-y}{x^2+y^2},\frac{x}{x^2+y^2},0\right)$$ is a vector field.
If we need to find $$\iint_{S}^{}(\nabla\times\mathbf{v})\cdot d\mathbf{a}$$ over a hemispherical surface placed on the $x$-$y$ plane centred at the origin, is it zero?
However if we use Stoke's theorem and calculate the line integral it gives a value $2\pi$. What's going on here?
Comment: This vector field is undefined at $(0,0,z)$.
Comment: Hmm... so that means 2π is the residue here? And so the vector field is not conservative then?
Comment: @Wojowu What do you mean by that? As I read it, the first two components of $v$ do not depend on $z$ and the third one vanishes. The first two components of its curl vanish and the third one $4xy/{({x^2}+{y^2})^2}$ does not depend on $z$ but does not vanish.
Comment: @Urgje At a point $(x,y,z)$ for which $x=y=0$ (so that the point is of the form $(0,0,z)$) the value vector field involves division by zero, hence isn't well-defined. Indeed, the components don't depend on $z$, but aren't defined for $x=y=0$.
Comment: @Wojowu That is true but it seems there are proper limits.
Comment: @Urgje There aren't. Taking e.g. $x=y$ there is no limit as $x,y\rightarrow 0$.
Comment: @Wojowu Yes, I am convinced.
Answer: Even though $\nabla\times\mathbf{v}=\mathbf{0}$, the domain of the field $\mathbf{v}$ is $D = \mathbb{R}^3 \setminus \left\{(0,0,z) ~|~ z \in \mathbb{R}\right\}$, i.e. $\mathbb{R}^3$ minus the $z$-axis. $D$ is not a simply connected region: for example, the boundary for your hemisphere surrounds the $z$-axis and cannot be continuously shrunk to a point while remaining in $D$. For any closed curve $X$ in $D$ which can be so shrunk, we have $\displaystyle\oint_X\mathbf{v}\cdot d\mathbf{r} = 0$
Comment: Thanks! So, anyways just for the sake of result verification, in this case the surface integral of the curl is 2π then?
Comment: @Dirac93: I don't know, I'm afraid! If Stokes' theorem applied, the equivalent line integral indeed gives $2\pi$, but for Stokes' theorem to apply $\mathbf{v}$ needs to be a continuous vector field with continuous first partial derivatives over a region in $\mathbb{R}^3$ which contains your hemisphere $S$. My grasp of continuity bad enough to keep me from speculating on what's going on near the $z$-axis. I don't know how to treat the surface integral in that region from basic principles.
Comment: Since the field spikes at the origin, can't we employ a Dirac delta function? So if we have the surface integral of a two dimensional dirac delta, we have a constant times 1 which here should be 2π. And hence, Stoke's theorem remains valid.

Is the vector field conservative?


Closedness and going up property

Question: Let $f: A\rightarrow B$ be a homomorphism of commutative unital rings. The problem is to show that if $f$ has going-up property and $\text{Spec }B$ is Noetherian topological space then $f^*: \text{Spec }B \rightarrow \text{Spec }A$ is a closed map. (Atiyah and Macdonald, Introduction to Commutative Algebra, Chapter 6, Exercise 11)
According to the Exercise 5.10 of Atiyah, going-up is equivalent to the following condition. For any prime $\mathfrak{q}\subset B, f^*(V(\mathfrak{q})) = V(\mathfrak{p})$, where $\mathfrak{p} = \mathfrak{q}^c$.
I was thinking of the following. Let $Z$ be the set of all closed subsets of $\text{Spec }B$ the image of which under $f^*$ is not closed. Then the set $Z$ has the minimal elements, because $\text{Spec }B$ is Noetherian. However I do not see any way out here.
Conversely, let $K$ be the set of all closed subsets of $\text{Spec }B$ the image of which under $f^*$ is closed. The set $K$ is non-empty because $f^*(V(\mathfrak{q})) = V(\mathfrak{p})$ for any prime $\mathfrak{q}$. The set $K$ has minimal elements, too. Suppose for some ideal $I$, the corresponding closed set $V(I)$ is minimal in $K$, it means that for any ideal $J$, such that $V(J)\subset V(I)$ the $f^*(V(J))$ is not closed. However, $I\subset \mathfrak{m}$ for some maximal ideal $\mathfrak{m}$ in $B$. Then $V(\mathfrak{m})\subset  V(I)$, it follows that $f^*(V(\mathfrak{m}))$ is not closed, a contradiction. Therefore the minimal elements of $K$ are of the form $V(\mathfrak{m})$. However, after this I do not see the way out of here, too.
Any help is appreciated.
Answer: Let $V(I) \subseteq \text{Spec}(B)$ be a closed set. Since $\text{Spec}(B)$ is a Noetherian space, $V(I)$ is a finite union of irreducible closed sets, necessarily of the form $V(q_i)$, where $q_i \in \text{Spec}(B)$. Then
$$f^*(V(I)) = f^*(\bigcup_{i=1}^n V(q_i)) = \bigcup_{i=1}^n f^*(V(q_i)) = \bigcup_{i=1}^n V(q_i^c)$$ is a finite union of closed sets, hence is closed.
Comment: [Lemma 10.40.6](http://stacks.math.columbia.edu/tag/00HU) shows that the noetherian condition is superfluous.
Comment: @user26857: That's interesting, and good to know. The proof that I gave is probably what Atiyah-MacDonald expected for this problem though

Closedness and going up property


Jquery contains is not working

Question: I need only jquery solutions, I have a span Text goes her like this, why this contains is not working in jquery, it will alert all span including bold, please help
$('#contentarea').bind('click',function(e){
                if($(e.target).is('span')){
                    if($(e.target).find('span:contains("italic")')){
                        alert('italic');
                    }
                }
        });

Comment: read the doc, :contains is for content not attribute
Comment: ok that is fine, but i am getting the same error, yesterday i asked the same question but the replied answers are not satisfying my need, if you knows that please feel free give me a possible solution, i am new in jquery
Answer: :contains looks for the elements containing the specified text, not the css properties
You need to
$('#contentarea').bind('click',function(e){
    var $target = $(e.target);
    if($target.is('span')){
        if($target.css('font-style') == 'italic'){
            alert('italic');
        }
    }
});

Comment: did you mean font-style?
Comment: @pebbo sorry copy paster mistake

Jquery contains is not working


Bash getopts option with another

Question: My current Bash script looks like in the following. So far it's working except I have no idea how to make it so the two options -f and -o work together:

the -o FILE option to display the most relevant information
in a file passed as an argument (if the file does not exist an error message must be displayed)
the option -f KEYWORD to display the lines containing the KEYWORD to
from a file. This option must be used with the -o option

Thank you for any input
<code>    #!/bin/bash
    function s_func()
{

filename="$1";

echo "when you're done saving information please write 'exit'"
        script $filename.txt

}
function o_func()
{

filename="$1"
dest='/home/eya/'

if [ -f "$filename".txt ]; then
cat $filename.txt
else echo "file does not exist"
fi
}

function f_func()
{
keyword="$1"
filename="$2"
grep $keyword $filename.txt
}
    while getopts ":s:o:f:" opt; do
        case $opt in
            s) s_func  "$OPTARG";;
            o) o_func  "$OPTARG";;
            f) f_func  "$OPTARG";;
            \?)echo "wrong option";exit 1;;
        esac
        done
    shift $((OPTIND -1))
</code>
Comment: Haven't you posted this code (I wouldn't say "asked this question", because this is more of a code dump than a question in its current state) before in the past?
Comment: Please try to make your code into a [mre] -- the _shortest possible thing_ that demonstrates a _specific problem_ when run without changes. (Both expected and actual output, likewise, should be shown in the question itself).
Comment: BTW, note how you're using `filename` in one place, and `file` in the other? If you make `f_func` write to a global variable (and all variables are global in bash by default), and `s_func` _read from_ that global variable... well, there you are (as long as they're used in the intended order).
Answer: Try this: while processing commnand line options, just collect variables.
Only do things with those variables after the options are parsed.
<code>declare f_arg o_arg s_arg

while getopts ":s:o:f:" opt; do
    case $opt in
        s) s_arg=$OPTARG ;;
        o) o_arg=$OPTARG ;;
        f) f_arg=$OPTARG ;;
    esac
done
shift $((OPTIND -1))

if [[ -z $o_arg ]] || [[ -z $f_arg ]] || [[ -z $s_arg ]]; then
    echo "ERROR: Options -s, -o and -f are required." >&2
    exit 1
fi

# Now you can do stuff in a specific order.
o_func "$o_arg"
f_func "$f_arg"
s_func "$s_arg"
</code>
Comment: thank you so much but I have a small problem how do I make it so the -f option only does the search with the keyword while the -o option is the one that does the displaying cause right now when I use them together it displays the whole file and then it displays what I searched for
Comment: I don't understand what you mean. Is doing `cat $filename` in the "o" func a problem?
Comment: the output  of ./ex.sh -f keyword -o file should only show the lines with the keyword however when now it displays the whole document then the lines with the keyword "the option -f KEYWORD to display the lines containing the KEYWORD to from a file. This option must be used with the -o option" thank you again for your time
Comment: Well, that behaviour is up to you, the programmer. I don't know what you're asking me to do for you.

Bash getopts option with another


Dúvida SQL Server 2012 - Query

Question: Estou com uma dificuldade. Na consulta abaixo, está trazendo dessa forma.

Tarefa_Inclusao      Tarefa
167909               167920

SELECT TarIDInclusao [Tarefa_Inclusao],tarid [Tarefa] FROM Tarefa WHERE TarID = 167920.

Nessa consulta é outra tarefa.  O que eu quero é o seguinte: Quero que na consulta acima, realizar uma manipulação para que o campo tarefa_inclusao em vez de vir 167909, venha 167907 igual da consulta abaixo.

Tarefa_Inclusao      Tarefa
167907               167909

SELECT TarIDInclusao [Tarefa_Inclusao],tarid [Tarefa] FROM Tarefa WHERE TarID = 167909

Comment: Isso mesmo @Sorack. É assim: A tarefa mãe é essa: 167907, as outras como 167909,167920 são filhas, ou seja, o campo tarefa_inclusao das filhas é justamente a tarefa mãe que no caso é a 167907.
Comment: Você quer a tarefa "mãe" de todas a partir da que você colocou no `WHERE`. É isso? A tarefa primordial possui o que na coluna `tarefa_inclusao`?
Answer: Utilize uma busca recursiva para encontrar o registro primordial para a tarefa desejada:
WITH historico AS (
  SELECT t.taridinclusao AS tarefa_inclusao,
         t.tarid AS tarefa,
         1 AS nivel
    FROM tarefa t
   WHERE t.tarid = 167920
   UNION ALL
  SELECT t.taridinclusao AS tarefa_inclusao,
         h.tarid AS tarefa, -- Pega do historico para garantir que o primeiro valor será mostrado
         h.nivel + 1 AS nivel
    FROM historico h
         INNER JOIN tarefa t ON t.tarid = h.taridinclusao
   WHERE h.taridinclusao IS NOT NULL
)
SELECT TOP(1) h.*
  FROM historico h
 ORDER BY h.nivel DESC
OPTION(MAXRECURSION 0);

O primeiro SELECT dentro do WITH irá definir a ancoragem dos registros, ou seja, o registro da qual partiremos, neste caso a tarefa da qual temos o número. Após isso, iremos sempre referenciar a própria historico para verificar o registro taridinclusao referente a ele.

WITH
Uma CTE (expressão de tabela comum) fornece a significativa vantagem de ser capaz de se autorreferenciar, criando, portanto uma CTE recursiva. Uma CTE recursiva é aquela em que uma CTE inicial é executada repetidamente para retornar subconjuntos de dados até que o resultado completo seja obtido.
Comment: tu é fera demais. Muitissimo obg pela sua ajuda. Abraços.
Comment: Peguei essa sua consulta e veio dessa forma
Tarefa_Inclusao     Tarefa          Nivel
Null                          167907         3

Porém, era para vir dessa forma

Tarefa_Inclusao     Tarefa          Nivel
167907                  167920           3
Comment: @RenanBessa por isso perguntei como estava o último registro no meu comentário na sua pergunta. Vou editar para corresponder a esta nova informação.
Comment: @RenanBessa alterado. Verifique por favor.
Comment: ainda veio da mesma forma.
Tarefa_Inclusao     Tarefa
167909                    167920

Era para vir:

Tarefa_Inclusao     Tarefa
167907                   167920
Comment: @RenanBessa corrigido
Comment: O responsável pelo `downvote` pode explicitar o que está incorreto na resposta? Apenas o `downvote` sem explicação acaba sendo inútil.

Dúvida SQL Server 2012 - Query


Simple MLE Question

Question: Let $X_1, X_2...X_n$ be iid with $f(x,\theta)=\dfrac{2x}{\theta^2}$ and $0<x\leq\theta$.
Find $c$ such that $\mathbb{E}(c\hat{\theta})=\theta$ where $\hat{\theta}$ denotes MLE of $\theta$.
What I have tried:
I found the MLE of $f(x;\theta)$ to be $\max\{X_1,X_2\cdots X_n\}$ (which aligns with the answer at the back) but now I am stuck at this question.
The answer given is $\dfrac{2n+1}{2n}$.
I would have proceeded as:
$$\begin{align*}
\mathbb{E}(c\hat{\theta})&=\theta\\
\int_0^\theta c \dfrac{2x}{y^2} &=\theta \quad (y = \max\{x_1,x_2,\cdots,x_n\})\\
\dfrac{1}{y^2}\int_0^\theta c .{2x}{} &=\theta
\end{align*}$$
But continuing this way gives me an answer far off from the one in the book (I don't have a term of n to begin with).
Comment: @Max Working on your hint $Y \leq y$ implies that each $X_i\leq y$ but how do I use this in my problem? I understand that my expectation is taken over $\hat{\theta}$ and thus, we must use its distribution. Now that brings up 2 questions in my head: 1. Is it different from the distribution of $X_i$? The answer seems to be no (although I am not completely sure why). 2. If it's different, then what is it?
Comment: So,$$P(\max \{X_i\}<y)=P(X_1<y,X_2<y,...,X_n<y) = \prod_{i=1}^n P(X_i<y)$$
$$=(\int_0^y\dfrac{2x}{\theta^2})^n=\dfrac{y^{2n}}{\theta^{2n}}$$
Comment: $$f(y) = \dfrac{2n.y^{2n-1}}{\theta^{2n}}$$
$$E(c\hat{\theta}) = \int_0^\theta\dfrac{c\cdot2n.y^{2n}dy}{\theta^{2n}}=\dfrac{c\cdot 2n}{\theta^{2n}}\times\dfrac{\theta^{2n+1}}{2n+1}=\theta$$
$$c = \dfrac{2n+1}{2n}$$
Awesome! Thanks! I'll mark the existing answer as the solution.
Comment: @Max Actually, an easier calculation would be $$E[\hat{\theta}] = E[\max X_i] = \int_0^{\theta} 1 - \left(\frac{y}{\theta}\right)^{2n}\,\mathrm dy = \theta\left(1-\frac{1}{2n+1}\right)$$ giving $c = \frac{2n+1}{2n}$
Comment: You can't find the expected value of the MLE (hence, you can't correct the bias) without knowing the distribution of the MLE. It is related to order statistics as suggested below, but you don't need to be familiar with order statistics to solve this problem. If $Y=\textrm{max}\left\{X_1,X_2,\ldots,X_n\right\}$, what is the CDF of $Y$, $F_Y(y)=P(Y\leq y)$? Hint: If $Y\leq y$, what does that say about each of the $X_i$?
Comment: The distribution of $Y$ is different from the distribution of each of the $X_i$. I'll take the hint a step further. I hope that's alright. If $Y\leq y$, then each of the $X_i$ are also at most $y$, as you've stated. Turn that into a probability statement: $P(Y\leq y)=P(X_1\leq y, X_2\leq y,\ldots, X_n\leq y)$. Are you able to explicitly compute that probability in terms of $\theta$?
Comment: Exactly. Now you have the CDF of the maximum value of the sample. How can you use that to compute the expected value of the maximum value of the sample? Hint: The derivative, with respect to $y$, of the CDF will produce the PDF.
Comment: @DilipSarwate That is a nice, simple solution. Unfortunately, my approach to problems like these has become so burnt into my memory that I don't even consider other options. I found a way that worked for me and stuck with it throughout my coursework. You're integrating the survival function because $E[Z]=\int_{0}^{\infty}P(Z\geq z)dz$ so long as $Z$ is a positive random variable.
Answer: What's the distribution of the largest observation from a sample of size $n$ with distribution F?
You want a special case of the formula for $f_{X_k}(X)$ where $k=n$ (which formula should be obvious in any case):
http://en.wikipedia.org/wiki/Order_statistic#The_joint_distribution_of_the_order_statistics_of_an_absolutely_continuous_distribution
Comment: We haven't covered Order Statistics yet, any way to do without that?
Comment: Yes, as the answer pretty much implies ("should be obvious in any case"), you can work it out yourself from first principles, using simple probability arguments. The probability that the largest value of a sample of $n$ is $\leq x$ is the probability that all $n$ observations are $\leq x$. Write that probability down (a power of a cdf at $x$), take derivates w.r.t $x$ to find the density. Then take expectations. to get $c$. (Though there are other ways to go about it, they're all going to involve some effort.)

Simple MLE Question


Alert() with dynamic content javascript

Question: What is wrong with alert({s[prop]}) but fine with this placeholder={s[prop]}
It says I am missing a ',' after 's' and ':' after ']'
Comment: If your post is missing a tag, please edit it and include the tag.
Comment: Is this part React/JSX? `placeholder={s[prop]}`
Comment: s is an object with many properties
Comment: Oh yes soz it is
Answer: In React, the { }s around attributes are essentially expression delimiters - they indicate that what follows between the brackets is an expression. So, if you have const str = 'foobar', then:
placeholder={str}

evaluates to
placeholder='foobar'

But, in alert, you're not writing JSX - you're writing plain JS. When in an expression context, { indicates the start of an object literal. But the following is not a valid object literal:
const obj = {
  s[prop]
}

because objects require keys and values (usually). Perhaps you wanted to do
alert(s[prop])

The only time an object literal doesn't require a value is when you're using the shorthand syntax, when you have a variable in the current scope and want to define an object with a property with the same name as the variable, and the same value as a variable, eg:
const str = 'foobar';
const obj = { str };

This results in an object like { str: 'foobar' }.
In any other situation, you'll need to define the property name in addition to the value, eg
{ somePropertyName: s[prop] }

Answer:
alert(s['use your key'])

Please use in this way. Avoid using {} in alert(), If you use you will see [object Object] instead of actual dynamic content.
Answer: try with
alert(s[prop])

In JSX to print any JS variable it must be wrap inside curly braces, but not required when using in JS, alert is the JavaScript function.

Alert() with dynamic content javascript


Modify url withut changing the code

Question: I want to change my current url to a modified one.
Suppose my current url is
www.abc.com/xyz/location.htm

I want it to change to
www.abc.com/location.htm

please suggest a suitable way....
Thanks in advance
Comment: What web server are you using? Apache?
Comment: Yes ... M using apache server
Answer: If you are running Apache servers, I'd suggest using mod_rewrite.
In that case you should have something like this in your .htaccess -file at the top level of your server root:
RewriteEngine on
RewriteRule  ^abc.com/xyz/(.*)$  <your_root_directory>/$1

Comment: here  refers to where my application is present in tomcat??
Comment: It's the URL to the root of your application, so if you want to remove xyz, it should be enough just to remove the your directory part altogether.  Also I am not sure if you need the host part (^abc.com) either if you use .htaccess at the top of your web application.
Comment: Can you please elaborate...... m not understanding much as m just started using Apache server..
Comment: @neeraj: Your comment above appears to suggest that you may be using "tomcat". Just to clarify, are you using "Apache Webserver" or "Apache Tomcat"? They are 2 very different things.
Comment: My war file is deployed in  apache tomcat....n i m access it using Apache Webserver.
Hence instead of giving localhost:8080 to open the application m using only localhost.

Modify url withut changing the code


Translate a list of time punches into time worked by hour in C#

Question: I have a List objects that detail clock punches for workers that looks like this:
Person  Time     Action
Cindy   07:00    clockin
Jim     08:12    clockin
Cindy   11:15    startlunch
Cindy   12:12    endlunch
Jim     12:30    startlunch
Jim     12:55    endlunch
Cindy   15:30    clockout
Jim     17:00    clockout

Of course the real data is hundreds of people and it is broken out by department, etc.
They want me to to create a report that shows how much labor is worked for each hour in the day. The end result Should look like this:
Time   Worked
7-8      1
8-9      1.8
9-10     2
10-11    2
11-12    1.25
12-1     1.3
etc.

As an interum step, I have converted the series of punches to a List of WorkRecords and it looks like this:
Person     In      Out
Cindy      07:00  11:15
Jim        08:22  12:30
Cindy      12:12  15:30
Jim        12:55  17:00

I was thinking about looping through all the hours and testing each WorkRecord if it includes time with in a given hour, but that seems cumbersome.
Is there a more elegant way to reorganize my data into my final product using lambda or linq expressions?  It could start with the original data or the interum.  Thank you for look into this puzzle.
Answer: Here is my attempt with LINQ.
I assume that your WorkRecord is something like this.
    public  class WorkRecord
    {
        public readonly String name;
        public readonly DateTime StarTime;
        public readonly DateTime EndTime;

        public WorkRecord(string name, DateTime starTime, DateTime endTime)
        {
            this.name = name;
            StarTime = starTime;
            EndTime = endTime;
        }

        public WorkRecord(string name, string starTime, string endTime)
        {
            this.name = name;
            StarTime = DateTime.ParseExact(starTime, "HH:mm", null);
            EndTime = DateTime.ParseExact(endTime, "HH:mm", null);
        }
    }

It is not clear if they are already pre-filtered for single day or not. I'll try to cover both cases (but still simplistic)
    public  class DayStats
    {
        public readonly int[] TotalMinutes = new int[24];

        public void AddWorkRecord(WorkRecord record)
        {
            // Note: this method doesn't handle case when EndTime is next day
            // handle "middle" hours, they are all full
            for (int hour = record.StarTime.Hour + 1; hour < record.EndTime.Hour; hour++)
            {
                TotalMinutes[hour] += 60;
            }
            // handle first and last hours that might be not full
            if (record.StarTime.Hour == record.EndTime.Hour)
            {
                TotalMinutes[record.StarTime.Hour] += record.EndTime.Minute - record.StarTime.Minute;
            }
            else
            {
                TotalMinutes[record.StarTime.Hour] += 60 - record.StarTime.Minute;
                TotalMinutes[record.EndTime.Hour] += record.EndTime.Minute;
            }
        }

        public string AsPrettyString()
        {
            return string.Join("\n", TotalMinutes
                .Select((totalMinutes, hour) => string.Format("{0}-{1} {2}", hour, hour + 1, totalMinutes)));
        }
    }

    public class TimeCardAggregate
    {
        private readonly Dictionary<DateTime, DayStats> _days = new Dictionary<DateTime, DayStats>();

        public void AddWorkRecord(WorkRecord record)
        {
            // Note: this method doesn't handle case when EndTime is next day
            var date = record.StarTime.Date;
            DayStats dayStats;
            if (!_days.TryGetValue(date, out dayStats))
            {
                dayStats = new DayStats();
                _days.Add(date, dayStats);
            }
            dayStats.AddWorkRecord(record);
        }

        public List<KeyValuePair<DateTime, DayStats>> GetTimecard()
        {
            return _days.ToList().OrderBy(kv => kv.Key).ToList();
        }
    }

DayStats represents aggregated result for single day. TimeCardAggregate is result for several days. Most of the work is done by helper methods AddWorkRecord in both classes which you can use from Aggregate LINQ method. See how you can use them:
    static void Main(string[] args)
    {
        List<WorkRecord> records = new List<WorkRecord>
        {
            new WorkRecord("Cindy", "07:00", "11:15"),
            new WorkRecord("Jim", "08:22", "12:30"),
            new WorkRecord("Jim", "12:12", "15:30"),
            new WorkRecord("Cindy", "12:55", "17:00")
        };

        var dayStats = records.Aggregate(new DayStats(), (ds, wr) =>
        {
            ds.AddWorkRecord(wr);
            return ds;
        });

        Console.WriteLine(dayStats.AsPrettyString());

        List<WorkRecord> recordsForTwoDays = new List<WorkRecord>();
        recordsForTwoDays.AddRange(records);
        // just copy the data for the next day
        recordsForTwoDays.AddRange(records.Select(wr => new WorkRecord(wr.name, wr.StarTime.AddDays(1), wr.StarTime.AddDays(1))));
        var timecard = recordsForTwoDays.Aggregate(new TimeCardAggregate(), (ds, wr) =>
        {
            ds.AddWorkRecord(wr);
            return ds;
        });
        Console.WriteLine("\n\n");

        Console.WriteLine(string.Join("\n-------------\n", timecard.GetTimecard().Select(kv =>
        {
            return kv.Key.ToShortDateString() + ":\n" + dayStats.AsPrettyString();
        })));
    }

Note also, that both implementations of AddWorkRecord are naive and don't handle the case when someone worked over night and have a record spawning over several days. It is not very hard to fix though.


Como exibir os valores de entrada da matriz sem [' ']

Question: Eu fiz uma matriz com 12 elementos que possui 4 linhas e colunas e queria que elas fossem exibidas assim sem [' '] em forma de lista, mas eu não quero que a saída seja exibida assim:
Lembrando: Deve funciona com números floats negativos e floats positivos digitados
Entrada:
02 04 06
08 10 12
14 16 18
20 22 24

Saída esperada:
02 04 06
08 10 12
14 16 18
20 22 24

Mas a saída está assim:
['02', '04', '06']
['08', '10', '12']
['14', '16', '18']
['20', '22', '24']

Meu código:
mt1 = input().split()
mt2 = input().split()
mt3 = input().split()
mt4 = input().split()

print (mt1)
print (mt2)
print (mt3)
print (mt4)

Comment: Por onde você está estudando Python? A frequência de perguntas me parece um pouco anormal.
Comment: Aleatoriamente (mas o problema maior é matriz)
Comment: Dá para fazer com dois for, dps eu vou mandar uma versão.
Answer: Há várias formas de fazer isso, como pode ser visto nas demais respostas. Vou deixar uma solução que, ao meu ver, é bastante elegante.
Você já deve ter percebido que a função print pode receber diversos parâmetros, resultando em printar cada um dos parâmetros separados por um espaço.
print('sem', 'tempo,', 'irmão') => printa "sem tempo, irmão"

Através do asterísco (que é o operador de unpack), o Python permite usar os valores de uma lista como argumentos de uma função.
argumentos = ['sem', 'tempo,', 'irmão']
print(*argumentos) => printa "sem tempo, irmão"

Sabendo isso, você pode usar a mesma técnica no seu código.
print(*mt1)
print(*mt2)
print(*mt3)
print(*mt4)

O resultado vai ser o que você deseja.
Caso você queira colocar outro separador que não seja um espaço, basta informar no parâmetro nomeado sep.
print(*mt1, sep=' - ')

Leitura adicional:

https://docs.python.org/3/library/functions.html#print
https://medium.com/rafaeltardivo/python-entendendo-o-uso-de-args-e-kwargs-em-fun%C3%A7%C3%B5es-e-m%C3%A9todos-c8c2810e9dc8
Answer: Você pode usar o método .join() de string. O uso é
# STRING.join(LISTA)
# Exemplo:
print( ".".join(['192', '168', '0', '1']))
# result: 192.168.0.1

Mas no seu caso, apenas coloque ele nas linhas do print:
mt1 = input().split()
mt2 = input().split()
mt3 = input().split()
mt4 = input().split()

print (' '.join(mt1))
print (' '.join(mt2))
print (' '.join(mt3))
print (' '.join(mt4))

Comment: Eu tinha visto o método **join** por auto, deu certo obrigado.
Comment: Isso funciona com números floats negativos e floats positivos?
Comment: Só funciona se for uma lista de strings. Do contrário ele retorna um erro. Você deve converter antes para string com `str(3.14)`
Answer: bom, eu não recomendaria fazer assim mas posso ajudar.
mt1 = input().split()
mt2 = input().split()
mt3 = input().split()
mt4 = input().split() # a função split retorna uma lista, mesmo que contendo apenas um elemento

matriz = [mt1,mt2, mt3, mt4] # já que você está trabalhando com lista junte tudo numa lista apenas

for i in range(len(matriz)): # para varrer as linhas da matriz
    for j in range(len(matriz[i])): # para varrer todos os elementos da linha ou seja as colunas.
        print (matriz[i][j], end = "\t") # printa o elemento da linha um ao lado do outro
    print() # dá espaço para uma nova linha.

lembrando que essa não é a melhor solução você poderia usar uma lista encadeada, ou algo do tipo.
Comment: Desse jeito pude entender melhor, obrigado Filipe.


If a family of sets $C$ is a subset of a $σ$-algebra $F$, then are the subsets of $C$ in the $σ$-algebra as well?

Question: Recently I asked this question
If a set is in a σ-algebra, then are the subsets in the σ-algebra as well?
involving a set in F rather than a family of sets.
Now the question is
Let $A \subseteq F$ where $F$ is a σ-algebra. If $B \subseteq A$, is it true that $B \subseteq F$ ?
My answer would be that if $E \in B$ then $E \in A$ and therefore$E \in F$ $\forall E$. This means $B \subseteq F$.
So am I correct to assume that the claim is correct?
Comment: Yes, you are correct. You don't need $F$ to be a $\sigma$-algebra. It is always true that if $A \subseteq  F$ and $B \subseteq A$ then $B \subseteq F$. The proof is as you state it (and you have not used that $F$ is a $\sigma$-algebra).
Answer: Yes, you are correct. You don't need $F$ to be a $\sigma$-algebra. It is always true that if $A \subseteq  F$ and $B \subseteq A$ then $B \subseteq F$. The proof is as you state it (and you have not used that $F$ is a $\sigma$-algebra).
Comment: Yes F in both cases is a set. In the case of $\sigma - algebra$ its elements are just sets by themselves so only the type of elements changes, which doesn't change the property.