Pass in version number when building in sbt

Question: I have a semi-complicated SBT process because I need to conditionally include a different config file based on what kind of build is needed. I solved this problem through sub-projects:
lazy val app = project
    .in(file("."))
    .enablePlugins(JavaAppPackaging)
    .settings(
      commonSettings // Seq() of settings to be shared between projects
      ,sourceGenerators in Compile += (avroScalaGenerateSpecific in Compile).taskValue
      ,(avroSpecificSourceDirectory in Compile) := new java.io.File("src/main/resources/com/coolCompany/folderName/avro")
    )

lazy val localPackage = project
    .in(file("build/local"))
    .enablePlugins(JavaAppPackaging)
    .settings(
      organization := "com.coolCompany",
      version := "0.1.0-SNAPSHOT",
      scalaVersion := "2.11.8",
      name := "my-neat-project",
      scalacOptions := compilerOptions, //Seq() of compiler flags
      sourceDirectory in Compile := (sourceDirectory in (app, Compile)).value,
      mappings in Universal += {
        ((sourceDirectory in Compile).value / "../../conf/local/config.properties") -> "lib/config.properties"
      }
    )
    .dependsOn(app)

val buildNumber = inputKey[String]("The version number of the artifact.")

lazy val deployedPackage = project
    .in(file("build/deployed"))
    .enablePlugins(JavaAppPackaging)
    .settings(
      organization := "com.coolCompany",
      buildNumber := {
        val args : Seq[String] = spaceDelimited("<arg>").parsed
        println(s"Input version number is ${args.head}")
        args.head
      },
      version := buildNumber.inputTaskValue + "-SNAPSHOT", //"0.1.0-SNAPSHOT",
      scalaVersion := "2.11.8",
      name := "my-cool-project",
      scalacOptions := compilerOptions,
      sourceDirectory in Compile := (sourceDirectory in (app, Compile)).value,
      mappings in Universal += {
        ((sourceDirectory in Compile).value / "../../conf/deployed/config.properties") -> "lib/config.properties"
      }
    )
    .dependsOn(app)

Now I need to allow the version number to be passed in by a build tool when building. You can see what I've attempted to do already: I created an inputKey task called buildNumber, then tried to access that in the version := definition. I can run the buildNumber task itself just fine:
$ sbt 'deployedPackage/buildNumber 0.1.2'
Input version number is 0.1.2

So I can at least verify that my input task works as expected. The issue is that I can't figure out how I actually get to that input value when running the actual packageBin step that I want.
I've tried the following:
$ sbt 'deployedPackage/universal:packageBin 0.1.2'
[error] Expected key
[error] Expected '::'
[error] Expected end of input.
[error] deployedPackage/universal:packageBin 0.1.2

So it clearly doesn't understand what to do with the version number. I've tried a bunch of different input variations, such as [...]packageBin buildNumber::0.1.2, [...]packageBin -- buildNumber 0.1.2, or [...]packageBin -- 0.1.2, and all of them give that error or something similar indicating it doesn't understand what I'm trying to pass in.
Now, ultimately, these errors make sense. buildNumber, the task, is what knows what to do with the command line values, but packageBin does not. How do I set up this task or these set of tasks to allow the version number to be passed in?
I have seen this question but the answers link to an sbt plugin that seems to do about 100 more things than I want it to do, including quite a few that I would need to find a way to explicitly disable. I only want the version number to be able to be passed in & used in the artifact.
Edit/Update: I resolved this issue by switching back to Maven.
Answer:
I think you're a bit confused about the way sbt settings work. Settings are set when sbt loads and then cannot be changed until you reload the session. So whatever you set version to, it will be fixed, it cannot be dynamic and depend on user input or a task (which on the contrast is dynamic and is evaluated every time you call it).

This is true. However you can still compute a SettingKey value in the first place. We use environment variables to set our build version.
version := "1." + sys.env.getOrElse("BUILD_NUMBER", "0-SNAPSHOT")

Explanation

1. is the major version. Increment this manually as you like
BUILD_NUMBER is an environment variable that is typically set by a CI, e.g. Jenkins. If not set, use 0-SNAPSHOT as a version suffix.

We use this in our company for our continuous deployment pipeline.
Hope that helps,
Muki
Comment: If you are using git flow it is useful to use `https://github.com/sbt/sbt-release` or `https://github.com/sritchie/sbt-gitflow` too
Answer: I think you're a bit confused about the way sbt settings work. Settings are set when sbt loads and then cannot be changed until you reload the session. So whatever you set version to, it will be fixed, it cannot be dynamic and depend on user input or a task (which on the contrast is dynamic and is evaluated every time you call it).
You have an input task buildNumber which depends on user input and is evaluated every time you call it:
> show buildNumber 123
Input version number is 123
[info] 123
[success] Total time: 0 s, completed Dec 24, 2017 3:41:43 PM
> show buildNumber 456
Input version number is 456
[info] 456
[success] Total time: 0 s, completed Dec 24, 2017 3:41:45 PM

It returns whatever you give it and doesn't do anything (besides println). More importantly, it doesn't affect version setting anyhow (and couldn't even in theory).
When you use buildNumber.inputTaskValue, you refer to the input task itself, not its value (which is unknown because it depends on the user input). You can see it by checking the version setting value:
> show version
[info] sbt.InputTask@6c996907-SNAPSHOT

So it's definitely not what you want.

I suggest you to review your approach in general and read a bit more sbt docs, for example about Task graph (and the whole Getting started chapter).
If you still really need to set version on sbt load according to your input, you can do it with a command. It would look like this:
commands += Command.single("pkg") { (state0, buildNumber) =>
  val state1 = Project.extract(state0).append(Seq(version := buildNumber + "-SNAPSHOT"), state0)
  val (state2, result) = Project.extract(state1).runTask(packageBin in (deployedPackage, universal), state1)
  state2
}

But you should be really careful dealing with the state manually. Again, I recommend you to review your approach and change it to a more sbt-idiomatic one.
Comment: I'm not surprised I'm doing it wrong. Is there a starting point for this kind of thing? I'm surprised at how few resources I can find for what I thought would be an extremely common use case.
Comment: I've linked sbt documentation in the answer. Unfortunately, there's not much else to read. You can also ask on the [Gitter channel](https://gitter.im/sbt/sbt) to solve some little issues.
Answer: I suggest you just set the version setting only for the project deployedPackage just before you call the task needing the version. This is the simplest way of setting the version, and as settings keys have scopes, this should work as intended.
I used something like this for a big multi module project, where one of the projects had a separate versioning history than the other projects.
Comment: I would reword this as an actual answer or post it as a comment. In it's current look this question is likely to be percieved as not an answer and would therefore be flagged accordingly.


Show that $\hat{\mu}$ has minimal variance

Question: So two independent analyses of a content in a water sample have been made using two different methods, both without systematical errors but with different standard deviations. Method $B$ is assumed to have twice the standard deviation as method $A$. $x_A$ and $x_B$ are the measured contents and $\mu$ is the real content.
By minimizing
$Q(\mu) = \lambda \left( \left( \frac{x_A - \mu}{\sigma_A} \right)^2 + \left( \frac{x_B-\mu}{\sigma_B} \right)^2 \right)$ and putting $\lambda = \sigma_A^2,$ I get $\hat{\mu} = \frac{4}{5}x_A + \frac{1}{5}x_B$.
The estimation is unbiased (I have been able to show that $E(\hat{\mu}) = \mu)$
Now I want to show that $\hat{\mu}$ has minimal variance compared to all other unbiased estimates that can be written on the form $a x_A + b x_B$, by minimizing $\mathrm{Var}(ax_A + bx_B)$ as $a+b=1$.
So I have
$\mathrm{Var}(ax_A + bx_B) = a^2 \mathrm{Var}(x_A) + b^2 \mathrm{Var}(x_B) = a^2 \sigma^2 + 4b^2 \sigma^2 + 2ab\mathrm{Cov}(x_A,x_B),$ which is minimized by differentiating and putting the derivative equal to zero.
Since the analyses are independent, I'm assuming the covariance is equal to zero. So to minimize I solve
$2a^2 \sigma + 8b^2 \sigma = 0$ and $a+b=1$ which gives me the solution $b = \frac{1}{5} \pm \frac{2}{5}i,$ and $ a = 1-b$.
So if I understand the problem correctly, I have almost reached the correct result, except there shouldn't be an imaginary part. Have I done something wrong (since my result is a complex number and I'm thinking it probably shouldn't be)?
Comment: and the most important point is that minimizing $a^2$ when $a$ is complex means nothing : minimizing $f(x)$ requires that $f$ ouputs its values in some well-ordered set : and the complex numbers are not order-able
Comment: Sorry, you are right. I have edited it and I'm hoping it's better now.
Comment: I don't see why minimizing $a^2 \sigma^2 + 4 (1-a)^2 \sigma^2$ subject to $0 \le a \le 1$ would give a complex optimum
Comment: Well, when solving the equation $2a^2 \sigma + 8(1-a)^2 \sigma = 0$ I get that $\sigma = 0$ or $10a^2 -16a + 8 = 0$ which in turn has complex solutions, no?
Comment: or if you minimize over complexes, the variance is $|a|^2$ not $a^2$ ! so minimize $|a|^2 \sigma^2 + 4 |1-a|^2 \sigma^2$ other $a \in \mathbb{C}$
Answer: You differentiated with respect to $\sigma$, but $\sigma$ is fixed; your variables are $a$ and $b$, subject to $a+b=1$.
So you need to differentiate $a^2\sigma^2+4b^2\sigma^2=a^2\sigma^2+4(1-a)^2\sigma^2=(5a^2-8a+4)\sigma^2$ with respect to $a$, yielding $10a-8=0$ and thus $a=\frac45$ as expected.
Answer: Much easier - don't substitute for $b$, simply use
    $$ \frac{\text{d}b}{\text{d} a} = -1$$
Then the answer is almost immediate.
Comment: Thanks  U-37238, that looks a lot better (it was latex was it, as below I can't check).

How do I get into source edit mode? Now I only see it in presentation mode.

Sorry I'm not making any effort to lift myself out of newbie level, I'm kind of tied up with work at the mo ....


Google Cloud gsutil instructions say update but there is no update command

Question:
On this page:

https://developers.google.com/storage/docs/gsutil_install?hl=ja#install

The gsutil install recommends, right after install, running

gsutil update

which returns

CommandException: Invalid command "update".

Am I just seeing incorrect documentation? Is there some other way to update?

Checking on 'usage' doesn't mention there being any update command:

Usage: gsutil [-d][-D] [-h header]... [-m] [command [opts...] args...] [-q]
Available commands:
  acl            Get, set, or change bucket and/or object ACLs
  cat            Concatenate object content to stdout
  compose        Concatenate a sequence of objects into a new composite object.
  config         Obtain credentials and create configuration file
  cors           Set a CORS XML document for one or more buckets
  cp             Copy files and objects
  defacl         Get, set, or change default ACL on buckets
  du             Display object size usage
  help           Get help about commands and topics
  lifecycle      Get or set lifecycle configuration for a bucket
  logging        Configure or retrieve logging on buckets
  ls             List providers, buckets, or objects
  mb             Make buckets
  mv             Move/rename objects and/or subdirectories
  notification   Configure object change notification
  perfdiag       Run performance diagnostic
  rb             Remove buckets
  rm             Remove objects
  setmeta        Set metadata on already uploaded objects
  stat           Display object status
  test           Run gsutil tests
  version        Print version info about gsutil
  versioning     Enable or suspend versioning for one or more buckets
  web            Set a main page and/or error page for one or more buckets

Additional help topics:
  acls           Working With Access Control Lists
  anon           Accessing Public Data Without Credentials
  crc32c         CRC32C and Installing crcmod
  creds          Credential Types Supporting Various Use Cases
  dev            Contributing Code to gsutil
  metadata       Working With Object Metadata
  naming         Object and Bucket Naming
  options        Top-Level Command-Line Options
  prod           Scripting Production Transfers
  projects       Working With Projects
  subdirs        How Subdirectories Work
  support        Google Cloud Storage Support
  versions       Object Versioning and Concurrency Control
  wildcards      Wildcard Names

Use gsutil help  for detailed help.

EDIT:

It is gsutil version 3.42
Comment: What platform are you running on? On CentOS 6, I have `gsutil` 3.42 and the `update` command is there. Alternatively, consider instead installing [Google Cloud SDK](https://developers.google.com/cloud/sdk/) which includes `gsutil` and other tools and then run `gcloud components update`.
Answer: Maybe you have a very old version?
Try gsutil version to see yours.
you can check release notes here:
https://github.com/GoogleCloudPlatform/gsutil/blob/master/CHANGES.md


ASP.net MVC - Authorize controller for one user/role but all users for one action

Question: I have a controller like this:
[Authorize(Users="Admin")]
public class MyController : Controller
{
    ...

    [AllowAnonymous]
    public AllUsersAction()
    {

    }
}

Except I actually do want to authorize AllUsersAction, only all authorized users should be able to hit it, not just Admin.
What to do?
EDIT: I know that I can authorize the whole controller and provide more restrictions for all actions that should only be available to Admin. But I'd rather not put attributes on every action but one.
The question could be better phrased: What would an implementation look like that would allow this 'minimalism' if it isn't currently possible?
Answer: Use Authorize attribute without any parameters for controller:
[Authorize]
public class MyController : Controller
{
    ...
    public AllUsersAction()
    {

    }

    [Authorize(Users="Admin")]
    public ActionResult OnlyForAdmin()
    {
    }

}

And specify Authorize attribute Roles/Users properties for restricted actions.
Unfortunately Authorize attribute on controller bypasses authorization only if action has AllowAnonymous attribute. Fortunately you can override OnAuthorization method of Authorize attribute to skip authorization check in controller Authorize attribute if action has its own Authorize attribute:
public class CustomAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if(filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
        {
            //skip authorization check if action has Authorize attribute
            return;
        }

        base.OnAuthorization(filterContext);
    }
}

You can use this CustomAuthorize in your example:
[CustomAuthorize(Users="Admin")]
public class MyController : Controller
{
    ...

    [Authorize]
    public AllUsersAction()
    {

    }
}

Comment: There is no ready solution in MVC for that. You can override Authorize attribute's OnAuthorization method to skip authoriztion if action has it own Authorize attribute. Check edits.
Comment: Right. I do understand that I can do that, but what I'm after is a way to do this with the least amount of code possible. I could also move my non-admin actions to another controller. Do you know if what I'm asking for can be done with the current infrastructure? If not, what might it look like to implement an improvement that would allow for what I want?
Comment: Thanks for the suggestion on an approach to approximate it!


opencv convexHull returns same point twice

Question: I am try to use convexHull to set the sequence of my points. But the result is just wrong.
<code>//image_points_queue.push_back(original_image_points);
vector<cv::Point2f> image_points = {
    { 585, 543 },
    { 643, 749 },
    { 767, 501 },
};

convexHull(image_points, image_points, false);
</code>
image_points comes to be "767, 501", "643, 749", "767, 501".
I don't have any idea about it . Please help.
Comment: Actually that is the only code I ran for test. And the only change I did to make it work is using another vector as result.
Comment: Can you provide a [mcve]? This works as expected for me (no duplicates, correct points). Probably you're doing something else in your code that provides wrong results.
Comment: Do you run the code in Linux? Please see my comment below. It went wrong in Windows.
Comment: I'm on Windows 8.1. I don't think it's platform dependent. You probably have some other code that messes up with this snippet.
Answer: I use another vector for the result and the code works just fine.
<code>vector<cv::Point2f> result_points;
vector<cv::Point2f> image_points = {
    { 585, 543 },
    { 643, 749 },
    { 767, 501 },
};

convexHull(image_points, result_points, false);
</code>
I am using Windows 10. Not sure whether it is platform dependent.
Answer: It basically gives a closed hull so the starting point and ending point would be same. so you need to ignore the last point of the hull.


JS function setting too many addEventListeners

Question: I have a single page app (SPA) with search functionality where I am trying to track how users interact with the search bar in Adobe Analytics. If I navigate to 5 different "pages" of my SPA, the following code will fire the event 6 times. Seems the addEventListener is being set but not cleared if no search happens on a "page". These eventListeners essentially get queued each time a "page" loads, and once a search is entered, they all fire at the same time, clearing the queue.
How can I clear the eventListeners if a search is NOT performed and only have this event fire once a search is performed via pressing enter?
Suppose I have the code:
clearInterval(interval);
var interval = setInterval(function(){
    if (document.querySelector("form div[data-autoid='search_bar'] input")) {
        inputField = document.querySelector("form div[data-autoid='search_bar'] input")
        inputField.addEventListener('keydown', searchEntered)
        clearInterval(interval);
    }
}, 500);

function searchEntered(e) {
    if (e.key == "Enter") {
      console.log("search entered");
      var event = new CustomEvent('searchEntered');
     dispatchEvent(event);
    }
}

Comment: What's happening with the intervals? This does not seem like a good solution to any use case.
Comment: `setEventListener()` does not remove event listeners that have already been added.
Comment: @ScottMarcus - intervals are listening for the search bar to exist, before setting the eventListener on it.
Comment: Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)
Answer: If you want remove an existing event listener, use EventTarget.removeEventListener().
As the MDN page states, you need to specify the same type and listener parameters that you passed to addEventListener(). If you passed options, also, you should also pass the same ones to removeEventListener():

Given an event listener previously added by calling addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(), but what about the options or useCapture parameters?
While addEventListener() will let you add the same listener more than once for the same type if the options are different, the only option removeEventListener() checks is the capture/useCapture flag. Its value must match for removeEventListener() to match, but the other values don't.

Note that is not possible to add multiple identical listeners to the same element. From MDN page:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener() method.
Answer: If you add the event listener to window it will capture all keydown events on the page (delegate target) once that happens make a check to see if it was triggered by the Enter key and if the parentNode has the attribute data-autoid='search_bar'.
If true dispatch your custom event.
This will continue to work even if the DOM changes

addEventListener('keydown', e => {
  if (e.key == 'Enter' && e.target.parentNode.dataset.autoid == 'search_bar') {
    console.log('search entered');
    const event = new CustomEvent('searchEntered');
    dispatchEvent(event);
  }
})

  Will trigger <input />

  Won't trigger <input />

Answer: var interval = setInterval(function(){
  var inputField = document.querySelector("form div[data-autoid='search_bar'] input");
  if (inputField && !inputField.dataset.searchEventAttached) {
    inputField.addEventListener('keydown', searchEntered);
    inputField.dataset.searchEventAttached = true;
  }
  clearInterval(interval);
}, 500);


Correlation between the j-feature and partial residual

Question: I am reading a book for the lasso-regression. However, I think that this is a more general question regarding the derivative of the OLS-term:

Can someone explain me why this $c_j$ term is measuring the correlation between $x_j$ and the partial residual. I cant see there the structure of the correlation Formula between them
Answer: Here is first attempt at an answer, as I have come across a similar intuition elsewhere:
In general correlation is defined as
$$\rho_{x,y} = \frac{\sum_i (x_i - \bar x)(y_i - \bar y)}{\sigma_x \sigma_y}$$
That is the covariance divided by a normalizing factor which makes the correlation unit-less
Since the denominator is always positive (standar deviations are positive) we can push them into the proportionality sign, hence the correlation is proportional to
$$ \rho_{x,y}\propto \sum_i (x_i - \bar x)(y_i - \bar y) = \sum_i (x_i - E[x])(y_i - E[y]) $$
Now in this case we have the term $c_j = \sum_i x_{ij}(y_i - w^T_{-j}x_{i,-j}) = \sum_i x_{ij}(y_i - \hat y_{i,-j}) $
Where $\hat y_{i,-j}$ is the predicted value of the model, using all features except feature $j$.
In a OLS regression model, the expectation of the random variable y is $E(Y_i) = \alpha + w x_i$ where $\alpha$ is a constant intercept and $w$ is the slope of the regression line, so again $E(Y_i) \propto wx_i$.
Putting all together we have
$$ c_j = \sum_i (x_{ij} - 0)(y_i - \hat y_{i,-j}) \propto  \sum_i (x_{ij} - 0)(y_i - E[y_{i,-j}]) $$
Which would imply / assume that the mean of the $x_{ij}$ is zero (i.e. data is centered)
Comment: The standard deviations in the denominator are always positive, so they won't change the sign of the numerator, hence you can "push" them into the proportionality sign - I would be curious to have someone double check though - if glen_b or whuber see this in the future, thanks !
Comment: In case of the lasso the mean of every feature should be zero because of the centering
Comment: Well that works out then
Comment: Great answer ! Just one question. I didnt understand how you can ommit the variance in that case and argue with the proportional statement.


How do I play this 8th note triplet?

Question:
These two measures are identical except for the triplet 8th notes in the right hand of the first measure.
This piece is in cut time, so how can both these measures add to 2 beats when one of them has triplet and the other doesn't?
Would I play these measures the same way?
Answer: The short answer is yes.  Triplet marking is often optional.  The composer is basically saying these are triplets, and play all the others the same.
The basic rule is if you see three 8th notes that are taking up a single quarter note's place, then you play them as triplets whether they are marked as such or not.  Another clue is that 8th notes beamed in groups of three are generally triplets.  (An exception would be three 8th notes followed by an 8th rest, for example.  Then you would analyze it in terms of how many 8th notes there are for a given quarter note.)
Comment: From experience I can tell you. A lot of composers didn't even bother writing the three, plus bracket when needed. Some did the first example of the serie and the following triplets you had to understand by yourself (like in your case). I was in your shoes a lot of time, so to speak, by ruminating I came to the conclusion like BobRodes  wrote.
Answer: These note values only make sense if both of them are triplets. Sometimes depending on the means of notation marking a measure as triplets can be a tiresome task. This may necessitate that triplet markings are not used every time.
The grouping of the triplets also gives you the indication of the triplets. They say to you here you have three notes in the time of one beat. So three quavers in the time of a crotchet beat so 3 in the time of two.
Answer: The notation as printed is technically incorrect.  But there is such a strong implication that the 3-note groups in bar 2 are also triplets that the composer (or engraver) felt justified in omitting the triplet number.
It wouldn't have been any trouble to print the number.  It wouldn't have taken up any space that could have been used for anything else.  You won't be the only  inexperienced student to question it.   So was omitting the number a good decision?

How do I play this 8th note triplet?


Esconder a URL de destino

Question: No exemplo do jquery os argumentos são bem identificados; url e os parametros de formulário.
<code>$.ajax({
  url: "test.html",
}).done(function() {
  // ...
});
</code>
Quero saber se tem alguma forma de ocultar a url no ajax ou dificultar ao maximo a identificação do destino para evitar que seja copiado e colado no navegador.
Vejo o js de outros sites e aparentemente são javascript puro.
Isso implica em segurança em alguma forma?
Comment: @Orion, obrigado pelo link, estou lendo
Comment: Dê uma olhada aqui depois http://pt.m.wikipedia.org/wiki/Cross-site_request_forgery
Comment: Que linguagem você usa no servidor? É possível identificar se a requisição veio mesmo por ajax, e responder com um erro se não tiver vindo.
Comment: Você pode colocar em um arquivo .JS separado e minificado, já dificulta um pouco, criptografar a  URL e usar uma função para descriptografar na hora de usar, já impede a visualização direta, mas se o usuário estiver determinado a ver a URL, nada pode ser feito.
Comment: Ou melhor ainda usar um ofuscador como [este](http://javascriptobfuscator.com/)
Comment: Qual sua linguagem no lado servidor?
Comment: Uso PHP, mas a variavel $_SERVER, é 100% garantido? Dizem que as requisições podem ser 'simuladas'
Answer: Não, na verdade não existe maneira de esconder nem a url nem os valores.
Agora tem algumas medidas que caso haja necessidade podem ser tomadas, como:

Adicionar uma regra restrita de CORS no seu servidor

Com isso você pode restringir a utilização da sua api ou seja o que for, a dominios especificos.
Ex: Você tem uma url que cadastra o usuário, você pode no servidor configurar para que apenas o site www.meusite.com com possa acessar, com isso um outro site qualquer vai receber um erro ao tentar acessar. ( Isso é browser que barra, um CURL já funciona)

Criptografar

Alguns dados mais sigilosos podem ser criptografados de modo que não sirvam de nada para quem interceptar.
Ex: Quero enviar meu usuário e minha senha e quero proteger esses dados, posso fazer um MD5 e enviar, também existem outras alternativos como bcrypt.. etc.
Espero que tenha ajudado.
Comment: Nunca ouvi falar em `CORS`, vou procurar, obrigado
Answer: Esquece isso! Se você encriptar alguém pode desencriptar, se você ofuscar alguém pode desofuscar (existe essa palavra?).
Se o problema é o usuário acessar uma página direto pelo endereço você deve verificar na requisição desta página se o método de chamada dele é o esperado. Por exemplo, GET ou POST.
Comment: obrigado... eu so PHP, a variavel $_SERVER dizem que as requisições podem ser 'simuladas' é seguro?
Comment: $_SERVER['REQUEST_METHOD'] pode usar sem medo!
Answer: Como desencriptografar um MD5 256 ou um bcrypt baseado em hash de comparação?
A possibilidade é claro que existe, mas o custo para fazer isso é muito grande e muito lento, no caso do bcrypt posso te afirmar que é quase impossível, já que o hash gerado é sempre diferente e tem que ser comparado através de um algoritmo lento.
Quanto a desofuscar não entendi tecnicamente como seria feito, como desofuscaria um CORS no browser?
Quanto aos metodos POST e GET não mudam em nada a segurança dos dados, a unica diferença é que o GET envia na query e o POST no payload do HTTP.
Concluindo, não.. não esqueça isso. Leve em consideração proteger seu servidor com CORS e pelo bem dos seus usuários utilize um algoritmo de criptografia para os dados sensiveis.
Comment: O custo não compensa! Encriptar a url somente para evitar que o usuário não tenha acesso a ela pelo código, quando na verdade ele pode capturar depois da requisição ser realizada!
Comment: Em nenhum momento eu falei de encriptar a url, e sim os dados. Quanto a url no servidor pode ser adicionada uma regra de CORS que não tem nada com criptografia e sim com restrição de uso pelo browser.
Comment: Sim no caso de ofuscar seria o endereço da url. Quanto ao CORS é uma boa também. Ao que parece ele já está utilizando o request_method!

Esconder a URL de destino


Reverse DNS and Mailserver and self generated certificates

Question: this is my first question here, so don't kill me if it sounds stupid.
I don't know much about server administration, that's why we booked a managed server to host our clients.
So far we have been to setup most of it but I am concerned about the Mailserver setup.
Wer are unable to change the reverse dns of the server. It uses a generic name such as xxx.yourserver.com and I am worried that the generic reverse dns server will lead to email rejections due to bad reputation as so many people are using the same reverse dns.
We do have our own dedicated ip adress and the option to book more.
I have seen that some agencies change the reverse dns to something like isp.agencyname.com and they also have the Mailserver for clients set up like this : mail.clientdomain.com
I'm wondering how the hostname, reverse dns and Mailserver work actually work together and how to set them up together to work in harmony.
I've tried to set the Mailserver for client domains to mail.clientdomain.com but then I had a mismatch with the hostname and the certificate name since the 2 are different. Also, plesk comes with a self generated certificate by rapid SSL for the hostname. Can I keep it or do I have to purchase my own certificate to ensure reliable transmission of email.
How can I achieve a reliable Mailserver setup for my clients?
Thanks so much for your help
Answer: I am racking my brain around this for some time now too. Any suggestions or corrections are very welcome.
In the following examples I will refer to xxx.yourdomain.com as hostname.yourdomain.com. Because the PTR (reverse dns record) should point to the hostname on any host, regardless if the host has a mailserver running.
Forward zone yourdomain.com:
yourdomain.com.   IN    MX    hostname
hostname          IN    A     126.96.36.199

The MX record should point to the host that will be serving mail for yourdomain.com. In your case this is a probably a pointer to itself, if you serve mail by the mailserver running on that host. The hostname must point to an A or AAAA record. The host where the MX is pointing to must always be an A or AAAA record and never an alias with CNAME.
The reverse dns record should point to your hostname.
184.108.40.206    -->    hostname.yourdomain.com.

Forward zone clientdomain.com:
clientdomain.com.   IN    MX     hostname.yourdomain.com.
mail                IN    CNAME  hostname.yourdomain.com.

The MX record should point to the hostname of your server, which will be serving mail for clientdomain.com. The subdomain mail here just serves as an alias to your mailserver host.
The mailserver running on host hostname.yourdomain.com should always advertise itsef with its hostname in the SMTP dialog. Many mailservers will make a reverse dns lookup and check if the IP address points to the same hostname as advertised by your mailserver.
Basically it would be sufficient to have a mailserver certificate with hostname.yourdomain.com as CN name. But if you want your clients to be able to also connect to your mailserver via mail.clientdomain.com, then this domain must be contained in the certificate as subjectAltName. Any commercial CA should be able to do this. As a free alternative you can use Let's Encrypt, where you are able to use up to 100 (at the moment of writing) subjectAltNames per certificate.


Has anyone run into problems in TortoiseSVN where the 'author' isn't written to the log?

Question: I have someone connecting to my repository using the url (substituted the IP address):
svn+ssh://firstname.lastname@example.com/subversion
Yet when they commit files, the author entry is "null".
According to this article: http://tortoisesvn.net/node/80
it should be working fine.
Does anyone have any suggestions?
Answer: Check your server configuration in [repository]/conf/svnserve.conf file if it has set
anon-acces=write
auth-access=write

Usually, with the default settings
anon-access = read
auth-access = write

(you can just comment out the lines), the author information should be preserved.


Calcular taxa de juros com JavaScript

Question: Não estou conseguindo calcular a taxa de juros de uma variável com JavaScript (Comecei a estudar hoje)
Segue o código:

FORMULÁRIO

Id
<input id ="id" name ="id" type="number" ng-model="cadastro.id"/>

Nome Cliente
<input id ="nome" name ="nome" type="text" ng-model="cadastro.nome"/>

Limite de Crédito
<input id ="limite" name ="limite" type="number" ng-model="cadastro.limiteCredito"/>

Risco
<input id ="risco" name ="risco" type="text" ng-model="cadastro.risco"/>

<button ng-click="salvar(cadastro)"> SALVAR </button>
<button ng-click="cancelar(cadastro)"> CANCELAR </button>

</form>

$scope.salvar = function (cadastro) {

    /*
     *Lógica para podermos utilizar a function Editar.
     */
    var achouCadastro = false;
    for (var i = 0, length = cadastros.length; i < length; i++) {
        if (cadastros[i].id === cadastro.id) {
            cadastros[i].nome = cadastro.nome;
            cadastros[i].limiteCredito = cadastro.limiteCredito;
            cadastros[i].risco = cadastro.risco;
            achouCadastro = true;
            break;
        }
    }

    if (!achouCadastro) {

        /*
         * Lógica para calcular a taxa de juros
         */

        var valorJuros = cadastro.risco.value;
        var limiteComJuros = number(cadastro.limiteCredito.value);
        if (valorJuros === "A") {
            return limiteComJuros;
        } else if (valorJuros === "B") {
            limiteComJuros = cadastro.limiteCredito + cadastro.limiteCredito * 0, 1;
        } else {
            limiteComJuros = cadastro.limiteCredito + cadastro.limiteCredito * 0, 2;
        }
        cadastros.push(cadastro);

    }
    $scope.cadastro = {};

};

Meu if .. else não está funcionando. Alguém poderia me dar uma luz?
Comment: Crie uma variável valorComJuros que calcula o valor de um boleto acrescido de 10% de juros por atraso;
Answer: Vi que está tentando utilizar a função para estocar os valores em arrays posteriormente, porém, o cálculo de juros tendo como base os dados que foram inseridos no campo de formulário, a lógica simples seria :
var valorJuros = cadastro.risco.value;
        var limiteComJuros = parseFloat(cadastro.limiteCredito.value);
        if (valorJuros === "A") {
            return limiteComJuros;
        } else if (valorJuros === "B") {
            limiteComJuros = cadastro.limiteCredito + cadastro.limiteCredito * 0.1;
        } else {
            limiteComJuros = cadastro.limiteCredito + cadastro.limiteCredito * 0.2;
        }

parseFloat() vai retornar sempre em número, pois assim não corre o risco de apanhar valores ao qual o JS não conseguirá calcular
Multiplicar qualquer valor e data por 0 (cadastro.limiteCredito * 0, 1), terá como resultado, 0.

Se a lógica acima não for o que procura, comente a lógica ao qual espera os resultados e tentarei refazer o código para ajudá-lo.

Calcular taxa de juros com JavaScript


ML method to identify data subset with lower average values?

Question: I have a task where I need to find anomalous groups of observations [y,X] by the average value of y, using the feature set X.
A good interpretation is that these are customers and I want to find the most valuable ones.
(Note, this is actually separate from a classification problem, which I would use decision trees.)
This lead me to "Subgroup Discovery", but this is a field I'm unfamiliar with and I don't know the mainstream methods in it. For example, regressions, decision trees and NN are methods in classification methods, but I don't know the standard methods for SD.
Can someone confirm subgroup discovery is what I want and give point me in the right direction with some concepts (maybe just search keywords) of common methods used in this field for my problem?
Comment: [Anomaly Detection](https://en.wikipedia.org/wiki/Anomaly_detection) that's the topic you're looking for.
Comment: doesn't seem like an SD problem; can you elaborate more on the kind of data you're having, and how exactly the "subgroup" look like.
Comment: The data is a list of features (X) and an outcome variable (y).

The population average of y is say 50. I want to find out all interesting groups where the average of y is say 200.

These groups are defined as having  features with certain values, for example X = (x_1 ,x_2,x_3) = (true,false,10).
Comment: @7kemZmani, I'm interested in why this isn't SD. I must have interpreted what I read wrong and I don't understand. Can you explain?
Comment: Using SD would only tell you what is expected for a population assuming that that population has certain characteristics, for example, normality. It will not identify which identifying characteristics form patterns which allow for recognition of distinct subpopulations whereas anomaly detection would.
Answer: Generally this type of problem can be viewed in two ways:

as an anomaly detection problem (as suggested by 7kemZmani), if we can assume that there is some kind of pattern that we expect the overall population to follow and we are interested in identifying the instances that deviate noticably from this pattern.
as a clustering problem, if we expect multiple subgroups in the population we're examining and want to identify their location and members.

Now based on these two views, I suppose it's up to you to identify which fits your problem better.
If you are not sure that your data is the result of a single underlying process, I would suggest you experiment with clustering approaches and on examination of the results decide further steps.
In particular it would be interesting to have a look at how clustering methods that don't require a prior assumption of the number of groups (like k-means does) cluster your data and with how many groups these end up. For this there's multiple options, right now DBSCAN, hierarchical clustering and (a bit far out for this but I've worked with it before) 'Bayesian Gaussian Mixture Models' come to my mind.
These three methods are examples of methods that will present you a grouping of your data into an unspecified number of groups. Examine the results you get from this, with hierarchical clustering for example you can visualize the result of the clustering with a dendrogram to examine which clustering is closer to the actual structure. With a bayesian GMM, you can have a look at the resulting mixture weights of the model.
If in these two examples this examination points towards a single cluster describing the data best, then you should be safe to assume that there actually is only a single process generating your data.
Then, applying anomaly detection makes sense and allows you to identify outliers from the 'expected outcome'.

Edit:
While I am not familiar with subgroup discovery, I can point you towards a nice survey article on the topic. This should give you a good introduction to the topic and point you towards common techniques and methods for such problems.
Comment: This is an excellent and very complete answer. I'm going to look up what you said on DBSCAN and Bayesian Gaussian Mixture Models. (I've already reviewed hierarchical clustering).
Comment: In addition to what you said, I'm interested in knowing if you are familiar with Subgroup Discovery and how this fits in...it seems like this is exactly a fit for it. It seems like SD is a more obscure subdiscipline. Some information here: https://www.google.ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=13&ved=0ahUKEwiJvb7pnLDYAhVRy2MKHTpLAaIQFghhMAw&url=http%3A%2F%2Fcrest.cs.ucl.ac.uk%2Fcow%2F15%2Fslides%2FRachelHarrison.pptx&usg=AOvVaw0vbTjSCpQMFrh2sfBTOx-d
Comment: I'll expand my answer tomorrow
Comment: Thank you Rickyfox, this is extremely helpful! I will review!
Comment: in case my answer is sufficient, consider accepting it ;)


Incremento e decremento não funcionam na ordem esperada

Question: int main(){
  int i=5;
  printf("%d%d%d%d%d",i++,i--,++i,--i,i);
}

saída: 45555

Por que dessa saída? Não entendi corretamente a razão dessa saída.
Comment: para obter a saída com os incrementos e decrementos tem de dar em passos sequenciais
Comment: O problema é que como o @Maniero falou na resposta abaixo não há ordem garantida, mas também outro problema é que você está fazendo atribuição nessa variável, o correto seria fazer + 1 e - 1 para ter o resultado sem modificar o valor da variável, mas sem saber a utilização dessa instrução, não dá para ter certeza. Imagino que isso seja apenas um estudo de caso.
Answer: Não há garantias acerca da ordem de execução dos argumentos na chamada da função, portanto a intuição indica que fará nesta ordem e o resultado seria "56655", mas cada compilador pode fazer como achar melhor. Esta operação é considerada um comportamento indefinido. Se deseja ordem faça um por statement, não use como expressões usando o operador de lista (vírgula).
Lembre-se que os operadores ++ e -- são atribuidores, portanto produzem efeitos colaterais mudando o valor da variável. Se a intenção for adicionar ou subtrair 1 do valor da variável sem mudar o valor dela própria, aí tem que usar um operador que não faz atribuição, que não gere efeito colateral. No caso seria i + 1 ou i - 1, assim geraria o resultado e o usaria sem afetar a variável. Neste caso o resultado seria "64645". Claro que seria semanticamente muito diferente do que postou, não parece querer saber isto.
Assim funciona como esperado:
#include <stdio.h>

int main() {
    int i = 5;
    printf("%d", i++);
    printf("%d", i--);
    printf("%d", ++i);
    printf("%d", --i);
    printf("%d", i);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Export command line output to a file in Python

Question: Here's my code to execute a jar file in Python:
import os
os.system("java -jar xyz.jar")

I can see the output on terminal, but want to store it in a file. How can I do that?
Comment: Redirect the output to a file in the terminal, using `>` ?
Comment: I want to do hundreds of iterations, so want the process to be automated. Any ideas?
Answer: With subprocess.call you can pipe outputs (stdout, stderr or both) directly into file:
import subprocess
subprocess.call("java -jar xyz.jar", shell=True, stdout=open('outfile.txt', 'wt'), stderr=subprocess.STDOUT)

Note that I added shell=True parameter, which is required if  your application requires shell-specific variables (such as where Java is located).
Also note that in the above call, the output streams are handled as follows:

stderr stream is piped to stdout, and
stdout is piped to outfile

More details on stream configurations are available in subprocess manual page.
Comment: Update after a chat: In this case `shell=True` was actually required to correctly locate Java.
Comment: I tried, but output file is empty. But I can still see output on terminal. Where I might be doing wrong?
Comment: No, I'm just doing this.
Comment: Wait... I get it now. Your application is probably printing to stderr so you need to pipe stderr stream to the file too.
Comment: Check out the edited answer, which takes stderr into account.
Comment: Traceback (most recent call last):
  File "pythonScript.py", line 15, in
    subprocess.call("java -jar xyz.jar", stdout=outfile, stderr=subprocess.STDOUT)
  File "/usr/lib/python3.4/subprocess.py", line 533, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'java -jar xyz.jar'
Comment: Well.. You asked how to run command `java -jar xyz.jar` and store console output and the code above does just that. You surely know better than anyone else what is the actual command you want to run, if its not that.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54886/discussion-between-tanay-soni-and-jsalonen).
Comment: Also, you may need to use absolute paths for programs. Using `shell=True` argument could possibly help too.
Answer: Don't use os.system, use subprocess instead.
import subprocess

output = subprocess.check_output(["java", "-jar", "xyz.jar"])

file = open('file.txt', 'w+')
file.write(output)
file.close()

Comment: I get this error:
File "pythonScript.py", line 4, in
    output = subprocess.check_output("java -jar xyz.jar")
Comment: Traceback (most recent call last):
  File "pythonScript.py", line 2, in
    output = subprocess.check_output("java -jar xyz.jar")
  File "/usr/lib/python3.4/subprocess.py", line 603, in check_output
    with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
  File "/usr/lib/python3.4/subprocess.py", line 848, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'java -jar xyz.jar'


Drush command to check if Drupal is installed?

Question: Is there any way to use Drush to determine if Drupal is installed, and have it return true or false? The boolean output would be used elsewhere in a bash script's logic.
Bonus: it needs to work for both Drupal 7 and Drupal 8.
Answer: $ cd /path/to/drupal6or7or8
$ drush status bootstrap | grep -q Successful

Then, $? will be 0 if Drupal has been installed, or 1 if there is no site, or it does not have a database, or the site has not been installed.
Comment: This does not work anymore with Drush 12. What is recommended now?
Answer: In addition to @greg_1_anderson answer, I'd like to add that that is sensitive to locale problems. Successful will be translated in the output from Drush. To work around this problem, I'd suggest this somewhat dirty workaround:
drush status bootstrap | grep -q $(drush php-eval 'if (function_exists("t")) echo t("Successful");') &> /dev/null;

As mentioned above, $? will be 0 if installed, higher if not.
Answer: For anyone looking for a like for like replacement for drush status bootstrap in Drush 12:
drush status --field=bootstrap

Comment: Upvoted. This is the way. Returns "Successful" if successful, otherwise blank.
Answer: As of Drush 12 drush status bootstrap does not work anymore.
You can check if there is something in the config table instead:
drush sql-query 'SELECT 1 FROM config LIMIT 0,1' > /dev/null 2>&1

Return value 0 means Drupal is installed.
Comment: `SELECT 1` or selecting a specific column name should be faster than `SELECT *`.


Support of a function.

Question: Let $f:\mathbb{R}^2\rightarrow\mathbb{R}$ such that $f(x,y)=1/2$ if $x=j2^{-m}$, with $j\in\mathbb{Z}$ and $m\in \mathbb{N}$, and $(x,y)\in[-1,1]\times[-1,1]$; and $f(x,y)=0$ if $(x,y)$ doesn´t satisfy  the previous conditions. Then the question is: what is the support of $f(x,y)$ if we know that the support of a function is the closure of all the points $(x,y)$ such that $f(x,y)\neq0$? This in order to prove that the support of $f$ is compact (bounded and closed).
Comment: You seems to be assuming *a priori* that the support is bounded (as $\operatorname{supp}f \subseteq [-1,1]^2$), and the support is closed by definition.  If the goal is to show that the support is compact, what else is there to know?
Comment: Well,, yes, we know that the support of $f$ is contained in $[-1,1]^2$, but for example, if we take $m=2$ what is the support of $f$? Sorry if my questions seem obvious but I'm taking a course of introduction to analysis for the first time.
Comment: You seem to be confused about how the function is being defined.  The function is nonzero for any value of $x$ such that there *exist* $j \in \mathbb{Z}$ and $m\in \mathbb{N}$ such that $x = j2^{-m}$.  You don't get to pick some value of $m$ and then compute the support of $f$.
Comment: I see, thanks. Then, just for curiosity, is the support  of $f$ the box $[-1,1]^2$ or the set {$(x,y)|j2^{-m},j\in\mathbb{Z},m\in\mathbb{N}, y\in[-1,1]$}?
Comment: The set $S = \{ (j2^{-m}, y) : j\in \mathbb{Z}, n\in\mathbb{N}, j2^{-m} \in [-1,1], y\in [-1,1]\}$ is the set of points where $f$ is nonzero.  This set consists of a bunch of vertical lines at at each of the dyadic rational numbers.  This is not the support of $f$, as the support is the *closure* of $S$. $S$ is dense in $[-1,1]^2$, hence $\overline{S} = [-1,1]^2$ is the support of $f$ (as noted in the answer below).
Comment: Thanks for your help!
Comment: But, again, I still find the question unclear.  Are you trying to determine the support of $f$, or are you simply trying to show that $f$ is compactly supported?  If the latter, then (1) the support is closed by definition, and (2) the support is bounded by construction of $f$.  Thus, by application of Heine-Borel, the support is compact.  Done.  You don't need to explicitly determine the support to arrive at this conclusion.
Comment: Sorry if i wasn´t clear. The idea of the exercise is to prove that the support of $f$ is compact but, since I didn´t have a course of set theory or some related, I don´t understand very well the concept of closure of a set (in reality my course is about integral calculus in several variables but many of my college say that it is a course of introduction to analysis). So I extended it as an example of the closure of a set, in this case the closure of {$(x,y)|x=j2^{-m}, j\in\mathbb{Z}, m\in\mathbb{N}, y\in [-1,1]$} and I wanted to see arguments on why $supp f =[-1,1]^2$.
Answer: The support of the function is equal to $$\mbox{supp}f =[-1,1]\times [-1,1]$$
since the set $$A=\{(x,y): x=j2^{-k} , j\in \mathbb{Z} , k\in\mathbb{N} , y\in [0,1]\}$$
is dense subset of $[-1,1]\times [-1,1].$
Comment: Thanks, it worked for me

Support of a function.


Sum of all elements in a matrix with specified conditions

Question: Let M be a matrix with 20 rows and 21 columns, containing the following elements
$M[i][j]=i*i$ if $i=j$
$M[i][j]=min(i,j)$ if $i≠j$
for $1\leqslant i\leqslant 20, 1\leqslant j\leqslant 21$.
What is the sum of all elements in the matrix?
My approach:
I drew a $4\times 5$ matrix with the specified elements and figured out that there are:
$i+j-1-1=7$ elements of $1$
$i+j-3-1=5$ elements of $2$
$i+j-5-1=3$ elements of $3$
$i+j-7-1=1$ elements of $4$
Plus the squared elements $(1,4,9,16)$
Now, for the $M[20][21]$, following the same approach ,we have:
$S=(39\times1+37\times2+\ldots+1\times20)+(1+4+\ldots+20)=S'+S"$
$S'=39\times1+37\times2+\ldots+1\times20=2870$
$S"=1+4+\ldots+20=1/6\times20\times(20+1)\times(2\times20+1)=2870$
$S=2\times2870=5740$
So, my questions are:

How can I calculate $S'$ without doing every operation?
Is there a easier way to solve the problem?
Answer: I'm not aware of any special formula for this strange kind of matrix, but a closed-form sum for any $m \times n$ matrix is fairly simple to figure out. I will do this for $n > m$, since that is what you have above, but you can simply switch these dimensions in the final formula if $m > n$.
You have already worked out most of the pattern. Let's take the $4 \times 7$ example which looks like
$$
\begin{bmatrix}
1 & 1 & 1 & 1 & 1 & 1 & 1 \\
1 & 4 & 2 & 2 & 2 & 2 & 2 \\
1 & 2 & 9 & 3 & 3 & 3 & 3 \\
1 & 2 & 3 & 16 & 4 & 4 & 4
\end{bmatrix}
$$
We can quickly count that the sum for this is $80$, but let's break it down.
You have already shown that the diagonal of squares has to be treated separately and has a known formula
$$
\sum_{i=1}^m i^2 = \frac{m(m+1)(2m+1)}{6}
$$
We can see that everything above the diagonal follows an obvious pattern and everything below is simply reflected, but truncated because of the smaller dimension.
For the elements above the diagonal it is simply the sum from $1$ to $m$ of the row number $i$, repeated $n - i$ times, which is
$$
\sum_{i=1}^m i (n - i)
$$
For the elements below the diagonal it is similar, but note that the sum is again up to $m$, not $n$, due to the truncation
$$
\sum_{i=1}^m i (m - i)
$$
Bringing this all together, the total sum can be given as
\begin{align}
S & = \sum_{i=1}^m i^2 + \sum_{i=1}^m i (n - i) + \sum_{i=1}^m i (m - i) \\\\
& = \sum_{i=1}^m [i^2 + i (n - i) + i (m - i)] \\\\
& = \sum_{i=1}^m [i^2 + i n - i^2 + i m - i^2] \\\\
& = \sum_{i=1}^m [(m + n) i - i^2] \\\\
& = (m + n) \sum_{i=1}^m i - \sum_{i=1}^m i^2 \\\\
& = (m + n) \frac{m(m+1)}{2} - \frac{m(m+1)(2m+1)}{6} \\\\
& = \frac{m(m+1)(3m + 3n) - m(m+1)(2m+1)}{6} \\\\
& = \frac{m(m+1)(m + 3n - 1)}{6}
\end{align}
For $4 \times 7$ this is indeed $80$ and for your big $20 \times 21$ example it is, as you calculated, $5740$.
As I indicated at the start, you can swap $m$ and $n$ if the matrix is taller than it is wide, and it will still work. Alternatively, if you always know that $n = m + 1$ you can obviously further simplify this final formula.


Printing out selected items from an enum flag

Question: I have the following enum (which later will grow larger!):
enum TrainingFilters {
    NONE    = 0,
    GAUSS   = 1,
    SOBEL   = 2,
    FEATURE = 4
};

I have to print out string representation of the all possible combination. For now, a not-leangthy switch statement works fine, but if I add more items it will be disaster!
void Manager::setFilters(int filters)
{
    QString what("Selected filters:");

    switch (filters) {
    case 0:
        what.append(" NONE ");
        break;

    case 1:
        what.append(" GAUSS ");
        break;

    case 1 | 2:
        what.append(" GAUSS SOBEL ");
        break;

    case 2:
        what.append(" SOBEL ");
        break;
    case 2 | 4:
        what.append(" SOBEL FEATURE ");
        break;

    case 4:
        what.append(" FEATURE ");
        break;

    case 1 | 4:
        what.append(" GAUSS FEATURE ");
        break;

    case 1 | 2 | 4:
        what.append(" GAUSS SOBEL FEATURE ");
        break;

    default:
        qDebug() << "Invalid FILTERS enum received!";
        return;
    }

    qDebug() << what;
    mFilters = static_cast<TrainingFilters>(filters);
}

P.S: I have a few checkbox items in the user interface, and I should do some stuff according to the checked checkboxes. I use it like this:
var a, b,c;
cbGauss.checked ? a = 1 : a = 0;
cbSobel.checked ? b = 2 : b = 0;
cbFeat.checked ? c = 4 : c = 0;

cpManager.setFilters(a | b | c);

So my qustion is what is the best/easiest/smartest way to achieve this?
Comment: Possible duplicate of [C++: Print out enum value as text](http://stackoverflow.com/questions/3342726/c-print-out-enum-value-as-text)
Answer: You could simply do
if (filters & 1)
    what.append("GAUSS ");
if (filters & 2)
    what.append("SOBEL ");
if (filters & 4)
    what.append("FILTER ");

And so on. This way you can easily add new ones. Of course you have to check for zero and then add NONE.


How to Set a Limit on Echo?

Question: Needed help here on how to set limit for my table. I just want the first and single value but i couldnt find solution on this.
As i have inserted dates and times in my table. So it looks like this, it has repeated values for both Date and Time.
Date : 19-11-1819-11-18
Time : 05:21:0705:32:10
I just want single value for both Date and Time. Here is my codes.
Date :
<?php
        mysqli_data_seek($results, 0);// second instance
        while($row = mysqli_fetch_array($results)) {
          echo $row['check_date'];
        }
        ?>

Time :
<?php
        mysqli_data_seek($results, 0);// second instance
        while($row = mysqli_fetch_array($results)) {
          echo $row['check_time'];
        }
        ?>

Appreciate for your help!
Comment: Is the value in your database actually `19-11-1819-11-18`? Why is it doubled? Also, where is your query? Why are you not fetching both time and date in one go? Are you storing the date and time as strings? Why not use date and time types? You should also let us know what actually happens when you run your code. What is the actual issue with it?
Comment: It supposed to be only 19-11-18, but it is because i have two columns with the same date, and i could only fetch both values, which that is why it got doubled. Still looking for solution on how to limit the value using echo. I just wanted the first single date.
Comment: Im sorry Im very new to php. ;(
Comment: Just select the columns you need and echo those columns? Not sure what the actual issue is. Or do you mean that you have two _rows_ with the same date? That's a big difference. If you just want the first, just add `LIMIT 1` at the end of your query. The question is still a bit unclear.
Comment: As @MagnusEriksson mentioned, it seems like your problem is on the query not PHP. You could do the `LIMIT 1` as he suggested or you could do something like `SELECT DISTINCT check_time FROM check_table`.
Answer: Use substr() to only show the first 'n' of your output
echo substr($row['check_date'],0,8);

but really, as Magnus says, you need to work out why your database is storing the date/time twice and consider moving to using actual datetime fields instead.
Comment: This won't fix anything. Currently the `echo` statement gets run twice because there's 2 rows. It's on a single line because OP didn't add a new line. Using `substr` doesn't do anything here.
Answer: There are several ways of doing this, but the simplest with just the lines of code you have is to not use a loop - if you want 1 value then just fetch 1 row of data...
mysqli_data_seek($results, 0);// second instance
$row = mysqli_fetch_array($results);
echo $row['check_date'];

One thing I would suggest is that it may be easier also to just fetch the data in one place.  Now you've fetched the data into $row you can latter on just echo out the data already retrieved...
echo $row['check_time'];

although you may be safer to read it into something with a more unique name so that you don't re-use the $row and loose the values...
mysqli_data_seek($results, 0);// second instance
$checkData = mysqli_fetch_array($results);
echo $checkData['check_date'];

How to Set a Limit on Echo?


Proving this set is compact in $L^2(\Omega)$

Question:
Let $\Omega = [0,1]^d \subset \mathbb{R}^d, d \ge 3$, and for any $x
 \in \Omega$ define $$Tf(x) \equiv \int_{\Omega} e^{-
 \frac{(y-x)^2}{2}}f(y) \lambda (dy) $$ for any $f : \Omega \to
 \mathbb{R}$ for which the RHS is well defined. Using Sobolev
inequality or otherwise, show that the following set $$ \{Tf :
 \|f\|_{L^2} \le 2 \}$$ is compact in $L^2(\Omega)$.

My questions:

Is my attempt below correct?
How would we even use the Sobolev inequality here? I thought that the only thing we need is the Rellich-Kondrachov theorem.
Is there an easy way to see the above set is closed?

My attempt:
I proved that $Tf \in L^2(\Omega)$ and also $\|Tf\|_{L^2(\Omega)} \le C$ for every $f$ in the set above, but now I need to find the weak derivative $\partial_{x_i} Tf$ and show it is in $L^2(\Omega)$ as well. But I am not sure how to find $\partial_{x_i} Tf$. My attempt with this:
Since our function is smooth then the weak derivative is equal to the ordinary partial derivative. So we calculate:
$$\partial_{x_i} Tf = \int_{\Omega} \partial_{x_i}e^{- \frac{(y-x)^2}{2}}f(y) \lambda (dy) = \int_{\Omega} (y-x)e^{- \frac{(y-x)^2}{2}}f(y) \lambda (dy)$$
And now:
$$|\partial_{x_i} Tf(x)| \le \int_{\Omega} |2| \cdot 1 \cdot |f(y)|  \lambda (dy) \le 2 \cdot \|f\|_2 $$ so
$$\|\partial_{x_i} Tf\|_{L^2(\Omega)} \le 2\lambda(\Omega)^{\frac{1}{2}} \|f\|_2 \le 4\lambda(\Omega)^{\frac{1}{2}}$$ Hence any weak derivative of first order is in $L^2(\Omega)$ and in fact since the above bound works for any $f$ with $\|f\|_2 \le 2$ then we have that our set is bounded in $H^{1}(\Omega)$. By Rellich-Kondrachov theorem this set is precompact in $L^2(\Omega)$ but since it is closed (I am not sure how to prove this actually) then it is compact in $L^2(\Omega)$.
Answer: You do not need Rellich-Kondrachov's theorem. You only need Ascoli-Arzelà theorem. As you write in your attempt:
$$\partial_{x_i} Tf (x) = \int_{\Omega} \partial_{x_i}e^{- \frac{(y-x)^2}{2}}f(y) \lambda (dy) = \int_{\Omega} (y-x)e^{- \frac{(y-x)^2}{2}}f(y) \lambda (dy)$$
and thus for all $i \in \{1,\dots,d\}$ and for all $x \in \Omega$ we have that:
$$|\partial_{x_i} Tf(x)| \le \int_{\Omega} |2| \cdot 1 \cdot |f(y)|  \lambda (dy) \le 2 \cdot \|f\|_2$$
end then $\|\nabla Tf\|_{L^{\infty}(\Omega)} \leq 2q \|f\|_2 \leq 4d$ for all $f$ such that $\|f\|_2 \leq 2$.
The family $\{Tf : \|f\|_{L^2} \le 2 \}$ is uniformly $4d$-Lipschitz continuous. What follows from Ascoli-Arzelà's theorem is that $\{Tf : \|f\|_{L^2} \le 2 \}$ is relatively compact. Hope this will help you.
Comment: Thanks a lot. This is a much nicer solution. But is my attempt also correct? If so what would be the easiest way to see the set in question is closed? I was thinking of writing it as the preimage of an open set under a continuous function but I was having trouble constructing such a function.


Why does the sectionn after the 'and' sometimes disappear (Conditional Probability)

Question: Trying to understand why in some problems I have seen regarding conditional probability, the section after the 'and' disappears without an explanation.
For example I have been looking at this problem:
$Pr(T-t>u|T>t) = \frac{Pr(T>t+u,T>t)}{Pr(T>t)} = \frac{Pr(T>t+u)}{Pr(T>t)}$
I do not understand why the $T > t$ on the numerator seems to disappear.
Why has $Pr(A|B)$ essentially been reduced to $\frac{Pr(A)}{Pr(B)}$ here?
Comment: When $A\cap B = A$ you can make the simplification.  Presumably $u$ must be non-negative.  The cases for which it is true then that $T>t+u$ as well as $T>t$ are exactly the same cases for which it is true that $T>t+u$.  After all, recognize that $T>t+u$ and $t+u>t$ together imply $T>t$ by the transitive property of $>$
Comment: What is $A\cap B$ if $A\subset B$?
Answer: First, to generalize the concept lets have $A \subset B$, and we want $\mathbb{P}(A | B)$. We can write:
$$ \mathbb{P}(A | B) = \frac{\mathbb{P}(A \cap B)}{\mathbb{P}(B)}$$
And remember here $A, B = A \cap B$ its just different notation for clarity of the concept. Now, if $A \subset B$ then $A \cap B = A$, which you may remember from discrete math*. We can now write:
$$\mathbb{P}(A | B) = \frac{\mathbb{P}(A \cap B)}{\mathbb{P}(B)} = \frac{\mathbb{P}( A)}{\mathbb{P}(B)}$$
Or in your notation:
$$\mathbb{P}(A | B) = \frac{\mathbb{P}(A ,B)}{\mathbb{P}(B)} = \frac{\mathbb{P}( A)}{\mathbb{P}(B)}$$
Which should clear up the general idea. Pause for a moment here and try to think to your example as to why we can apply this concept to your problem.
If $T > t + u$, then $T > t$, since $u > 0$. Hence, if we call $B$ the set of events such that $T < t$, and $A$ the set of events such that $T > t + u$, any event in $A$ is also in $B$, thus $A$ is a subset of $B$. That's why we can forget about the second part in your problem. Hope this helps!
*Proof for $A \subset B \Rightarrow A \cap B = A$. Let $A$ and $B$ be two sets such that $A$ is a subset of $B$. Then iff $x \in A \cap B$ then $x \in A$ and $x \in B$, but by definition of subset, $x \in A \Rightarrow x \in B$. Thus our condition can be shortened to iff $x \in A \cap B$ then $x \in A$, and hence $A \cap B = A$.


Cannot align top QTableWidget in QVBoxLayout

Question: I want to align both a QLabel and a QTableWidget in a QVBoxLayout on the top.
I have no problem aligning a QLabel on top to the QVBoxLayout by using the setAlignment method. When I add a QTableWidget to the QVBoxLayout, there is an issue.
My code:
class AWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.aLabel = QLabel('Table')

        self.aTable = QTableWidget(6, 6)
        self.aTable.setMaximumHeight(200)

        self.aLayout = QVBoxLayout()
        self.aLayout.addWidget(self.aLabel)
        self.aLayout.addWidget(self.aTable)
        self.aLayout.setAlignment(Qt.AlignTop)
        self.setLayout(self.aLayout)

app = QApplication([])

aWidget = AWidget()
aWidget.resize(640, 480)
aWidget.show()

sys.exit(app.exec_())

The QLabel must be on top of the main widget followed by the QTableWidget below it. However, both the QLabel and the QTableWidget keep staying on the center of the main widget, leaving much spaces between them.
Answer: You fixed the maximum height of your table to 200px and the layout is dealing with it by occupying as much space as possible.
You want to keep this height, you can insert a stretch at the end of your layout:
class AWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.aLabel = QLabel('Table')

        self.aTable = QTableWidget(6, 6)
        self.aTable.setMaximumHeight(200)

        self.aLayout = QVBoxLayout()
        self.aLayout.setAlignment(Qt.AlignTop)
        self.aLayout.addWidget(self.aLabel)
        self.aLayout.addWidget(self.aTable)
        self.aLayout.addStretch() # Adding a stretch to occupy the empty space
        self.setLayout(self.aLayout)


Number theory textbook exercise $11^{n+2} + 12^{2n + 1}$

Question: I have been stuck on proving the equation $11^{n+2} + 12^{2n+1}$ is divisible by $133$ for all positive counting integers $N$. The proof should ideally use induction and I'm not sure how to proceed through the inductive step
It's asking something like this problem: Show that this expression is divisible by $133$ [more info in desc.]
but I'm not sure how the modulo are derived equal and I would like to use induction.
Comment: You are not asking the same question. The link you gave has a different question. Further, the statement you wrote is incorrect too. It is not divisible if you take n=1 (I don't know about the rest though!).
Comment: I apologize I made a couple edits to clarify and corrected to the right question
Answer: The induction step $n \rightarrow n+1$ without modular arithmetic may look as follows:

Induction hypothesis (IH): $133 | (11^{n+2} + 12^{2n+1}) \Leftrightarrow 11^{n+2} + 12^{2n+1} = 133 \cdot k$ for a $k \in \mathbb{N}$
Induction step:
$$11^{n+3} + 12^{2n+3} = 11\cdot 11^{n+2} + 144\cdot 12^{2n+1}= 11\cdot 11^{n+2} + (133+11)\cdot 12^{2n+1} $$ $$= 133\cdot 12^{2n+1} + 11(11^{n+2} + 12^{2n+1}) \stackrel{IH}{=} 133\cdot 12^{2n+1} + 133 \cdot k$$
Answer: Without induction, consider mod $133$:
$$\begin{align}11^{n+2} + 12^{2n+1}&\equiv 121\cdot 11^{n} + 12\cdot 144^{n}\equiv \\
&\equiv (-12)\cdot 11^n+12\cdot 11^n\\
&\equiv 0 \pmod{133}.\end{align}$$
Comment: deserves an upvote!
Comment: I'm not very familiar with congruence. How did you go from the second congruence to the the third one?
Comment: $121\equiv 133-12\equiv -12 \pmod{133}$ and $144\equiv 133+11\equiv 11 \pmod{133}$.
Answer: Note that $11\cdot 12 =132 \equiv -1 \pmod {133}$.  They also use $144 \equiv 11 \pmod {133}$.  That should get you through the chain in the linked question.
To do an inductive proof, note that for $n=1$ we have $11^3+12^3=3059 \equiv 0 \pmod {133}$.  Then assume it is true for $k$, and we have
$$11^{k+2}+12^{2k+1}\equiv 0 \pmod {133}\\
11^{k+3}+12^{2k+3}=11\cdot 11^{k+2}+144\cdot 12^{2k+1}\\\equiv 11\cdot(11^{k+2}+12^{2k+1})\equiv 0 \pmod {133}$$
Answer: Like
Prove by induction that $3^{3n+1} + 2^{n+1}$ is divisible by 5
or
Proving that $64$ divides $3^{2n+2}+56n+55$ by induction,
If $P(m)=11^{m+2}+12^{2m+1}$
$$P(n+1)-11P(n)=12^{2n+1}(12^2-11)$$ which is divisible by $133$
Or $P(m+1)-12^2P(m)=11^{n+2}(11-12^2)$ which is divisible by $133$
In either case,
$133|P(n+1)\iff133|P(n)$ as $(11,133)=(12,133)=1$
Answer: Induction Step:
$11^{n+2} + 12^{2n+1} = 133*k$
and
$11^{(n+1)+2} + 12^{2(n+1) + 1} =$
$11^{(n+2)+1} + 12^{(2n+1) + 2}=$
$11^{n+2}*11 + 12^{2n+1}*144 =$
$11^{n+2}+ 12^{2n+1}*11 + 12^{2n+1}*133 =$
$(11^{n+2} + 12^{2n+1})*11 + 12^{2n+1}*133 =$
$[133*k]*11 + 12^{2n+1}*133 = $
$133 \times (11k + 12^{2n+1})$.
....
If you want to be slick an look like a magician take the above and do it backwards:
$11^{n+2} + 12^{2n+1} = 133*k$
$(11^{n+2} + 12^{2n+1})11 = 133*(11k)$
$11^{n+3} + 12^{2n+1}*11 = 133*(11k)$
$11^{n+3} + 12^{2n+1}*11 + 12^{2n+1}*133 = 133*(11k) + 133*12^{2n+1}$
$11^{n+3} + 12^{2n+1}(11 + 133) = 133(11k + 12^{2n+1})$
$11^{n+3} + 12^{2n+1}*144 = 133(11k + 12^{2n+1})$
$11^{n+3} + 12^{2n+1}*12^2 = 11^{n+3} + 12^{2n+3} = 133(11k + 12^{2n+1})$
$11^{(n+2) + 1} + 12^{2(n+1) + 1} = 133(11k + 12^{2n+1})$


Creating a job portal system

Question: I want to create a job system with the following workflow:

Administrator can add the jobs.
A page for job listings.
On detail job there should a link of apply for this job.
The form will contain the fields and upload application form.
The back end must display the number of application received for respective job.
On click on number of application received for respective job the see the list of Application received list for particular job category.

I have tried it with the Views and the Webform module.
Created a view for job listing and use webform for apply form. But what should I do with the trackers in point 5?
Answer: I would implement this in the following manner:

Two content types: Job opening & Job application
Job openings to have fields like : Job description, current CTC, expected CTC, etc.
Job application to have fields like : Cover letter, experience, resume (file upload), etc.
Important: In job application content type, add an entityreference field that refers to Job openings.
Give permission to company user to create job opening; and normal user to create job application.

With this architecture, you should easily be able to build the views as entityreference module provides two very powerful relationships:

Entity reference: Referenced entity (Job opening)
Entity reference: Referencing entity (Job application)
Comment: thank a lot for your solution. But how to display the number of application received for respective job.
Comment: @KadambiniDas I am afraid, I don't have much time to write down the complete answer. Just to give you pointer, and I have already mentioned this in the answer, you have to use views to build this and the relationships provided by entityreference module. I will try to expand on the answer when I can.
Answer: I've never used the Webform module, so this is just a hypothetical / shot in the dark suggestion (assuming somehow your webform links with your Job opening node).
Add a Numeric field to your Job Opening content type.
With Rules and Webform Rules you can react when a Webform is submitted.
So when webform is submitted, Add action of set a data value, you can add an offset of +1 to your numeric field. (you may need to click on Switch to something input mode to get the offset option)
The tricky part in the rule would be linking your webform with the correct job posting node. If you can figure out this part, you're golden.
Lastly, you would just add the numeric field to your view.

BONUS: You could use Field Permissions to hide
  your numeric field from node edit view.

Creating a job portal system


Prove that this subgroup is normal in $G$ where $G$ is a subgroup of $GL(2,\Bbb{F}$).

Question: Suppose that we have 2 subgroups  of $GL(2,\Bbb{F}$).
$G$ that contains matrices of the form:
$$\left(\begin{matrix}
        a & b \\
        0 & c  \\
        \end{matrix}\right)
$$ where $a,b \in \Bbb{F}$.
And $H$ that contains matrices of the form:
$$\left(\begin{matrix}
        1 & b \\
        0 & 1  \\
        \end{matrix}\right)
$$ where $b \in \Bbb{F}$.
Show that $H$ is a normal subgroup in $G$.
My attempt:
Let $A$ be a matrix in $G$. For every matrix $B$ in $H$, we have:
$ABA^{-1}$ = $$\left(\begin{matrix}
        ac & a^2b \\
        0 & ac  \\
        \end{matrix}\right)
$$
$det(ABA^{-1})$ = $det(A)$ $det(B)$ $det(A^{-1})$ = $det(A)det(A^{-1})$ = $1$.
And $det(ABA^{-1})$= $(ac)^2$, so $(ac)^2$ = $1$ which means that $ac$ = $ \pm 1$ and not only $1$. so how can we conclude that $ABA^{-1}$ $\in$ $H$?
Comment: Two comments: A) The $b$ parameters in $A$ and $B$ are not necessarily equal. B) You made an error in calculating $A^{-1}$.
Comment: Check your $A^{-1}$ again
Comment: Oh, right! I made a mistake in calculating $A^{-1}$.
Answer: An alternative approach to proving a subgroup is normal is to prove
that it's a kernel of some homomorphism. How about
$$\pmatrix{a&b\\0&c}\mapsto\pmatrix{a&0\\0&c}?$$
Is this a homomorphism? If so, what's its kernel?
Comment: A better approach! An even simpler homomorphism would be to map that matrix $\mapsto a$. Oops. That doesn't work. I have used $SL_2$ too often as of late. :-)
Comment: Ummm I'm not familiar with this method. But what should be the homomorphism's domain and codomain to apply this approach?
Comment: The domain would be $G$ of course; as for the codomain, well that has to be a suitable matrix group....
Comment: But finding such a homomorphism is not easy. I think it needs a lot of practice. So we can apply this to other questions by taking our $G$ as a domain, but we can take any codomain?


Leitura de ficheiros em Java

Question: public static void loadfile(stock []a) throws IOException{

        String fich;
        File fichDad;
        int i=countDatas(a);

        while(sc.nextLine().length()!=0);
        do{
            System.out.print("\nQual é o nome do ficheiro que deseja ler?\n");
            fich=sc.nextLine();
            fichDad = new File(fich);
        }while(!fichDad.canRead()||!fichDad.exists()||!fichDad.isFile());

        Scanner lerFil = new Scanner (fichDad);

        while (lerFil.hasNextLine()){
            if(i==100) break;
            if(!lerFil.hasNext()) break;;

            a[i]=new stock();
            a[i].nome=lerFil.next();
            a[i].quant=lerFil.nextInt();
            i++;
        }

        System.out.print("\n\n\nValores inseridos com sucesso!\n\n\n\n");

        lerFil.close();

}

Eu estou a fazer um exercício que consiste num programa (em Java) para manutenção de stock numa loja. O programa está a funcionar, mas tem um "problema" que não consigo resolver. O programa faz todas as operações corretamente e depois o progresso feito pode ser guardado num ficheiro, ficheiro esse que pode depois ser lido e carregado para o programa para retomar o progresso. No entanto, se ler o ficheiros duas vezes seguidas, em vez de apagar o que tem na memória e escrever por cima, a função apresenta duas vezes o conteúdo do ficheiro. Alguém tem uma solução?
Comment: pode compartilhar o seu código que faz a leitura?
Comment: peço desculpa, tinha me esquecido de adicionar. ja adicionei
Comment: O que é `countDatas(a)`?
Comment: De onde vem a variável `sc`? Porque você limpa toda a entrada dela?
Comment: countDatas(a) é uma funçao que conta o numero de elementos no array. sc é o scanner
Answer: Você pode reescrever sua classe Stock assim:
import java.io.File;
import java.io.Scanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Stock {
    private final String nome;
    private final int quantidade;

    public Stock(String nome, int quantidade) {
        this.nome = nome;
        this.quantidade = quantidade;
    }

    public String getNome() {
        return nome;
    }

    public int getQuantidade() {
        return quantidade;
    }

    public static List<Stock> loadFile(Scanner sc) throws IOException {
        // Limpa o sc.
        while (!sc.nextLine().isEmpty());

        File ficheiro;
        do {
            System.out.print("\nQual é o nome do ficheiro que deseja ler?\n");
            String nomeFicheiro = sc.nextLine();
            ficheiro = new File(nomeFicheiro);
        } while (!ficheiro.exists() || !ficheiro.isFile() || !ficheiro.canRead());

        List<Stock> lista = new ArrayList<>();
        try (Scanner leitor = new Scanner(ficheiro)) {
            for (int i = 0; i < 100 && leitor.hasNext(); i++) {
                String nome = leitor.next();
                int quantidade = leitor.nextInt();
                Stock s = new Stock(nome, quantidade);
                lista.add(s);
            }
        }

        System.out.println("Valores inseridos com sucesso!");

        return lista;
    }
}

Observe que ele sempre devolverá uma nova lista de Stock contendo o conteúdo do arquivo. Use o try-with-resources e siga convenções de código.
Para substituir então a lista, basta fazer isso:
Scanner sc = new Scanner(System.in);

// Primeira vez.
List<Stock> lista = Stock.loadFile(sc);

// ...Um monte de código aqui...

// Segunda vez.
lista = Stock.loadFile(sc);

Comment: muito obrigado!
Comment: mas nao existe maneira de fazer sem usar construtores e listas?
Comment: @MartimNeves Certamente que existe. Você pode usar arrays no lugar de listas (inclusive você usava) ou bolar a sua própria estrutura de dados equivalente para guardar a sequência de dados e pode construir objetos chamando os setters posteriormente ou diretamente nos atributos (tal como você fazia). Entretanto, não recomendo nenhuma dessas abordagens, motivo pelo qual fiz a resposta exatamente dessa forma. Trabalhar com arrays é algo um tanto difícil e listas são muito mais flexíveis e fáceis de se lidar. Quanto a usar os construtores, deve-se a isso: https://pt.stackoverflow.com/a/252986/132
Comment: muito obrigado!

Leitura de ficheiros em Java


Sufficient conditions for measurable sample-paths?

Question: If we have a stochastic process $\{X_t\}$ on a filtered probability space $(\Omega, \mathcal{F},P,\mathbb{F})$. The integral process $\int_0^t|X_s|ds$ often comes up in stochastic analysis. But in order for this process to be well-defined the sample-paths have to be lebesgue-meausrable? What are sufficient conditions for this to happen?
I guess it is easy to see adaptiveness is not enough, by choosing a non-measurable function, deterministic. But is joint-measurability enough? That is, if the process is: $\mathcal{B}(\mathbb{R}_+)\times \mathcal{F}$-measurable? Is progressive measurability enough? I know that cádlag is enough, but this seems too strong, because it seems that one often needs the integral of processes which are not cádlág.
The problem I have with joint measurability is that it is ok if each singleton $\{\omega\}$ is $\mathcal{F}$-measurable. But does this need to be the case?, even if $\mathcal{F}$ is complete? Is it possible to show that if the process is jointly measurable, then a.s. it has measurable sample-paths?
Answer: Yes, jointly measurable is sufficient.  This is one of the assertions of Fubini's theorem: if $f(x,y)$ is jointly measurable on the product of two $\sigma$-finite measure spaces, then the section $f(\cdot, y)$ is measurable for every $y$.
You don't need completeness of $\mathcal{F}$ nor measurability of singletons, and if you're assuming joint measurability with respect to the product $\sigma$-field $\mathcal{B}(\mathbb{R}^+) \times \mathcal{F}$, then in fact you get that the sample paths are Borel.
Comment: Thank you very much! Just one quick question, when I looked up this in my book it seem it would hold for all y, not just almost every y, do you agree?
Comment: @user119615: Yes, you're right.  I was thinking of something else.


$\chi^2$ tests to compare the fit of large samples logistic models

Question: Does anyone know of any $\chi^2$ tests to compare the fit of logistic models which factor out the sample size? I'm dealing with a very large sample and I fear the significant $\chi^2$ test I get when adding a single variable to the model is simply the result of the sample size (>200,000 cases). I'm doing what is known as differential item functioning analysis with logistic regression. Basically it's as if I'm checking whether giving the right answer to a question (dependent variable) depends on your ethnicity when controlling for the total exam score.
Model 1 Q1~TotalexamScore
Model 2 Q1~TotalexamScore+ Group
I'm basically using a chi-squared test to compare model1 to model2. The coefficient significance is not that important but $\chi^2$ and sometimes $R^2$ are generally recommended to check differential item functioning. My problem is that my sample is very large. In theory (for the question I'm considering) there should be no real difference across groups, so I suspect it's simply the sensitivity of the $\chi^2$ to sample size.
I'd rather use the whole dataset instead of taking (small) random samples as it is highly skewed. I've seen things like Phi and Cramer's V for crosstabs but I'm not sure whether they have been used before on logistic regression, if there are better ones and if there are any packages (I generally use Spss, Mplus, Stata, R).
Comment: I've added a link describing DIF so that people get a better idea of what you are really testing. In your case, as you do not consider any interaction between trait level and group, an LRT of M1 vs. M2 will assess *uniform DIF*. And +1, this is a good question.
Answer: One hueristic way you can take account of sample size is to make a random group variable which has the same marginal propensity as your "Group" variable.  Then check the chi square statistic for this random group.  If it's greater than the chi square for your variable then you have a fair case to dismiss the effect as noise.  A more robust version would be to create many noise variables and see if any of their chi square statistics are greater than the chi square for your variable.
Another thing you should do is examine the beta coefficients or "effect sizes" for the "Group" variable.  Do they make intuitive sense?  For example can you explain why a coefficient should be positive or negative?  Can you explain why the magnitude of the coefficient should be bigger or smaller than the other coefficients?
As far as more formal tests go I would recommend BIC as it tends to be conservative.  If BIC favours the larger model, then just about any other test will.  This usually means "low power" when the sample size is small, but your sample size is large.  You can show that using BIC is approximately the same thing as setting the p-value for significance in a likelihood ratio chi square test equal to $Pr(\chi_q^2>q\log[N])$ where $q$ is the number of additional parameters in the larger model.
Comment: Thank you. I particularly like the interpretation of the chi-square in terms of BIC.
Answer: Any test of statistical significance will be sensitive to sample size, that's one of the problems with statistical significance measures.
There are alternatives:
1) Point out just what you did above: Present the chi-square statistic and note its significance but then discuss the size of the effect of adding group.
2) Use a measure that accounts for model complexity (e.g. AIC, AICC, BIC). These may show that the simpler model is better, despite the huge sample size. However, AFAIK, the difference in AIC doesn't yield a p-value.
and probably other things as well.
Comment: Because the penalty in AIC does not vary with the sample size I would have thought it would be subject to the same problem as ordinary significance testing - the saturated model will eventually be favoured if the sample is made big enough.
Comment: I am not sure. Does loglikelihood change systematically with sample size?
Comment: my thinking was that AIC corresponds in regression to setting your significance level to 0.15 - regardless of the sample size. And Im pretty sure all fixed significance levels are eventually passed for a large enough sample.
Comment: How could AIC correspond to a particular significance level? I don't understand
Comment: if you're comparing two nested hypothesis which are one parameter different, then you come to the same conclusion as someone who use a LR test with p value of $0.15$ and this does not depend on the sample size.  They both accept the more complex model if the likelihood ratio is above the same threshold independent of the sample size.
Answer: You should realize that the statistical power is not going to be determined by the number of cases, but rather by the number of events (or the smaller of the 0/1 categories). There are a variety of goodness of fit statistics that have been proposed. I generally avoid them, since I am more interested in looking at effect magnitudes rather than in global fit. I generally set my threshold for considering differences in the model X^2 much higher when working on large data. My data is on the order of 10 times as large as yours but with only 1% of cases being events. In that context I find that models with X^2 differences of 10 or less with one degree of freedom generally have very little meaningful difference when examined for effect differences. And I also require a X^2 difference of 30 when I know if have done extensive multiple testing.
Along the same lines, when doing model comparison with large datasets, you should be using penalization that takes into account the number of model comparisons. I sometimes figure my degrees of freedom are in the range of 50-100 considering the number of different models I have examined.  You will have the opportunity to examine non-linearity and the potential for interactions, and you should definitely avail yourself of that possibility. And you should consider the search for non-linearity in your estimates of the number of degrees of freedom needed. There is general agreement in the R-help community that Frank Harrell's text "Regression Modeling Strategies" has excellent discussions on these points, and I am basically repeating things I learned from Frank. (I do hope I haven't misrepresented them.) The R 'rms' and 'Hmisc' packages implement the advice and methods Harrell recommends.
This is the list of potential "model metrics" that Harrell's lrm function will offer:
model likelihood ratio chi-square, d.f.,
P-value,
c index (area under ROC curve),
Somers' D_{xy},
Goodman-Kruskal gamma,
Kendall's tau-a rank correlations between predicted probabilities and observed response,
Nagelkerke R^2 index,
Brier score computed with respect to Y > its lowest level,
g-index,
gr (the g-index on the odds ratio scale),
gp (the g-index on the probability scale using the same cutoff used for the Brier score).

As I said I generally am considering comparing penalized LR statistics, but the Nagelkerke pseudo-R^2 should be somewhat free of sample-size inflation.
Comment: What the OP didn't say, unfortunately, is that the kind of model he is interested in is generally of the form $f(\text{response}\mid\text{trait level},\text{group})=\beta_0+\beta_1\cdot\text{trait level}+\beta_2\cdot\text{group}$, meaning that response is conditioned on individual trait level (usually, assumed to be a latent variable). This amounts to consider a mixed-effect logistic regression, as our (psychometric) measurement model. An alternative approach is to use raw scores stratified by levels of total score, which amounts to rely on some variant of the Mantel-Haenszel test.


Relation between field of two webform

Question: I have created two webform as Vendor and Sponsors.There is two sponsorship type as gold and platinum in sponsors and each vendor is sponsors. Now i want to show in Vendor view the type of sponsorship this vendor have. Both are separate modules. I am not able to understand how to do this.
Comment: I would consider using regular content types for this instead. Webforms are great for signups, surveys etc. But with real content types you can use modules such as entity reference to build this functionality.
Comment: Why do you need this to be webforms? If they were ordinary content types you could use the module entity reference to reference the vendor from the sponsor.
Comment: Actually there are  separate registration form for both vendors and sponsors and i have used web forms for that
Comment: I am newbie in drupal so i dont have much idea about these concepts early so i have choose webforms for this and now stuck into these
Answer: As far as I know you can not reference a webform submission from another webform. The functionality you describe is needed here is something I recommend using standard Drupal content types for.
Create a content type called Vendor and another one called Sponsor. Use the module Entity reference to create a field that describes the reference between the content types.
Webforms are great for simple forms, surveys etc but not in this use case.

Relation between field of two webform


Php foreach loop, add to different div depending on if/else

Question: My current code:
<?php if($_images){?>
    <?php $i=0; foreach($_images as $_image){ $i++; ?>
        <?php if($i > 2) { ?>

                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(600,900); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php $this->htmlEscape($_image->getLabel());?>" />

        <?php } else { ?>

            <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(450,675); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php $this->htmlEscape($_image->getLabel());?>" />

        <?php } ?>

    <?php } ?>
<?php } ?>

So this is obviously wrong since every time an image is echo'ed it's assigned to a different div (same name but different). Is it possible to assign echoes to certain div depending on the count?
For example, first two images will be assigned to the smallPic div, then the rest will be in the largePic div.
Comment: Just put the divs outside the foreach and use 2 foreach instead (removing pictures in the $_images array when its assigned to a div).
Comment: And what is wrong now?
Comment: The problem now is that the first two images are read as two different divs so they line up on top of each other instead of right next to each other. @u_mulder
Comment: Sounds like that is more of a styling issue than a PHP issue. Why not use CSS to make them appear next to each other?
Comment: I could but it's still pretty messy seeing a bunch of divs under the same name occupying the space. If it's possible I want them to be group under one div.
Answer: What you want is to first devide your array into two arrays and then foreach through both of them.
<?php

$largeImages = array();
$smallImages = array();

foreach ($_images as $k => $v) {
    if ($k > 2) {
        $largeImages[] = $v;
    } else {
        $smallImages[] = $v
    }
}
?>

<?php foreach ($largeImages as $_image) { ?>
    <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(600,900); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php $this->htmlEscape($_image->getLabel());?>" />
<?php } ?>

<?php foreach ($smallImages as $_image) { ?>
    <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(450,675); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php $this->htmlEscape($_image->getLabel());?>" />
<?php } ?>

Answer: Process the images first (storing the HTML for each image in either an array or string) and then create the div elements- see example below. This will reduce the number of opening/closing tags immensely.
Also note that if the keys of the array are numeric then the following syntax can be used instead of creating an extra variable (i.e. $i) just to track the index (so as to avoid extra bookkeeping like incrementing the variable - one of the major benefits of foreach compared to a for statement).

foreach (array_expression as $key => $value)
            statement 1

<?php
$largePic = '';
$smallPic = '';
if($_images){
    foreach($_images as $i => $_image){
        if($i > 2) {
           $largePic .= 'helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(600,900).'" alt="'. $this->htmlEscape($_image->getLabel()). '" title="'. $this->htmlEscape($_image->getLabel()).'" />';
         } else {
            $smallPic .= 'helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(450,675). '" alt="'. $this->htmlEscape($_image->getLabel()). '" title="'. $this->htmlEscape($_image->getLabel()). '" />';
        }
    }
 } ?>

<?php echo $largePic; ?>

<?php echo $smallPic; ?>

Answer: I'm not in PHP but I'm quite sure for start you can loose those extensive open/close tags (<?php ?>) and replace it with only one at the start and the end. This is hardly readable.
Then, like in many server side scripts, what you need is some kind of buffer containing HTML which you will output at the end of loop. Because what you're doing now is outputting from inside the loop, this sending multiple DIVs to client.
Create largePic nad smallPic variables contianing DIVs HTML, and append HTML to it inside loop (instead outputing it to client like you do now). Then, after loop is finished, output those two variables to client.


How to create a session in node.js with jade

Question: I made a login for admin panel and now i want to implement the session.
I was searching alot but could not find How to implement the sessions in node.js. Simply i want to store the token when i login from admin panel and for logging out the session will be destroyed. Please help.
Here is my login code:
<code>`use strict`

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../../user/auth/storage/model/User');
const userPopulation = require('../../user/auth/storage/populate/userPopulation');
var loginServices = {};

loginServices.login = (req, res, next) => {
    // var rollno = param.rollno.toLowerCase()
    // var email = req.body.email
    // console.log(email);
    return User.findOne({ email: req.session.email })
        .then(user => {
            console.log(user)
            if (user && bcrypt.compareSync(req.body.password, user.password)) {
                if (user.role == 'admin') {
                    const token = authToken(user)
                    res.render('../views/home', { token: token, user: user });
                } else {
                    res.redirect('/auth/login');
                }
            }
            else {
                res.redirect('/auth/login');
                // return Promise.reject(ES.authError('Authentication Failed'))
            }
        })
}

const authToken = (user) => {
    return jwt.sign(
        {
            email: user.email,
            _id: user._id,
            role: user.role
        },
        process.env.SECRET_KEY,
        {
            expiresIn: process.env.TOKEN_EXPIRY_TIME
        }
    )
}

module.exports = loginServices;
</code>
Here is the snippet of app.js:
<code>require('dotenv').config();
const express = require('express');
const path = require('path');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.Promise = Promise;

app.use(morgan("dev"));
app.use('/uploads', express.static('uploads'));
app.use(session({
    secret:'sssshhh',
    saveUninitialized: true,
    resave: true
}))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({
    // Because Stripe needs the raw body, we compute it but only when hitting the Stripe callback URL.
    verify: function(req,res,buf) {
        var url = req.originalUrl;
        console.log('------------'+url);
        if (url.startsWith('/notify_transaction_success')) {
            req.rawBody = buf.toString();
        }
    }}));
app.use(express.static(path.join(__dirname, '../public')));
</code>
I do alot of search but i could not find any solution. Please help me.
Answer: I, basically, followed this step by step to get my sessions up and running with only some slight modification to how the session is stored.
https://medium.com/@evangow/server-authentication-basics-express-sessions-passport-and-curl-359b7456003d
After you are up and running, you can insert a if( req.isAuthenticated() ) into your middleware for routes and you are laughing.
Comment: Also, I didn't use cURL for testing, I just did it in the browser.
Comment: I thinks thats manage session from server side but i want to store token in client side with jade template engine @David Duffy
Comment: When you create a session, it does store a cookie on the client. You can set the terms for how long it is until expired. So, once you have authenticated, it is authenticated. Jade is an engine for quickly and cleanly producing web content.


Getting the ServletContext

Question: I wonder as calling a bean in Spring MVC web. I tried to call this class but i do not know how to pass the ServletContext. This is the code.
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext (sc);
Servicio servicioB= (Servicio) ctx.getBean("servB",Servicio.class);

How do I get the ServletContext?.
Answer: Use below steps -

Autowire ServletContext object
@Autowired
    ServletContext context;
get ServletContext object in controller class
private ServletContext context;
public void setServletContext(ServletContext servletContext) {
     this.context = servletContext;
}

Note : You must have implement ServletContextAware interface in controller class.
Comment: There is no way how to do it from the controller without using annotations, I'm starting with Spring.

I have seen examples that use Servlets for the ServletContext with the method getServletContext ()
Comment: An easier way of doing this is using the annotation Qualifier example: public class IndexController {
    @Autowired
    @Qualifier("servB")
    private Servicio servicio;
    System.out.printl(""+Servicio.getMensaje());
}

Getting the ServletContext