in-sample and out of sample forecasting plot look very different

Question:
why the in-sample looks very different from the out-of-sample? Is the in-sample overfitting? Horizon is 12, using pycaret time series function.
Answer: This is a common issue in forecasting.  It appears pycaret is using a simple random walk modelas the naive, where the prediction for each point is equal to the actual from the previous point.  With other models, the issue is close to being the same thing, so it's worth going into the random walk model in depth.
For in-sample, random walk models will have the last actual value, and it will use it for the prediction.
For out-of-sample, the actuals are not available.  Random walk will use the last actual to predict the next point.  For subsequent points, an immediately previous actual is not available, so it will use the predicted from previous points.  This means the last in-sample point will be the prediction for the entire out-of-sample set.
Comment: Again, it's because it can correct for each previous actual for the in sample. For the out of sample, it just has to fly blind.
Comment: Thanks! How about the two ARIMA? My understanding is that in the in-sample, they are overfitting, and for out-of-sample, the next 12 month forecasting are just some results of ARIMA with some seasonality components.  How the two ARIMA can be so good in fitting the in-sample though? Lol.


Como capturar erro do mysql (duplicate entry) e exibir uma mensagem na tela para o usuário, usando o codeigniter?

Question: Como capturar o erro do mysql (duplicate entry) e exibir uma mensagem na tela para o usuário, usando o codeigniter?

Error Number: 1062
Duplicate entry '123456' for key 'processo'
INSERT INTO processo (nprocesso)
Filename: C:/xampp/htdocs/aplicacao/system/database/DB_driver.php
Line Number: 691
Answer: A solução para esse problema é pegar o sqlstate e verificar se ele é 1062 (Duplicate entry). Use o método error() em caso de falha ele retorna um array com o código e a descrição do erro.
Seu código deve ser algo como:
$msg = '';
if(!$this->db->query('INSERT....')){
   $error = $this->db->error();
   if($error['code'] == 1062){
      $msg = 'Registro duplicado';
   }
}

Para que o CI não exiba essa mensagem de erro gigante você pode desabilitar isso via arquivo de configuração application/config/database.php mudando a seguinte configuração para false.
Antes/original:
'db_debug' => (ENVIRONMENT !== 'production')

Depois:
'db_debug' => false

Também possível fazer isso em trechos especificos via código, basta alterar o valor da propriedade db_debug
$msg = '';
$this->db->db_debug = false;
if(!$this->db->query('INSERT....')){
   $error = $this->db->error();
   if($error['code'] == 1062){
      $msg = 'Registro duplicado';
   }
}
$this->db->db_debug = true;

Comment: Obrigado pela resposta, mas não funcionou, continua aparecendo "A Database Error Occurred", estou usando mysql.

Error Number: 1062

Duplicate entry '123456' for key 'processo'

INSERT INTO processo (nprocesso)

Filename: C:/xampp/htdocs/aplicacao/system/database/DB_driver.php

Line Number: 691
Comment: @Ramiro a mensagem de erro aparece ainda pq seu ambiante está configurado como dev, quando mudar para produção não sera exibido. Tem uma forma de desligar isso via código, posso complementar isso na resposta.
Comment: pode sim, por favor.
Comment: @Ramiro editei a respostas.
Comment: Depois que você falou eu consegui. Muito obrigado!


Generate a new string

Question: So I have code that when you press the mouse it will generate some random code in a text box, then when enter is hit, it is suppose to clear said textbox and replace is with a new random string but it just picks the same random string. E.g. I click the mouse and "hps" is generated, I click enter and "hps" is generated again. Is there a way to get a new string from my generator?
        public void mouseClicked(MouseEvent arg0) {
            RandSt string = new RandSt();
            textField_tf.setText(string.randStr());
            }

Comment: Show your `RandSt()` method.
Comment: Move your static class attribute `chosen` into the randStr() method (as a method variable) and you should be fine.
Comment: what is the code inside RandSt.randStr() ?
Comment: I've added it :)
Answer: chosen is not reset after generating a String. A very simple solution would just be to add this one line at the start of your method:
chosen = "";

I would advise however, to use a completely different method, for example the one explained here:
import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator {
    private SecureRandom random = new SecureRandom();

    public String nextSessionId() {
        return new BigInteger(130, random).toString(32);
    }
}

Comment: You noticed that he is using Java, right? - Your advise wont compile;)

Generate a new string


sbt.ResolveException: unresolved dependency: org.apache.spark#spark-core_2.11;2.1.2: not found

Question: I want to use the connected components algo in spark 2.0. However, the packaging with sbt 0.13.15 got dependency errors. What's the cause behind this? The build.sbt file is like this:
lazy val root = (project in file(".")).
settings(
   name := "Networkana",
   version := "1.0",
   scalaVersion := "2.11.8",
   libraryDependencies ++= Seq(
       "org.apache.spark" %% "spark-core" % "2.1.2" % "provided",
       "org.apache.spark" %% "spark-sql" % "2.1.2" % "provided",
       "org.apache.spark" %% "spark-hive" % "2.1.2" % "provided",
       "org.apache.spark" %% "spark-hive-thriftserver" % "2.1.2" % "provided",
      "org.apache.spark" %% "spark-mllib" % "2.1.2" % "provided",
      "graphframes" % "graphframes" % "0.5.0-spark2.1-s_2.11",
      "org.apache.spark" %% "spark-graphx" % "2.1.0",
      "joda-time" % "joda-time" % "2.7",
      "org.joda" % "joda-convert" % "1.7"
      )
  //resolvers ++= Resolver.url("SparkPackages", url("https://dl.bintray.com/spark-packages/maven/"))
  )

Spark 2.0.0 is failing with:
[warn] Executing in batch mode.
[warn]   For better performance, hit [ENTER] to switch to interactive mode, or
[warn]   consider launching sbt without any commands, or explicitly passing 'shell'
[info] Loading project definition from /data/mop_strategy_group/machine_learning/AlgorithmsCodes/Networkana/project
[info] Updating {file:/data/mop_strategy_group/machine_learning/AlgorithmsCodes/Networkana/project/}networkana-build...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Set current project to Networkana (in build file:/data/mop_strategy_group/machine_learning/AlgorithmsCodes/Networkana/)
[info] Updating {file:/data/mop_strategy_group/machine_learning/AlgorithmsCodes/Networkana/}root...
[info] Resolving org.apache.spark#spark-graphx_2.11;2.1.0 ...
[error] Server access Error: Connection refused (Connection refused) url=https://repo1.maven.org/maven2/org/apache/spark/spark-graphx_2.11/2.1.0/spark-graphx_2.11-2.1.0.pom
[warn]  module not found: org.apache.spark#spark-graphx_2.11;2.1.0
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-graphx_2.11/2.1.0/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-graphx_2.11/2.1.0/spark-graphx_2.11-2.1.0.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-graphx_2.11/2.1.0/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-graphx_2.11/2.1.0/spark-graphx_2.11-2.1.0.pom
[info] Resolving org.apache.spark#spark-core_2.11;2.1.2 ...
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-core_2.11/2.1.2/spark-core_2.11-2.1.2.pom
[warn]  module not found: org.apache.spark#spark-core_2.11;2.1.2
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-core_2.11/2.1.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-core_2.11/2.1.2/spark-core_2.11-2.1.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-core_2.11/2.1.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-core_2.11/2.1.2/spark-core_2.11-2.1.2.pom
[info] Resolving org.apache.spark#spark-sql_2.11;2.1.2 ...
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-sql_2.11/2.1.2/spark-sql_2.11-2.1.2.pom
[warn]  module not found: org.apache.spark#spark-sql_2.11;2.1.2
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-sql_2.11/2.1.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-sql_2.11/2.1.2/spark-sql_2.11-2.1.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-sql_2.11/2.1.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-sql_2.11/2.1.2/spark-sql_2.11-2.1.2.pom
[info] Resolving org.apache.spark#spark-hive_2.11;2.1.2 ...
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-hive_2.11/2.1.2/spark-hive_2.11-2.1.2.pom
[warn]  module not found: org.apache.spark#spark-hive_2.11;2.1.2
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-hive_2.11/2.1.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-hive_2.11/2.1.2/spark-hive_2.11-2.1.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-hive_2.11/2.1.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-hive_2.11/2.1.2/spark-hive_2.11-2.1.2.pom
[info] Resolving org.apache.spark#spark-hive-thriftserver_2.11;2.1.2 ...
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-hive-thriftserver_2.11/2.1.2/spark-hive-thriftserver_2.11-2.1.2.pom
[warn]  module not found: org.apache.spark#spark-hive-thriftserver_2.11;2.1.2
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-hive-thriftserver_2.11/2.1.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-hive-thriftserver_2.11/2.1.2/spark-hive-thriftserver_2.11-2.1.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-hive-thriftserver_2.11/2.1.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-hive-thriftserver_2.11/2.1.2/spark-hive-thriftserver_2.11-2.1.2.pom
[info] Resolving org.apache.spark#spark-mllib_2.11;2.1.2 ...
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-mllib_2.11/2.1.2/spark-mllib_2.11-2.1.2.pom
[warn]  module not found: org.apache.spark#spark-mllib_2.11;2.1.2
[warn] ==== local: tried
[warn]   /data/mop_strategy_group/.ivy2/local/org.apache.spark/spark-mllib_2.11/2.1.2/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/apache/spark/spark-mllib_2.11/2.1.2/spark-mllib_2.11-2.1.2.pom
[warn] ==== local-preloaded-ivy: tried
[warn]   /data/mop_strategy_group/.sbt/preloaded/org.apache.spark/spark-mllib_2.11/2.1.2/ivys/ivy.xml
[warn] ==== local-preloaded: tried
[warn]   file:////data/mop_strategy_group/.sbt/preloaded/org/apache/spark/spark-mllib_2.11/2.1.2/spark-mllib_2.11-2.1.2.pom
[info] Resolving jline#jline;2.12.1 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.spark#spark-graphx_2.11;2.1.0: not found
[warn]  :: org.apache.spark#spark-core_2.11;2.1.2: not found
[warn]  :: org.apache.spark#spark-sql_2.11;2.1.2: not found
[warn]  :: org.apache.spark#spark-hive_2.11;2.1.2: not found
[warn]  :: org.apache.spark#spark-hive-thriftserver_2.11;2.1.2: not found
[warn]  :: org.apache.spark#spark-mllib_2.11;2.1.2: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]      org.apache.spark:spark-mllib_2.11:2.1.2 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
[warn]      org.apache.spark:spark-graphx_2.11:2.1.0 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
[warn]      org.apache.spark:spark-hive_2.11:2.1.2 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
[warn]      org.apache.spark:spark-sql_2.11:2.1.2 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
[warn]      org.apache.spark:spark-core_2.11:2.1.2 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
[warn]      org.apache.spark:spark-hive-thriftserver_2.11:2.1.2 (/data/mop_strategy_group/wuzj_spark/Networkana/build.sbt#L6)
[warn]        +- networkana:networkana_2.11:1.0
sbt.ResolveException: unresolved dependency: org.apache.spark#spark-graphx_2.11;2.1.0: not found
unresolved dependency: org.apache.spark#spark-core_2.11;2.1.2: not found
unresolved dependency: org.apache.spark#spark-sql_2.11;2.1.2: not found
unresolved dependency: org.apache.spark#spark-hive_2.11;2.1.2: not found
unresolved dependency: org.apache.spark#spark-hive-thriftserver_2.11;2.1.2: not found
unresolved dependency: org.apache.spark#spark-mllib_2.11;2.1.2: not found
at sbt.IvyActions$.sbt$IvyActions$$resolve(IvyActions.scala:313)
at sbt.IvyActions$$anonfun$updateEither$1.apply(IvyActions.scala:191)
at sbt.IvyActions$$anonfun$updateEither$1.apply(IvyActions.scala:168)
at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:156)
at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:156)
at sbt.IvySbt$$anonfun$withIvy$1.apply(Ivy.scala:133)
at sbt.IvySbt.sbt$IvySbt$$action$1(Ivy.scala:57)
at sbt.IvySbt$$anon$4.call(Ivy.scala:65)
at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:93)
at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:78)
at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:97)
at xsbt.boot.Using$.withResource(Using.scala:10)
at xsbt.boot.Using$.apply(Using.scala:9)
at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:58)
at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:48)
at xsbt.boot.Locks$.apply0(Locks.scala:31)
at xsbt.boot.Locks$.apply(Locks.scala:28)
at sbt.IvySbt.withDefaultLogger(Ivy.scala:65)
at sbt.IvySbt.withIvy(Ivy.scala:128)
at sbt.IvySbt.withIvy(Ivy.scala:125)
at sbt.IvySbt$Module.withModule(Ivy.scala:156)
at sbt.IvyActions$.updateEither(IvyActions.scala:168)
at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1488)
at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1484)
at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$121.apply(Defaults.scala:1519)
at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$121.apply(Defaults.scala:1517)
at sbt.Tracked$$anonfun$lastOutput$1.apply(Tracked.scala:37)
at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1522)
at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1516)
at sbt.Tracked$$anonfun$inputChanged$1.apply(Tracked.scala:60)
at sbt.Classpaths$.cachedUpdate(Defaults.scala:1539)
at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1466)
at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1418)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
at sbt.std.Transform$$anon$4.work(System.scala:63)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
at sbt.Execute.work(Execute.scala:237)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
[error] (*:update) sbt.ResolveException: unresolved dependency: org.apache.spark#spark-graphx_2.11;2.1.0: not found
[error] unresolved dependency: org.apache.spark#spark-core_2.11;2.1.2: not found
[error] unresolved dependency: org.apache.spark#spark-sql_2.11;2.1.2: not found
[error] unresolved dependency: org.apache.spark#spark-hive_2.11;2.1.2: not found
[error] unresolved dependency: org.apache.spark#spark-hive-thriftserver_2.11;2.1.2: not found
[error] unresolved dependency: org.apache.spark#spark-mllib_2.11;2.1.2: not found

Comment: This might be a temporary error, the URL is available for me, now. Try again.
Comment: Thanks, Karl. I tried it again and sbt still got the same error. Could it be caused by sbt?
Answer: I see this line:
[error] Server access Error: Received fatal alert: protocol_version url=https://repo1.maven.org/maven2/org/apache/spark/spark-hive-thriftserver_2.11/2.1.2/spark-hive-thriftserver_2.11-2.1.2.pom

It seems like you're trying to connect with a Java version that doesn't support TLSv1.2 (or is not enabled)
Please read Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central? for the complete answer and how to solve it.


Why bother proving that a class is a set?

Question: Fix a set theory, say ZFC. Now suppose you have a statement $P(x)$ written in the language of that theory, which has precisely one free variable $x$. We can conceive of the class of all $x$ in the domain of discourse such that the statement $P(x)$ holds. It is my understanding that this class may or may not itself correspond to an object in the domain of discourse. My questions are as follows. Firstly, suppose that it does correspond to an object in the domain of discourse, well what do we gain by proving that this is the case? And secondly, if the class of all such objects does not correspond to an object in our domain of discourse, what are we NOT allowed to do with this class which we would perhaps like to be able to do?
Now firstly, let me apologize in advance if my conceptualization above is either imprecise, or founded on false assumptions. My experience is limited to naive set theory, and I have no model theory under my belt.
Secondly, let me provide some background context for my question.
Suppose I have a unary function $f$ and I want to speak of the set of all sets that are closed with respect to $f$. We might write this as $\mathrm{clo}(f)$. My understanding is that even if $\mathrm{clo}(f)$ is defined only on 'small' functions $f$ (that is, those functions that are defined by a set of ordered pairs), nonetheless $\mathrm{clo}$ is going to be 'big'. Is this going to be a problem?
Now things get messier. I want to define a binary function $\curvearrowright$ such that for any object in the domain of discourse $x$ and any function $f$, we may write that $x \curvearrowright f = f(x)$. However, I don't want to limit this to small functions $f$. For instance, letting the object $x$ be replaced by a small function $g$, and letting $f$ be replaced by the large function $\mathrm{clo}$, I want to be able to write $g \curvearrowright \mathrm{clo}$ for the set of all sets that are closed with respect to $g$. Can this be done without introducing contradiction?
Comment: If a class is a set, then there are a lot more things you can do to it: you can form its powerset, take subsets of it, etc. As for your unary "function" $f$ – if $f$ is a "small" function, then $f$ has a domain of definition, so the set of all sets closed under $f$ is going to be a set.
Answer: Well, let us assume we are working in ZFC. In this case:

We are not allowed to quantify over classes which are not sets.
We cannot collect proper classes into other classes.
We cannot say that a class "exists".
We cannot use classes as parameters internally.

One of the main uses of set theory is to give a foundation to the rest of mathematics. If you cannot say that an object exists in your foundation, how can you delegate it to other theories? You can't. You can only talk about it as a syntactical construct, without any semantical meaning.
If you want to define the class $\operatorname{clo}(f)$ and $f$ itself is a class then your definition is not within the theory. Of course if you are not a set theorist it will probably interest you as much as it would interest you to know that I'm hungry right now. You should know, and you probably do, that there are ways around it like class-set theories or large cardinals.
Furthermore, if you define the operation for class functions and you want to talk about the collection of "all functions which have such and such closure" then you can only do that if these functions form a set. You cannot talk about a collection of classes, not in ZFC and not in NBG. You need to go another step to allow $2$-classes (classes of classes).
This form of iteration can go on for a while before it settles down and you find yourself with a large cardinal. It is somewhat necessary for some constructs in categories, but it is not always necessary otherwise.
Your $\curvearrowright$ function takes input of a function and a set. If the function is not a set, then $\curvearrowright$ cannot take it as input.
Comment: So would the best solution involve simply defining things as abbreviations? For example: If $f$ is a map (not necessarily set-like) with domain $X$ and if $x \in X$, we will use $x \curvearrowright f$ as shorthand for $f(x)$. If $f$ is a set-like map with domain $X$, we will write $f \curvearrowright \mathrm{clo}$ as shorthand for $\{U \subseteq X \,|\,\forall u(u \in U \rightarrow f(u)\in U)\}$.
Comment: @Yianni: You'll notice I changed your "answer" to a comment. I also combined the account you used to write the question with the account you used to write the "answer" (did you know they were different?).
Comment: @Yianni: Yes, that is one solution. Another is to use some trick which allows you to have classes as sets (large cardinals, for example).
Answer: One thing that you can do with a set is put a poset structure on it and use Zorn's Lemma, which is a very powerful technique in proving the existence of certain objects. The following is a false application of Zorn's Lemma that illustrates its usefulness and the necessity of proving set-hood.
Suppose you want to prove that any field $F$ has an algebraic closure. Consider the collection of all algebraic extensions of $F$ and order this collection by inclusion. It is easily seen that all of the conditions for Zorn's Lemma hold and that a maximal element is an algebraic closure. The only problem is that the collection is not a set and thus this proof is wrong. It can be corrected but it requires a bit more work to actually produce a set.
Now, the following example shows that a very similar variant of the 'proof' above can be construed that 'proves' nonsense. Consider now the collection of all sets and order it by inclusion. Again, the conditions of Zorn's Lemma are easily satisfied and a maximal element now gives us a set with the property that it is not properly contained in any other set, obviously nonsense.
Another thing one can do with a set is use it to index other sets and then take the cartesian product of the indexed family. If one instead uses a proper class to index some sets then the cartesian product may or may not exist and determining if exists or not can be very difficult. This type of importance in distinguishing between sets and proper classes is very general. Indeed, given any small category it is well known that if the category admits arbitrary (i.e., class indexed and not just set indexed) categorical products (of which the cartesian product of sets is a special case) then the category degenerates to a poset. This argument thus shows that in any category which is not a poset (the category of sets is an example of a non-poset category) there must exist a proper class indexed family of sets which has no product in the category. In contrast, many categories (that of sets included) have the property that any set indexed family of objects has a product in the category (more generally, all small limits and colimits exist in many categories but if all limits, or all colimits, exist then the category must be a poset).
Comment: There are class-forms of Zorn's lemma which are equivalent to Global Choice. Global choice is the most non-issue in set theory (you can always force it without adding new sets). Furthermore, if you are using large categories you need a better solution anyway.
Comment: @ Asaf   I'm not sure how that relates to what I said. Global Choice doesn't make any difference to the examples I gave on how to misuse Zorn's Lemma if one does not pay attention to the set-hood of the class. As for big categories, what do you mean by 'better solution'? Certain big categories have all small limits but not all limits, showing again where the distinction between set and class is important, which is, I think, what OP asked about.
Comment: Ittay, the class version of Zorn's Lemma asserts that if every chain is bounded then there is a maximal element. Note that if you consider the algebraic closure example, then the class has the same properties: every chain is bounded. Yes, there are class-many members but in fact every chain is of set-length, there are not even chains which are proper classes, so you can even give a medium-sized argument and not require the full blown class-form of Zorn's lemma which allows class-chains...
Comment: But wouldn't the same be true about the class of all sets ordered by inclusion? Every chain of set-length is bounded, thus (???) there exists a set that is not properly contained in any other set (in ZF)?
Comment: You are talking about $(V,\supsetneq)$ as an ordered class, or about $(V,\subsetneq)$? If the former, then note that a minimal element is $\varnothing$ which has no proper subsets; if the latter than it is not true, consider just the ordinals -- they form a class-length chain which has no upper bound.
Comment: I'm talking about (V,\subseteq). You said that in the case of the algebraic closure, having set-length chains bounded suffices to establish an algebraic closure, I'm asking about that same for (V, \subseteq). There too set-length chains are bounded, but there is no set which is not a proper subset of any other set.
Comment: I'm not sure why you are trying to use a class-form of Zorn's lemma to prove the existence of a *minimal* element. Note that a maximal element corresponds to "largest set". There is no largest set, but there are chains without an upper bound (yes, those are not set-length, but that is not important). The requirement is that every chain is bounded. Note that in $(V,\subseteq)$ this is clearly false. Whereas in the case of an algebraic closure every chain *is* bounded, and there are no chains of class-length at all.
Comment: I'm not trying to prove the existence of a minimal element. I'm pointing to the fact that you can't deduce, in an ordered class, from the existence of bounds for set-length chains that there exists a maximal element. Now, what you claim about the case of algebraic closure that the only chains are set-length is true but I don't see how to prove it without already knowing that the algebraic closure exists.
Comment: First, I claimed that you need the assertion that *every* chain in bounded. I merely remarked that in the alg. closure case it is sufficient to require every *set* chain is bounded. Secondly, your argument can be reduced to claiming "how can Zorn's lemma be used to prove the existence of an upper bound? We need to know there is an alg. closure to assert that". Note that in this aspect the proof is essentially the same: we just prove that the increasing union of alg. extensions is contained in an alg. extension. (cont...)
Comment: (...) The only difference from the usual case is that we do not limit the underlying sets. This still doesn't matter because we require the chains to be increasing in inclusion, and since they are of set-length we can use the axiom of union to produce an upper bound.
Comment: that will be fine if you can prove that in the class of algebraic extensions all chains are set-length. How do you do that?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4577/discussion-between-ittay-weiss-and-asaf-karagila)
Comment: First prove: algebraic extension over an algebraic extension is algebraic; there are only set many polynomials over your field. If you had a class-length chain, you would be able to find a proper class of polynomials. Now all chains are set-length; each bounded by its union. Class-form of Zorn yields a maximal element, this is a set by definition (otherwise it wouldn't be an element), and we can easily prove it is algebraically closed.
Comment: Of course there is only a set of polynomials over a fixed field $F$. But what stops you from having a class-long chain of alg. extensions of $F$? With each extension there are more polynomials to split. So you might as well end up with a proper class of polynomials, just not all with coefficients in the same field. Of course this doesn't happen but how do you see that?
Comment: You are aware that we are *fixing* both $F$ and the polynomials over $F$, right? Proving that algebraic extension of an algebraic extension of $F$ is itself an algebraic extension of $F$ suffices. It ensures us that even if the underlying set is different, we cannot be "that" far from $F$ in this aspect. There are only set many polynomials and only set many roots to each polynomial (actually finitely many), so there can only be set many new elements. Recall that for a collection here to be a chain, each is a proper extension of the other, so we have a proper class of roots, and polynomials.
Comment: yes, of course F is fixed. But a priori it is not sufficient to prove that you can split all polynomials over F in some algebraic extensions. An alg. closure for F is an alg. extensions K such that every polynomial over K has a root in K. Not just every polynomial over F has a root in K. So you fix F indeed, but then with each extension you need to consider, potentially, more and more polynomials to split.
Comment: Yes, but splitting new polynomial can be done by splitting *old* polynomial. That is the essence of the claim: algebraic extension of an algebraic extension is itself an algebraic extension.
Comment: shall we continue in chat?
Comment: I rather not. I have placed a self-imposed exile from the chat system here. I dislike it, a lot. If you're fed up with this argument via comments, we can remove it and call it a day.


Lag based numerical features or ID categorical variable?

Question: I have to develop a Machine Learning regression model to predict customer's delay in paying invoices. In addition to the invoice related variables, of course a very important variable is the customer.
One possibility is to use directly the customer as categorical predictor variable, an alternative solution is to use some customer related Lag Based Features, such as the number of invoices previously paid by the customer and the average delay on them.
Of course I can try both the methods and compare the accuracy (ID categorical variable vs lag based numerical features), but what are the implications, pros and cons of the 2 alternative approaches?
I did a Google search and I was impressed that I could not find any resources on this topic.
Answer: If you have a large number of customers and you can consider a linear model, you may choose to use a random effects term for customer.  Random effects are great for categorical variables with large number of levels.  Without them, you may see huge and unrealistic differences for different customers, especially if there isn't a lot of data for some of them.
You can also include lag terms for previous payment delay of the customers.  You may have to write some code to create these features.  Perhaps columns for (delay in customer's previous order) and (delay in customer's order 2 previous), ...
An interaction between the customer variable and the lagged variable will allow each customer to have their own contribution of this history.  However if you have a large number of customer and lag terms, this will explode the number of features.  I would start small and try only 2 lags to start.
An alternative to including multiple lags is to calculate the exponential moving average of the previous payment delays for each order within each customer.  For example using R function TTR::EMA. You will have to assume a value for the constant.  But this has the advance of less features, and smooth contribution from larger set of previous order information.
Comment: See also `forecast::ets` in R for a more advanced implementation of exponential smoothing models.


Where to learn x64 assembly from?

Question: Okay so I know C++, C#, Java and some other languages and I decided to learn assembly next but I feel like I've hit a solid brick wall right from the start. I just need someone to point me in the right direction.
Here are the questions:

I've been told that it's better to learn assembly from the internet than from books because assembly depends on your hardware and books are mostly outdated. Is that true?
I've got a 64 bit CPU and I'm using (or at least trying to use) FASM. Where do I find the necessary documentation?
I'm totaly confused because most of the tutorials I've seen don't even work for me. Is that because of the hardware differences? How do I find the right tutorials?
Can I run x86 and x32 assembly on my 64 bit computer?
Could you please be so kind and write me a simple program in assembly (that works on my PC) with a breakdown in the comments? I'm running 64 bit Windows 10 on my intel core i5 CPU. Please.
Comment: https://software.intel.com/en-us/articles/introduction-to-x64-assembly
Comment: https://www.youtube.com/watch?v=rxsBghsrvpI&list=PLKK11Ligqitg9MOX3-0tFT1Rmh3uJp7kA
great playlist to get you started
Comment: You could write simple programs in C, and have the C compiler output assembly source code. Use those as a basis. You didn't mention if you're running on Windows or some version of Linux. In the case of Windows, you can run 32 bit programs, but not 16 bit programs, on 64 bit versions of Windows. For 64 bit versions, you could use Virtual PC or perhaps something like dosbox.
Comment: If you have Windows 7 or later, you can get Visual Studio for Desktop express 2015 for free. This includes assembler for 32 bit (ml.exe) and for 64 bit (ml64.exe), and a good source level debugger.
Comment: Not often do I agree with the powers that be to close a question. However, boy is this a bad question! It is provoking to write a book, by asking comment about confused and conflicting remarks.
Comment: Hmm, so this needs improvement while questions about how to write "Hello World" are accepted?
Answer: I think this is a valid question. It can be a bit hard to find up to date information on assembler.

Yes. A lot of resources printed and online describe i386 (x86) assembler and not the new amd64 (x86_64). Many things have changed, e.g. function arguments used to be passed on the stack but now they are passed in registers. This applies both to Unix and Windows.
Basically, ensure you are reading about 64-bit assembly.
Why not try the online manual. Note that assemblers are not that different when it comes to simple stuff.
I don't have Windows but if you are having trouble with any specific program, you could ask about it here. You will need to post the actual failing program.
Yes but you have to link it against 32-bit libraries and use the 32-bit version of the Win32 API. But if you're starting out, why program in the 1980's when you can work with the modern instruction set?
Try this.

Also, if you are going to be programming in assembly, I strongly recommend you get a debugger. I use GDB which works well and is free, on Windows you get to use the Visual Studio debugger which is superb.
Comment: Advantage of not using a debugger is that rather than use the trial and error method of learning assembly (debuggers are great for that), you are forced to have a much better understanding of the assembly language for a particular architecture. These days I answer assembly language questions on SO and rather than take the time to try and compile it myself i usually inspect the code visually for bugs. If I had a choice between hiring someone who can't debug without a debugger and one who could (assume everything else is equal) I'd choose the latter.
Comment: The post encourages to learn about x64 assembly but both links in it go to x86 tutorials... what?
Comment: In the old days I remember debugging without a debugger. It is far less efficient but was still very doable.
Comment: @MichaelPetch I've also done it but would not recommend it when there are great free debuggers available.
Comment: @MichaelPetch agreed, but this was in response to a programmer who had never written a correct assembly program. Also, skill with assembly debugging carries over to C since you can now start understanding programs that you don't actually have the source code to. But I get your point.

Where to learn x64 assembly from?


Calculus of Variations - Function dependent of $y'$ only

Question: I completely understand the proof for the Euler-Lagrange equation for a general function $F(x,y,y')$. However, when I try to use the same proof technique on a function $F(y')$, I run into a curiosity that I can't seem to resolve.
So I want to choose a function $y(x)$ passing through points $x = a$ and $x = b$ which minimizes
$$I[y]=  \int_a^b F(y') dx.$$
Suppose $y*$ is such a function, then any function $y(x)$ can be written as
$$y^*(x)+eV(x),$$
where $e$ is a constant and $V(x)$ is some function of $x$ such that $[y-y^*]/e = V$. Thus the integral $I$ is now a function of $e$, and $I'(0) = 0$. To calculate $I'(e)$, we can take the derivative inside the integral, which is
$$\frac{dF}{dy'} \frac{dy'}{de} = \frac{dF}{dy'} V'.$$
Now here is where my confusion is: This integral needs to be $0$ for all $F$ and $V$ as long as $e=0$ ($y=y^*$), so it's fair to say that we can't count on $V$ being a constant (thus $V'$ being 0), and so we must have that $dF/dy' = 0$. However, if we use integration by parts, we get that the integrand is
$$\frac{d}{dx}\frac{dF}{dy'} V,$$
and since we can't count on $V$ being $0$,
$$\frac{d}{dx}\frac{dF}{dy'} = 0,\ \ \text{ or }\frac{dF}{dy'} = C.$$
The latter is also consistent with the Euler-Lagrange equation, so it's definitely correct.
So my question is this: Why can I not set $\frac{dF}{dy'} = 0$ before I do integration by parts, but I can after?
Comment: I am a bit confused here. Since  $V(x)$ is some function of $x$ such that $[y-y^*]/e = V$, it implies that $V(x)$ is also a function of e if we treated e as a variable instead of a constant here. So when we take the derivative of $eV(x)$ wrt to e, we shouldn't get V'.
Answer: You are using the following lemma:
Lemma: If $f$ is continuous on $[a,b]$ and $\int_a^b f(x) V(x) dx = 0$ for all continuous $V$ so that $V(a) = V(b) = 0$, then $f(x) = 0$.
This is the lemma you used in the argument to conclude that $\frac{d}{dx} \frac{dF}{dy'} = 0$.
However, without using integration by part, you only have
$$\int_a^b g(x) V'(x) dx$$
and all smooth function $V(x)$ with $V(a) = V(b) = 0$. This is not sufficient to infer that $g(x) = 0$. Indeed if $g(x)=C$ is a constant function,
$$\int_a^b CV'(x) dx = C \int_a^b V'(x) dx = C(V(b) - V(a)) = 0,$$
by the fundamental theorem of Calculus. So you can at best conclude $g(x) = C$, instead of $g(x) = 0$.
A proof of the lemma: Let $c\in (a, b)$ so that $f(c)\neq 0$. Without loss of generality, assume that $f(c)>0$. Then there is $\delta>0$, as $f$ is continuous, so that $f(x) >f(c)/2$ for all $|x-c|<\delta$. Now let $V(x)$ be continuous positive function supported inside $(c-\delta, c+\delta)$. Then
$$\int_a^b f(x) V(x) dx >0$$
which is not possible from the assumption. Thus $f(x) = 0$ on $(a, b)$. As $f$ is continuous, it's zero on $[a, b]$.
Comment: Could you show me a proof of that lemma, or direct me to a source where I can find one? I suspected that the boundary values were involved but in the derivations that I've read for E-L, I didn't see any mention that V must be 0 on the boundary for this particular step, though I can logically see now why it must be the case.
Comment: The boundary value just make the proof a little bit harder to write down. Please see the edit of my answer. @MitchellJones
Comment: Very well written answer! Basically, the derivative of the variation does not fulfill the criteria for the principal lemma of the calculus of variations!


Is it ok to use irregular key signatures for neutral scales?

Question:
So for 24-TET neutral scales is it correct to use irregular key signatures? or do I need to use a minor with accidentals or something?
Answer: Once you start operating outside of standard major/minor scales all bets are off key-signature-wise. Especially in microtonal music, you can "invent" your own key signature as is most convenient to express your ideas.


How does apache solr search recognize my changes by mysql query in my database

Question: I would like to use mysql query to modify some of my data. But I found that apache solr doesn't index all my changes.
For example, I modified some products' category in the field_data_field_category table through query yesterday. When I went to those products' content edit page, the category shows correctly. However, I found that Apache Solr doesn't count any of them into Remaining Item.
Does anyone know how does apache solr search work? Or what kind of query I should use to achieve my goal.
Answer: Solr maintains in own search index separated from the database. A process is required to index content from your database into Solr's index. Usually, this is done transparently by the Drupal Solr integration modules. These integrtions rely on usage of Drupal API for content changes. These API allow integration code to be executed on changes. This code will either index the change directly, or mark the content for re-indexation during the next cron run.
By accessing the database directly, you bypass Durpal's APIs and prevent the integration module to see your changes.
If this is a one off operation, you should be able to mark all content for re-indexation from the administration page of your Solr integration module.
Comment: Thank you for your reply. I have a question what are "Drupal Solr integration modules"? Do you mean apache solr module (https://www.drupal.org/project/apachesolr) ?


Porta serial COM

Question: Estou tentando executar um código a cada determinado tempo, onde ele pega o valor enviado pela porta COM do Arduíno, imprime em uma textbox e logo apos gera um insert no banco mysql.
So que ele ler o que foi enviado pela porta COM e não executa o insert. Me ajudem.
<code> private void timer1_Tick_1(object sender, EventArgs e)
    {
        serialPort1.Open();
        string entrada = serialPort1.ReadLine();
        serialPort1.Close();
        txtIDTag.Text = entrada;

        if (txtIDTag.Text == "Gol")
        {
            string sql = "insert into tcc (Carro,Placa,Fabricante,Ano,Cor,Status,Data) value ('" + txtIDTag.Text + "','SCD - 4365','VW','2010','PRETO','NOVO', NOW())";

            comando.CommandText = sql;

            conexao.Open();

            comando.ExecuteNonQuery();

            conexao.Close();

            MessageBox.Show("Dados cadastrados com sucesso.");

            txtIDTag.Text = "";
        }}
</code>
Tentei tirar o IF ai ele executou.
Comment: Por que não executa? Porque o texto é diferente de Gol, porque não consegue conexão com o banco ou porque dá erro no insert?
Comment: Ja testei as duas tags que tenho. A que esta como gol e a outra que definir como palio. O problema é que não da insert com nenhuma das duas.
Comment: Mas na *textbox* aparece corretamente? O que aparece? Tem certeza que não existem caracteres a mais na string? Por quê não faz o *if* utilizando o valor de `entrada`?
Comment: Esta correto sim. Fiz o que o colega Rodrigo falou. Coloque o sinal de diferente e ele executou corretamente. Não sei explicar o motivo. Alguém teria alguma opinião de como corrigir?
Comment: Ele não esta fazendo certo não. ta pulando o if e executa o que tem dentro. Coloquei dois ifs agora e ele so executa o que ta dentro pulando os if.
Answer: Provavelmente é pq o retorno da porta serial é feito em byte, pelo menos em Java é assim, tente achar algo para concatenar as informações. Pois o retorno passa da seguinte forma
Byte G ->
Byte O ->
Byte L
então se você comparar só o G talvez funcione.

Porta serial COM


Space before PHP tag

Question: I have written an application in PHP. It includes
1: login form
2: Welcome page
3: Logout form which is redirected to login form.

My register_global =On in php.ini.
My application has working properly on LAMP and WAMP. But it has not setting session on live server.
But, after checking by line by line, in session setting file, there was single space before starting '<?PHP ...... ?>'. After removing that space my application has working properly on live server.
What can be the reason behind that space before the '<?PHP ...... ?>' by which session is not setting?
Comment: Note that a workaround to this issue (in any file other than the landing point) is to enable output buffering.  See: http://www.php.net/manual/en/function.ob-start.php
Answer: The space is output, i.e. sent to the browser. For opening a session you need to send a so-called HTTP header, which you need to do before anything is output. That's why it didn't work. Your error message probably was "headers already sent".
Answer: You can't send any content before sending the response headers; the session is sent in the response headers.  Because you sent a space beforehand, you are therefore unable to start a session.
From the documentation on session_start, "To use cookie-based sessions, session_start() must be called before outputing anything to the browser.".  This includes the single space at the start.
Basically, the first thing in any script should always be <?php

Space before PHP tag


Verificar se há retorno da imagem via Javascript

Question: Como verificar se a imagem retornou com erro 404 via javascript.
Abaixo um codigo de exemplo, quero verificar se o get dessa imagem é 404. Se for quero colocar uma determinada imagem, se não for retornar a imagem.
<!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>

Answer: Você pode usar um listener para o evento onerror:

Comment: Nesse link dos Arquivos que eu mencionei na minha resposta o autor lista uma série de peculiaridades antre browsers quanto ao onerror (e onload). JS não é bem meu forte pra dizer se confiar completamente (e unicamente) no onerror é seguro ou não.
Comment: @BrunoAugusto Pelo que entendi, grosso modo, o maior problema é com cache. Se o objetivo é controlar o carregamento de algo que pode ou não estar acessível, intermitentemente, `onerror` pode ser problema. Se é pra checar se um recurso não existe nem nunca existiu, `onerror` deve ser suficiente.
Comment: muito obrigado, mas fiz aqui o teste e ele não faz o alert, é como se retornasse algo. Mas se você acessar essa imagem vai ver que dá erro no console 404.
Comment: Fiz um teste e pareceu funcionar: http://jsbin.com/saritewu/1/edit
Comment: Rolou aqui @bfaretto. Valeu mesmo :)
Comment: Obrigado @BrunoAugusto, li o link.
Comment: E então? Isso influencia em alguma coisa?
Answer: Você pode fazer uma requisição HEAD e verificar o status de retorno da url.
function checkStatus(imageUrl)
{
   var http = jQuery.ajax(
   {
      type:"HEAD",
      url: imageUrl,
      async: false
    })
  return http.status;
}

E utilizá-la desse modo:
var imageUrl = 'http://pbs.twimg.com/profile_images/438827041199099904/ZLjBL8Tg_normal.jpeg';
var statuscode = checkStatus(imageUrl);

if (statuscode == 200)
{
   // Existe!
} else if (statuscode == 404)
{
   // Não existe!
}
// else if....

Comment: beleza, vou testar dessa forma.
Answer: Uma outra solução vinda do SOen baseada em um artigo que hoje já não existe mais (link dos Arquivos).
// First a couple helper functions
function $(id) {
    return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) {    return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}

// Here's the meat and potatoes
function image(src,cfg) {    var img, prop, target;
    cfg = cfg || (isType(src,'o') ? src : {});

    img = $(src);
    if (img) {
        src = cfg.src || img.src;
    } else {
        img = document.createElement('img');
        src = src || cfg.src;
    }

    if (!src) {
        return null;
    }

    prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
    img.alt = cfg.alt || img.alt;

    // Add the image and insert if requested (must be on DOM to load or
    // pull from cache)
    img.src = src;

    target = $(cfg.target);
    if (target) {
        target.insertBefore(img, $(cfg.insertBefore) || null);
    }

    // Loaded?
    if (img.complete) {
        if (img[prop]) {
            if (isType(cfg.success,'f')) {
                cfg.success.call(img);
            }
        } else {
            if (isType(cfg.failure,'f')) {
                cfg.failure.call(img);
            }
        }
    } else {
        if (isType(cfg.success,'f')) {
            img.onload = cfg.success;
        }
        if (isType(cfg.failure,'f')) {
            img.onerror = cfg.failure;
        }
    }

    return img;
}

Uso:
image('http://somedomain.com/image/typooed_url.jpg', {
    success : function () {alert(this.width)},
    failure : function () {alert('Oops!')}
});

image('https://www.gravatar.com/avatar/bac48b9b301f4b2aea7ec399a14b8bc9?s=128&d=identicon&r=PG', {
    success : function () {/** ... */},
    failure : function () {alert('Oops!')},
    target : 'successImageContainer'
});

Demo no Fiddle.
A primeira vista parece recurso em excesso, mas se for ver, caso resulte num 404 você teria que fazer algumas condições e tal então alguns callbacks vêm bem a calhar.
Comment: Poxa ! Completo @BrunoAugusto, muito bom mesmo.
Answer: Você pode fazer um load na url da imagem para verificar se existe:
function checkImagem(url) {
  var img = '';
  $(img).load(function() {
    $('body').append(url+img);
  }).bind('error', function() {
    alert('imagem: '+url+' não existe');
  });
 }

Exemplo: JSFiddle
Comment: Para funcionar nas novas versões da JQuery use assim `$(img).on("load", function() {`


How to timestamp last block access to profile cck field

Question: I need to log when a user last accessed particular areas of my site (a content type and some views pages), to do this I have added a block using PHP filter with the below code. This block is only visible on the required pages so I was hoping it would mean when a user accesses these pages it updates the users profile with the timestamp.
<code>global $user;
$uid = $user->uid;
$node = content_profile_load(profile,$uid);
$pid = $node->nid;
$node = node_load($pid);
$changeLastAccess = mktime();
$node->field_changes_last_access[0]['value'] = $changeLastAccess;
node_save($node);
</code>
The problem is this date always shows the CURRENT time, not the time when a user was last on one of the pages on which the block is active. I am totally stumped...
EDIT:
This was working all along, i had created the wrong CCK field type of "Date" rather than "Datestamp", changed this over and it works fine.
Answer: The above works fine, however the cck field type needs to be a "Datestamp"


Path to 3d Mathematics programming, where to start?

Question: This might read like duplicate of this question https://math.stackexchange.com/search?q=where+to+start
However since that one wasn't answered, and I have a more specific problem in regards to learning what I want to learn, I feel it was worth while to ask the question anyway.
My last hurdle to becoming a hireable game programmer is the the application of 3D mathematics in graphics programming. While I have no problems using simpler math while programming basic games and understanding how to use the 3D math libraries already present in other engines, every time I get a around actually doing matrix calculations myself and other complex calculations I find myself at a brick wall.  There have been a few times where I was able to briefly learn and apply 3d Mathematics but it didn't last that long and I find myself once a again stuck.
It feel my understanding of mathematics is only skin deep because of this. There may be something missing in my understanding of mathematics thus far, as often when I look up a lengthy equation or algorithm, I get overwhelmed with the all the symbols. Obviously this doesn't help me in understanding 3D mathematics at all.
So, does anyone know about how I can rectify this, not just in 3D mathematics. (I've already accumulated my own resources for this but I can't easily read through it because the amount of mathematics don't I know) Are there any books, articles, blogs or websites that can deepen my understanding enough so that I won't forget 3d mathematics again. This includes prerequisites just before the 3D mathematics and also sites that can help me practice. I already know about Khan Academy, however I would prefer a written version as I can get through those quicker. And also If you know of any books in kindle or eReader format that really help, as I hate reading lengthy texts on the computer screen.
Thank you!
Comment: Have you tried reading a textbook in linear algebra? Any decent such book should contain what you need to know in order to understand how to use matrices to perform rotations, reflections, projections, etc.
Answer: If you wish to learn how to make 3d graphics to use in an existing game engine, you won't need more than very basic maths.
However, if you wish to develop game engines, you will need linear algebra, vector calculus and graph theory skills, and you will need to learn how to program!
Calculus' applications in game development are extensive. Physics is a typical example.
Graph theory is what you will crucially need. It underpins the theory of algorithms and data structures used in complicated software engineering. Algorithms such as Dijkstra's and Prim's are essential graph theory for software engineering.
Some nice introductory books are:
Thomas H. Cormen - Introduction To Algorithms, MIT Press.
R. Balakrishnan, K. Ranganathan - A Textbook of Graph Theory, Springer.
Answer: The best way to learn hands down is to read the code of an open source 3D framework. See how they implement all of the different operations. Try running one of their basic examples, and put breakpoints in the code to see how it gets executed.
To get started, check out Three.js. It's a very popular JavaScript 3D engine, and by reading the code you can get a good sense of how to implement everything.

https://github.com/mrdoob/three.js (such as three.js/src/math)

To find frameworks in other languages, just search on GitHub. By far the best way to learn how to use math in programming. Much much better than any book.


Show content type teaser only if posts available for the content type

Question: I'm displaying a content type teaser view on the front page using Twig Tweak. But I want to show it only if there are posts available. Something like
{% if content type has posts %}

Upcoming Events

  {{ drupal_view('home_upcoming_event_teaser') }}
{% endif %}

How can I achieve this in a Twig Template?
Comment: Use a View for this.
Answer: You can use drupal_view_result to check if your view has result:
From Cheat sheet

{# This might be useful to check if a view returns nothing. #}
    View results:
{{ drupal_view_result('who_s_new', 'block_1') }}

Your code will be something like:
{% if drupal_view_result('home_upcoming_event_teaser') is not empty %}

Upcoming Events

  {{ drupal_view('home_upcoming_event_teaser') }}
{% endif %}


Serve static content in Stoplight Prism mock server

Question: I have OpenAPI file describes my API design, using the Stoplight Prism to provide a mock server for the front-end developers by their Docker image stoplight/prism:4
My question is, how can I serve static content within that server?
I need to provide an API documentation for the front-end developers to know how to use the API, I have this documentation as HTML file, for now I serve this documentation by a separate web server, how can I include it within Prism?
All my API endpoints are available  at /api/ path, can I serve my HTML file at something like /static/doc.html?
Answer: Prism CLI doesn't support serving static file. A simple approach is to use Docker Compose to start the mock server and web server.
Below example bases on the way described in Serving Multiple OpenAPI Documents, to use Caddy as both reverse proxy and static file server.
❯ tree
.
├── Caddyfile
├── docker-compose.yaml
├── html
│   └── index.html
└── myapi.yaml

docker-compose.yaml:
version: '3'
services:
  proxy:
    image: caddy
    volumes:
      - ${PWD}/Caddyfile:/etc/caddy/Caddyfile
      - ${PWD}/html:/var/www/static
    ports:
      - '8080:80'
    depends_on:
      - prism
  prism:
    image: stoplight/prism:4
    volumes:
      - ./myapi.yaml:/usr/src/prism/packages/cli/myapi.yaml
    command: >
      mock -p 4010 --host 0.0.0.0 myapi.yaml

Caddyfile:
http:// {
    root * /var/www
    reverse_proxy /api/* prism:4010
    file_server /static/*
}

After run the command docker-compose up, you can view document on http://127.0.0.1:8080/static and call API on http://127.0.0.1:8080/api/....


Can we set question formatting?

Question: Here is some suggestion to change question formatting.
I have edited some question regarding it.
whenever question is asked and it's about to magento 2.
some people write question like below format.
"Magento2 question"
"Magento2-question"
"Magento 2 - question"
"Magento2 : question"
"Magento 2 : question"
"Magento2 | question"
"Magento 2 | question"
They always add new symbols so in my personal opinion why we are giving them to add deliminator for question. we can set plain text in question
or we can give them suggestion text like "Magento 2 question" so it would be go in proper way for next all questions.
Comment: How about we put the version in the tags and not in the title?
Comment: that is great but still people are writing in title
Comment: those does not make sense to change version format, it does not make any useful impact
Comment: Is there any specific usecase for having it more standardized in the title?
Comment: It is more readable & quick searchable from google .. Thanks to SE great search mechanism it is also searching like this question also
Answer: Personally I don't see any added value to have the magento version in the title, or not to have it either.
There is no point to set a standard or to start editing all the questions to reflect the magento version in the title or to not reflect it.
Comment: Yes, there is no possibilities to set standard as not much useful. Agree.  thanks for the time.

Can we set question formatting?


What are the requirements for an application health monitoring system?

Question: What, at a minimum, should an application health-monitoring system do for you (the developer) and/or your boss (the IT Manager) and/or the operations (on-call) staff?
What else should it do above the minimum requirements?
Is monitoring the 'infrastructure' applications (ms-exchange, apache, etc.) sufficient or do individual user applications, web sites, and databases also need to be monitored?
if the latter, what do you need to know about them?
ADDENDUM: thanks for the input, i was really looking for application-level monitoring not infrastructure monitoring, but it is good to know about both
Comment: yes, this is a self-serving question. so what?
Comment: that's what i want you to tell me...
Comment: This seems kind of vague for a discription what exactly are you looking to monitor?
Comment: Nice way to put down unfounded criticism makers. We have to be **bold** sometimes to make our point pass through.
Answer:
Whether the application is running.
Unusual cpu/memory/network usage.
Report any unhandled exceptions.
Status of various modules (if applicable).
Status of external components (databases, webservices, fileservers, etc.)
Number of pending background tasks (if applicable).
Maybe track usage of the application and report statistics on most/less used functionalities so you know where optimizations are most beneficial.
Comment: It depends on the application, but basically I'd get the average usage over a specific period (say 5 minutes), and if it's higher than X (90% cpu, 1 gig of memory, 200kbps... these values really depend on the app), report it.
Answer: The answer is 'it depends'. Why do you need to monitor? How large is your operations staff? Do you need reporting? What is the application environment? Who cares if the application fails? Who cares if an exception happens? Are any of the errors recoverable? I could ask questions like these for a long time.
Comment: [@David Medinets]: as for "why do you need to monitor" the answer is: to be pro-active about support, i.e. to know when something goes wrong immediately, so we can fix it
Answer: This is such an open ended question, but I would start with physical measurements.
1. Are all the machines I think are hosting this site pingable?
2. Are all the machines which should be serving content actually serving some content? (Ideally this would be hit from an external network.)
3. Is each expected service on each machine running?
3a. Have those services run recently?
4. Does each machine have hard drive space left? (Don't forget the db)
5. Have these machines been backed up? When was the last time?

Once one lays out the physical monitoring of the systems, one can address those specific to a system?

1. Can an automated script log in? How long did it take?
2. How many users are live?  Have there been a million fake accounts added?
...
These sorts of questions get more nebulous, and can be very system specific.  They also usually can be derived reactively when responding to phsyical measurements. Hard drive fill up, maybe the web server logs got filled up because a bunch of agents created too many fake users. That kind of thing.
While plan A shouldn't necessarily be reactive, it is the way many a site setup a monitoring system.
Comment: excellent points, but what about the applications running on each machine?
Answer: Great question.
We've been looking for some application-level monitoring solution for our needs some time ago without any luck. Popular monitoring solution are mostly addressed to monitor infrastrcture and - in my opinion - they are too complicated for a requirements of most of small and mid-sized companies.
We required (mainly) following features:

alerts - we wanted to know about
incident as fast as possible
painless management - hosted service wouldbe
the best
visualizations - it's good to know what is going on and take some knowledge from the data

Because we didn't find suitable solution we started to write our own. Finally we've ended with up-and-running service called AlertGrid. (You can check it for free of course.)
The idea behind it is to provide an easy way to handle custom monitoring scenarios. Integration API is very simple (one function with two required parameters). At the momment we and others are using it for:

monitor scheduled tasks (cron jobs)
monitor entire application logic execution
alert on errors in applications
we are also working on examples of basic infrastructure monitoring using AlertGrid
Answer: Minimum: make sure it is running :)
However, some other stuff would be very useful. For example, the CPU load, RAM usage and (in multiuser systems) which user is running what. Also, for applications that access network, a list of network connections for each app. And (if you have access to client computer(s)) it would be cool to be able to see the 'window title' of the app - maybe check each 2-3 minutes  if it changed and save it. Also, a list of files open by the application could be very useful, but it is not a must.
Comment: For monitoring Apache, Exchange and other common services, take a look at software like Nagios (open source) that does all the job already. Just install, configure and enjoy.
Answer: I think this is fairly simple - monitor so that you can be warned early enough before something goes wrong. That means monitor dependencies and the application itself.
It's really hard to provide specifics if you're not going to give details on the application you're monitoring, so I'd say use that as a general rule.
Comment: my project is a system for monitoring .NET applications - of all types
Answer: At a minimum you want to know that the system is healthy. This is subjective in what defines your system is healthy. Is it computers are up, the needed resources exist, the data is flowing through the system, the data is properly producing results, etc, etc.
In my project we do monitoring of most of this and then some. It really comes down to what is the highest level that you can use to analyze that everything is working. In our case we need to know down to the data output. If you just need to know down to the are these machines up it saves you on trying to show an inexperienced end user what is wrong.
There are also "off the shelf" tools that will do a lot of the hard work for you if you are just looking too hard into data results. I particularly liked Nagios when I was looking around but we needed more than it could easily show so I wrote our own monitoring system. Basically we also watch for "peculiarities" in the system, memory / cpu spikes, etc...
Comment: nagios - like many others - monitors only 'infrastructure' applications, not individual applications. What do you need to make sure your user's programs are 'healthy'?
Answer: thanks everyone for the input, i was really looking for application-level monitoring not infrastructure monitoring, but it is good to know about both
the difference is:

infrastructure monitoring would be servers plus MS Exchange Server, Apache, IIS, and so forth
application monitoring would be user machines and the specific programs that they use to do their jobs, and/or servers plus the data-moving/backend applications that they run to keep the data flowing

sometimes it's hard to draw the line - an oversimplified definition might be "if your team wrote it, it's an application; if you bought it, it's infrastructure"
i think in practice it is best to monitor both
Answer: What you need to do is to break down the business process of the application and then have the software emit events at major business components.  In addition, you'll need to create end to end synthetic transactions (eg. emulating end users clicking on a website).    All that data would be fed into an monitoring tool.   In the past, I've done JMX for applications of which flowed into Tivoli Monitoring's JMX Adapter and then I've done scripts that implement a "fake user" and then pipe in the results into Tivoli Monitoring's Script Adapter.   Tivoli Monitoring takes the data and then creates application health and performance charts from that raw data.
Comment: interesting - but I'm not trying to simulate the results, I'm trying to monitor the actual result in real-time
Comment: The monitoring is real time... the emulation part was just to get data flowing into the real time monitoring dashboards.


If $T\in B(X,Y)$ and $T$ is bijective is $T^*$ also bijective?

Question: 1) This first link seems to provide a proof that seems to work for all normed vector spaces.
If $T:X \to Y$ is a linear homeomorphism, is its adjoint $T^*$ a linear homeomorphism?
2) This second link provides a counter example.
Adjoint operator, bijective
I can't seem to find any differences in the assumptions. Could someone explain whats the difference and if the statement is rue in general for all normed vector spaces? I know in the first link it mentions linear homeomorphisms and hilbert spaces but the proof provided seems to hold for any normed spaces(not just banach)and the the continuity of the inverse is not used in the proof.
Answer: In the first post the spaces are complete and in the second they are not. In the first post completeness is necessary. It is assumed that the inverse $S$ of $T$ is a bounded operator. (If it is just a linear map we cannot even define its adjoint). So Open Mapping Theorem is used here.
Comment: Yes but the proof in the first post hold for all normed spaces not just for banach spaces.
Comment: @JhonDoe I have added some details to my answer.
Comment: The first link shows: if $T$ has an inverse, then... However, merely "bijective" is not enough to imply an inverse when the spaces are not complete.
Comment: I see. So both spaces have to be banach for the inverse to be bounded.
Comment: @GEdgar i think the inverse exists just that it need not be bounded


templated lambda return type

Question: I want to write a little bit of code that maps enums to specific members of a struct.
The trouble is the members of the struct have different types, if they didn't I've just used an std::array of references or pointers to do this.
So I thought to use a lambda instead since they now have template params
Here's something like what I have:
#include <type_traits>
#include <iostream>

struct foo
{
    int x;
    double y;
};

enum class keys
{
    x,
    y,
};

void print(foo f)
{
    auto get = [&f]<keys K, typename T>(std::integral_constant<keys, K>) -> T&
    {
        switch(K)
        {
            case keys::x: return f.x;
            case keys::y: return f.y;
        }
    };
    std::cout << get(std::integral_constant<keys, keys::x>{}) <<std::endl;
    std::cout << get(std::integral_constant<keys, keys::y>{}) <<std::endl;
}

int main(void)
{
    foo m{1,2.0};
    print(m);
    return 0;
}

Note, in my real code, I cannot modify the foo struct, and the types are much more complex than int or double.
But this code gives me errors like:
<source>: In function 'void print(foo)':
<source>:26:21: error: no match for call to '(print(foo)::<lambda(std::integral_constant<keys, K>)>) (std::integral_constant<keys, keys::x>)'
   26 |     std::cout << get(std::integral_constant<keys, keys::x>{}) <<std::endl;
      |                  ~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:18:16: note: candidate: 'template<keys K, class T> print(foo)::<lambda(std::integral_constant<keys, K>)>'
   18 |     auto get = [&f]<keys K, typename T>(std::integral_constant<keys, K>) -> T&
      |                ^
<source>:18:16: note:   template argument deduction/substitution failed:
<source>:26:21: note:   couldn't deduce template parameter 'T'
   26 |     std::cout << get(std::integral_constant<keys, keys::x>{}) <<std::endl;
      |                  ~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:27:21: error: no match for call to '(print(foo)::<lambda(std::integral_constant<keys, K>)>) (std::integral_constant<keys, keys::y>)'
   27 |     std::cout << get(std::integral_constant<keys, keys::y>{}) <<std::endl;
      |                  ~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:18:16: note: candidate: 'template<keys K, class T> print(foo)::<lambda(std::integral_constant<keys, K>)>'
   18 |     auto get = [&f]<keys K, typename T>(std::integral_constant<keys, K>) -> T&
      |                ^
<source>:18:16: note:   template argument deduction/substitution failed:
<source>:27:21: note:   couldn't deduce template parameter 'T'
   27 |     std::cout << get(std::integral_constant<keys, keys::y>{}) <<std::endl;
      |                  ~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiler returned: 1

How can I work around this? I'm a little confused how the compiler fails to be able to deduce T&. One way I could work around this is via specializations but I was not able to figure out how to specialize a lambda function for specific template params.
Comment: The compiler can't deduce a return type because you have one case that returns `int` and one that returns `double`. There is no compile-time `switch` that would let you choose one of them but you can use `if constexpr`.
Comment: why are you using `std::integral_constant` rather than simply the enum value?
Comment: typo `print(foo);` -> `print(m);`
Comment: Why introduce this `key` thing and repeat every member name three times? (once in `foo`, once in `key`, once in `get`). You can use `&foo::x` and `&foo::y` as keys instead. https://godbolt.org/z/f6j6Y4vvr
Answer: You are not passing anything to the lambda that lets the compiler deduce what T should be. As @molbdnilo  mentioned, your switch is not evaluated until runtime, and it returns different types for each value of K, so the compiler can't use that to deduce T at compile-time.
Just use auto instead for the return type, and then use if constexpr to let the compiler evaluate the conditions at compile-time and remove unused code, thus letting auto to deduce the type of whichever return is actually used.
For example:
#include <type_traits>
#include <iostream>

struct foo
{
    int x;
    double y;
};

enum class keys
{
    x,
    y,
};

// see https://devblogs.microsoft.com/oldnewthing/20200311-00/?p=103553
// for why this is needed below...
template<keys K>
inline constexpr bool always_false_v = false;

void print(const foo& f)
{
    auto get = [&f]<keys K>() -> auto&
    {
        if constexpr (K == keys::x)
            return f.x;
        else if constexpr (K == keys::y)
            return f.y;
        else
            static_assert(always_false_v<K>, "Invalid key");
    };
    std::cout << get.operator()<keys::x>() << std::endl;
    std::cout << get.operator()<keys::y>() << std::endl;
}

int main(void)
{
    foo m{1,2.0};
    print(m);
    return 0;
}

Online Demo
Alternatively, as @n.m. suggested, you can just get rid of the keys enum and use pointer-to-members instead, eg:

include <type_traits>
#include <iostream>

struct foo
{
    int x;
    double y;
};

void print(const foo& f)
{
    auto get = [&f](auto member) -> auto&
    {
        return f.*member;
    };
    std::cout << get(&foo::x) << std::endl;
    std::cout << get(&foo::y) << std::endl;
}

int main(void)
{
    foo m{1,2.0};
    print(m);
    return 0;
}

Online Demo
Comment: Thank you for answering the question directly as well as providing an improvement suggestion, in the real code I ended up using a combination of the two. The reasoning I did this is because the enum names are fixed while multiple structures are present.

The pointer to member strategy suggested solves the multiple structure problem as well because I can simply pass in their pointer to members <3
Answer: You can use a class template for the mapping:
template <keys> struct key_to_foo_mem;
template <> struct key_to_foo_mem<keys::x> { auto& operator()(const foo& f){ return f.x; } };
template <> struct key_to_foo_mem<keys::y> { auto& operator()(const foo& f){ return f.y; } };

void print(foo f)
{
    std::cout << key_to_foo_mem<keys::x>()(f) <<std::endl;
    std::cout << key_to_foo_mem<keys::y>()(f) <<std::endl;
}

Your lambda approach has two issues: T is used but neither provided explicitly nor deduced. The return type is deduced inconsistently from the two cases, but a function can have only one return type. Moreover you use a trailing return of T& which does surpress the deduction of the return type by the compiler.
You can remove T and use constexpr if :
void print(foo f)
{
    auto get = [&f]<keys K>(std::integral_constant<keys, K>)
    {
        if constexpr(K == keys::x) { return f.x; }
        else { return f.x; }
    };
    std::cout << get(std::integral_constant<keys, keys::x>{}) <<std::endl;
    std::cout << get(std::integral_constant<keys, keys::y>{}) <<std::endl;
}

I'm a little confused how the compiler fails to be able to deduce
T&.

When you use trailing return type you are telling the compiler "this is the type" (ie you surpress the deduction) but -> T& as trailing return type makes no sense. Once you use constexpr if the compiler can deduce the return type itself (lambdas have implicit auto return type).

One way I could work around this is via specializations but I was not able to figure out how to specialize a lambda function for specific template param

Its important to understand that for the above lambda expression it is the operator() that is templated, not the type of the lambda. How you can use specialization I have shown above (though it is specialization of a class template, not of a member template).

templated lambda return type


Which is this series

Question: When
m = 2, series is 1,2,3,4,5..
m = 3 : 1,3,6,10,15..

m = 4 : 1,4,10,20,35..

m = 5 : 1,5,15,35,70..

m = 6 : 1,6,21,56,126..

So given value of m, can I find the entire series ?
Thank you
Comment: For given $m$, the sequence is $\binom{m+k-1}{k}$ with $k$ start from $0$. The corresponding OGF is $\sum_{k=0}^\infty \binom{m+k-1}{k} z^k = \frac{1}{(1-z)^m} $.
Comment: Looks rather like Pascal's triangle, especially if for  $m=1$ the sequence is $1,1,1,1,1,\ldots$
Answer: I guess:
$\displaystyle
\left \{
  1, m, \frac{m(m+1)}{2}, \frac{m(m+1)(m+1)}{6} , \ldots , \binom{m+k-2}{k-1}
 \right \}
=\left \{ \binom{m+k-2}{k-1} \right \}_{k=1}^{\infty}$
Comment: Here, k is kth term of the series right? And this is not converging series..
Comment: K can not start from 0 right?
Comment: Looks fine now.. Thank you
Answer: These are obviously oblique rows in Pascal's triangle,
$$\binom{m-1+n}{n}=\frac{(m-1+n)!}{(m-1)!n!}=\frac{(m-1+n)(m-2+n)\cdots(n+1)}{(m-1)!}.$$
The sequence for $m$ is the prefix sum of the sequence for $m-1$.
For example, for $m=4$,
$$\frac{1\cdot2\cdot3}{1\cdot2\cdot3},\frac{2\cdot3\cdot4}{1\cdot2\cdot3},\frac{3\cdot4\cdot5}{1\cdot2\cdot3},\frac{4\cdot5\cdot6}{1\cdot2\cdot3}\cdots$$
You can compute the sequences efficiently by recurrence,
$$S_{m,n}=S_{m,n-1}\frac{m-1+n}{n}.$$
For $m=4$,
$$1,1\cdot\frac41=4,4\cdot\frac52=10,10\cdot\frac63=20\cdots$$

Which is this series


Form submission in spring using jquery

Question: My Form with spring tags:
 <form:form action="save" commandName="user" id="form1">
  <form:input
     .
     .
  <form:select
     .
     .
  <input type="submit" value="Submit" />
 </form:form>

Controller:
 @RequestMapping(value="/save",method = RequestMethod.POST)
 public @ResponseBody UserEntity dataSave(@ModelAttribute("user") UserEntity user, BindingResult result) {
    userManager.addUser(user);
 return user;
}

jquery call:

My problem is how to send data from jsp to controller. My form nearly contains 20 Fields.
Comment: Possible duplicate of http://stackoverflow.com/questions/13957581/how-to-submit-spring-form-in-ajaxjquery-with-modelattribute
Answer: Try this code:
$("#form1").submit(function(event){

        // setup some local variables
        var $form = $(this);
        // let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");
        // serialize the data in the form
        var serializedData = $form.serialize();

        // let's disable the inputs for the duration of the ajax request
        $inputs.prop("disabled", true);

        // fire off the request to /action
        request = $.ajax({
            url: "/app/action",
            type: "post",
            data: serializedData,
            success: function(response){
            // we have the response
            alert(response);
        });

        // callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR){
            // log a message to the console
            $inputs.prop("disabled", false);
            console.log("Form1 Posted");
        });

        // callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            $inputs.prop("disabled", false);
            // log the error to the console
            console.error(
                "The following error occured: "+
                textStatus, errorThrown
            );
        });

        // callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // reenable the inputs
            $inputs.prop("disabled", false);
        });

        // prevent default posting of form
        event.preventDefault();
    });

Answer: Need to add @ResponseStatus(HttpStatus.NO_CONTENT) to the Spring MVC controller method
eg
@RequestMapping(value="/save",method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public @ResponseBody UserEntity dataSave(@ModelAttribute("user") UserEntity user, BindingResult result) {
userManager.addUser(user);
return user;
}

And also see this question.
Answer: try this code please
$.ajax({
    data:$("#form1").serialize(),
    url : $("#form1").attr("action"),
    type : "POST",
    success : function(response) {
    alert("success");
    }
});

Form submission in spring using jquery


SlamData uninstall Linux

Question: Does anyone know how to uninstall SlamData on a Linux system (Centos 7)? I would like to completely remove it from the server. I looked through the documentation but could not find anything on uninstallation.
Thanks,
Answer: On Linux, you can uninstall SlamData simply by removing the directory you specified during the initial installation.  By default it ends up being

/home/username/SlamData version

There is also a configuration directory and file you can delete located at

/home/username/.config/quasar/quasar-config.json

SlamData uninstall Linux


How to sort View on rewritten field?

Question: I have a View with a table display format and all columns are set as being sortable. Although the issue isn't specific to Date fields; I am specifically trying to figure out an issue with Date fields.
I have 2 Date fields, one is primary and the other is secondary. I have tried various ways in adding the login for "if (pri) pri, else sec".

using no results option for pri date field
using twig in a custom text field

The results are:

sorts only on the base field; not the rewritten value
wsod when selecting to sort on this column

I have tried this both with db search as well as Search API - same results. I seem to be able, with Search API, to create an aggregated "First" field which seems to work; although the date format is not adjustable. I have also seen a patch which allows formatting of the base date fields; but my guess is that this will then give a string sorting of the aggregated field (i.e. Dec comes before June).
My next shot is to use the aggregated date field formatted as SOLR is giving by default and assume that is a valid date sort (I think it is, YYYY-MM-DD) and then do up a field formatter to display the correct date format.
Comment: I think you might have better luck if you convert the date fields to Unix timestamps, which are integers.
Answer: I think the quick answer is "you can't sort on a rewritten value" in Views; regardless if it's a date field or using Search API.
There are however; various workarounds depending on the particular issue. I have used the following now:

use Computed Field to store the rewritten value in the db and then display/sort on that
SearchAPI is capable of doing simple rewrites with its Aggregated Field; this may work for simple rewrites.

You can often combine a computed field and a rewrite in Views to take advantage of Views field formatting. Keep in mind that the sorting occurs on the original db value for the field. So, for my example above, you could do a computed field to store the timestamp of the Date Range's end date; and then add that to the View but rewrite that field with the formatted end date. This will then sort on the timestamp; but display the properly formatted value.

How to sort View on rewritten field?


Tensor product of representations of a Lie algebra (or Lie Superalgebra)

Question: Let $V$ and $W$ be finite dimensional irreducible representations of a Lie Algebra or a Lie Superalgebra. If $V$ is one dimensional, is $V\otimes W$ necessarily irreducible?
I know this to be true for $\mathfrak{gl}(n)$ and the superalgebra $\mathfrak{gl}(m|n)$ and I wonder if this is true in general. Thanks.
Answer: A 1-dimensional represenation $V$ is always invertible, in the sense that there is another representation $V^{-1}$ such that $V\otimes V^{-1}$ and $V^{-1}\otimes V$ are both isomorphic to the trivial representation. Indeed, you can tale $V^{-1}$ equal to the dual (that is, contragredient) repreentation of $V$.
It follows from that that if $V\otimes W$ is isomorphic to a dirct sum $U\oplus U'$, with $U$ and $U'$ nonzero, then $V^{-1}\otimes(V\otimes W)$ is isomorphic both to $V^{-1}\otimes U\oplus V^{-1}\otimes U'$ and to $W$. This is impossible if $W$ is irreducible.


User can't access own private files via Views

Question: I've set up a private directory sites/default/files/private and use it for a file field.
As an admin, everything works as expected when uploading and viewing a private file.
As a user who uploads a private file, I can only download own private files with the Views formatter Download link (example.com/file/585/download?token=TcBjzT2I), but not view them via Generic file (example.com/system/files/private/mypic.jpg) or other formatters. When using the latter, I get
"Access Denied
You are not authorized to access this page."
Permission "View own private files" for role enabled. Even enabling "View private files" has no effect.
What am I missing?
Answer:
Files in the private directory are not accessible directly through the web server;

You may have to use file_create_url or hook_file_download to access the files under private directory.
For More info on Accessing Private Files check here
Comment: Thanks, Kstack. What I don't understand is why can the admin view the files then?


How do I decode a JSON file containing arrays Swift 4?

Question: I have a JSON file which I'm trying to decode but am getting an error message:

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))

My code is as follows:
struct Phrase: Decodable {
let sentences: [String]
}

func getFromJSON() {

    do {
        let jsonURL = Bundle.main.url(forResource: "script", withExtension: "json")
        let jsonDecoder = JSONDecoder()
        let jsonData = try Data(contentsOf: jsonURL!)
        let jsonSentence = try jsonDecoder.decode([Phrase].self, from: jsonData)
        debugPrint(jsonSentence)

    } catch {
        print(error)
    }
}

I've been looking at lots of other stack overflow questions and I've noticed that the format of these JSON files are different to mine. They are formatted as dictionaries while mine is like this-
[
["bin blue", "with A 2 soon"],
["set blue", "in A 9 soon"],
["lay blue", "at A 3 please"],
["3 5 zero zero 5 8"],
["place blue", "by A 6 now"],
["lay green", "at B ZERO now"],
["8 9 1 5 4 zero"]
]

I know that the decoder is looking for a dictionary but how do I have it decode the arrays instead?
Answer: I think you need
let jsonSentence = try jsonDecoder.decode([[String]].self, from: jsonData)

Comment: +1. Hardy143, You can't use `struct Phrase` because JSON doesn't have a `sentences` key. Your JSON is an Array of Arrays.
Comment: @subdan exactly no keys here
Answer: Your JSON data does not match the structure you want to parse. The JSON is an array of string arrays, whereas you try to parse an array of Phrase objects.
Solution 1: to keep the JSON structure as-is, you need to parse an array of arrays, or to keep the custom model type, by using a type alias:
typealias Phrase = [String]

Solution 2: to keep the struct you defined as-is, you'll have to change the JSON format to this;
[
  { "sentences": ["bin blue", "with A 2 soon"] },
  { "sentences": ["set blue", "in A 9 soon"] },
  ...
]

Both solutions will work with your getFromJSON implementation.
Comment: Thanks a lot. I went with solution 1 and works perfect.


Web-based (intranet / non-hosted) timesheet / project tracking tools

Question: I realize some similar questions have been asked along these lines before, but from reading-through them today, it appears they don't match my use case.
I am looking for a web-based, non-hosted time and project tracking tool. I've downloaded Collabtive and Achievo so far, but am looking for other suggestions, too.
My list of requirements:

runs on standard LAMP stack
non-hosted (ie, there is an option to download and run it on a local server)
not a desktop/single-user application
easy-to-use - my audience is a mix of technical and non-technical folks
easy to maintain - when time for upgrading comes, I'd really like to not have to rebuild the app (a la <code>./configure ; make ; make install</code>)
needs to support multiple users
free-form project additions: we don't have a central project management authority (users should be able to add whatever they're working on, not merely from a drop-down)

Does anyone here have experience with such tools? It doesn't have to be free.. but free is always nice :)
Comment: side note: this seems like a question more-or-less equally suitable to SU, SO, and SF
Answer: Achievo: price certainly can't be beat - and it fills the other requirements (so far) of my initial list.
I've now had a chance to use (or try to use) both Achievo and Collabtiv, and must say that Collabtiv is non-ideal. I couldn't get it setup at all, even after going through all the docs on the website and that come with it.
I'm running RHEL 5 x64 with PHP 5.2 and MySQL 5.0, and Achievo setup with no problems. For now, this looks like the solution I'll go with.
Comment: This is, in fact, the solution I'm going to use. Thanks for the other options :)
Answer: Collabtiv: this one also can't be beat form the price perspective, and also matches (so far) my requirements list.
However, I cannot get it up and running on my RHEL 5 x64 box (PHP 5.2 and MySQL 5.0). Don't know what's up with it, as the previews online looked really really promising.
For now, I'm going with Achievo.
Answer: The Ruby on Rails application ClockingIT sounds like you could need it.
It's not quite using the LAMP stack, but the installation should be quite easy on any reasonably modern Linux distribution which provides packages for Ruby (and ideally Ruby on Rails).
Comment: just a source download? That's different :)
Comment: Since Ruby is interpreted, there is no need to offer anything than a source tarball. ;)
Comment: To be clear: I'm talking about http://github.com/ari/clockingit/archives/master
Comment: . ahh - good point. Haven't used Ruby, and expected it to be a bunch of compiled jars (gems?) or similar and need an installer


Parallel straight Lines on Residuals vs. Predicted Values Plot

Question: In a data set I have, all of the results of the residual vs. predicted values  appear as parallel lines as pictured below. I interpret this according to my training as a violation of homoscedasticity which makes running a multiple regression untenable.

Here is some context about the data sets, type of analysis used, the design of the study, etc.

The type of analysis I conducted was multiple regression. In SPSS - Analyze > Regression > Linear.
The independent (predictor) and dependent (outcome) variables are all ordinal data (though I'm treating them as "scale" in the analysis). Both the independent and dependent variables represent satisfaction scores on a 7-point scale. These satisfaction scores were collected from the same participants at the same point in time (one survey). There are 4 independent variables that represent participants' satisfaction with several more granular dimensions or aspects of a service (e.g., easy to use, effective in meeting needs, etc.) The dependent variable is satisfaction overall with the service.
More about the other results from testing the multiple regression assumptions: (1) The data set passed the "independence of observations" test as measured by a Durbin-Watson statistics which was approximately 2; (2) the independent and dependent variables are approximately linearly related which was based on an inspection of the partial plots produced by the regression analysis.
There are around 20 highly influential data points out of approximately 450 participants as measured by studentized deleted residuals of over +/- 3.

I've tried transforming the data using a log transformation and this did not at all help the apparent heteroscedasticity problem. Plotting the log transformed residuals vs. predicted values yielded the same general pattern in the chart.
The other technique I tried was outlined in this paper http://afhayes.com/public/BRM2007.pdf which described providing a regression model with heteroscedasticity-corrected error residuals. The beta coefficients for each predictor variable were essentially the same as the non-heteroscedasticity corrected model, as well as the overall R^2 value for the model.
Some of the predictor variables are highly correlated with one another, but around .6 - .8 - so there may be a slight multicollinearity problem - however, the tolerance and VIF values are fine.  More intuitively, a lot of the participants provided similar satisfaction ratings for all of the predictor variables and the dependent variable. Quite a few on the 7-point scale answered things like " 7 7 7" for the predictors and "7" for the outcome or "1 1 1" and "1". However, this was not always the case.
Looking for some guidance around potential reasons for this, alternative ways to analyze the model, etc. Thanks in advance.
Comment: There was already many questions more or less similar. Search `parallel lines residuals` `diagonal lines residuals` `straight lines residuals`
Comment: Backing up, the fundamental issue is arguably not homoscedasticity at all but fitting a linear model to a outcome that is bounded (and the bounds are attained). Even if you choose to treat the outcome as measured, it is still bounded! You are clearly aware of some of the issues here but I'd underline that many researchers would regard this model as fundamentally wrong as applied to this data. As an important detail, it's hard to see that a Durbin-Watson test is pertinent here outside a time framework. Otherwise put, what order defines which observations are compared with which?
Comment: The definition residual = observed $-$ fitted necessarily implies that each distinct observed value lies on a line of negative slope when you plot residual versus fitted. Lo and behold! You have 7 lines for 7 distinct values. (Standardization as linear scaling doesn't affect this, clearly.)
Comment: Thanks for the comments. I do recognize this violates some assumptions of multiple regression and homoscedasticity is not the problem here, as the nature of the measurement instrument itself may cause this to be produced. In my experience (industrial / commercial), I'm surprised that many researchers in applied settings treat ordinal data as scale data if this is seemingly untenable in the view of the statistics community. Perhaps this is a different question, but I'm wondering if there are any resources / papers you would recommend for how to conduct regression with ordinal data?
Comment: To clarify further -- and to step away from the measurement scientist perspective for a moment -- I don't think most individuals would see reporting, for example, an "average" satisfaction score based on data from an ordinal scale as offensive. Having said that, I'm not trained enough at this time to understand how this treatment of ordinal data affects / translates into linear regression analyses and the procedure for that analysis. The interpretive convenience of R^2 / beta coefficients this analysis produces is helpful in comparison to ordinal regression.
Comment: I'd be interested in understanding the implications / caveats to keep in mind when treating ordinal data in this way in the context of multiple regression -- assuming this is even a tenable approach. If this is simply not done, I'd be interested in hearing that perspective as well. Thanks for reading!
Comment: See this very similar thread https://stats.stackexchange.com/q/33165/3277
Answer: The parallel lines are a logical consequence of the fact that your dependent variable has only a few possible values. Try and plot your dependent variable against your one of your independent variables and overlay a regression line. You will see a couple of horizontal line, and a sloping regression line. Now look at a particular value of your independent variable and see what the residuals (deviation from the regression line) is. Look at a value of your independent variable to the right and see what happens to those residuals.
Transforming your variable cannot change the fact that you have only a few possible values, so no transformation can change this pattern.
Comment: This calls for ordinal regression
Comment: Agreed with answer + comment. The fundamental problem here is not heteroskedacity; it is the level of measurement of the data, which is ordinal, rather than interval, violating the assumptions of the linear regression analysis.