Why this exception running a Spring Boot\Batch application on my server? java.lang.OutOfMemoryError: unable to create native thread:

Question: I am working on a SpringBoot\Spring Batch application. I tested it on my development machine and I found no problem . It is working fine. The problem happened when I tried to deploy it on a production machine.
First of all I say that at the momement I installed Oracle Java 17 on this prod machine in this simple way: I only downloaded the tar.gx version of the Oracle Java 17 SE from here: https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html
I extract it on this Linux Centos 7 machine, then into the bin folder I can execute java command:
firstname.lastname@example.com [~/java/jdk-17.0.1/bin]# pwd
/home/webadmin/java/jdk-17.0.1/bin
firstname.lastname@example.com [~/java/jdk-17.0.1/bin]# ./java -version
java version "17.0.1" 2021-10-19 LTS
Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.1+12-LTS-39, mixed mode, sharing)
email@example.com [~/java/jdk-17.0.1/bin]#

I am not sure that it is totally corect but untill now it seems to works because I am obtaining the Java version as output.
Then I tried to execute my Spring Boot\Spring Batch application, in this way:
email@example.com [~/java/jdk-17.0.1/bin]# ./java -jar /home/webadmin/notartel-import-data-batch/UpdateInfoBatch-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.3)

2021-11-14 11:27:04.878  INFO 23288 --- [           main] c.n.u.UpdateInfoBatchApplication         : Starting UpdateInfoBatchApplication v0.0.1-SNAPSHOT using Java 17.0.1 on c00lc5-notariato.sphostserver.com with PID 23288 (/home/webadmin/notartel-import-data-batch/UpdateInfoBatch-0.0.1-SNAPSHOT.jar started by webadmin in /home/webadmin/java/jdk-17.0.1/bin)
2021-11-14 11:27:04.880  INFO 23288 --- [           main] c.n.u.UpdateInfoBatchApplication         : No active profile set, falling back to default profiles: default
2021-11-14 11:27:06.759  INFO 23288 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-11-14 11:27:06.783  INFO 23288 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-11-14 11:27:06.783  INFO 23288 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.50]
2021-11-14 11:27:06.831  INFO 23288 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-11-14 11:27:06.831  INFO 23288 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1898 ms
[2.997s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 0k, detached.
[2.998s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 0k, detached.
[3.001s][warning][os,thread] Failed to start thread - pthread_create failed (EAGAIN) for attributes: stacksize: 1024k, guardsize: 0k, detached.
2021-11-14 11:27:07.013  WARN 23288 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
2021-11-14 11:27:07.028  INFO 23288 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-14 11:27:07.046 ERROR 23288 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.9.jar!/:5.3.9]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at com.notariato.updateInfo.UpdateInfoBatchApplication.main(UpdateInfoBatchApplication.java:42) ~[classes!/:0.0.1-SNAPSHOT]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[UpdateInfoBatch-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[UpdateInfoBatch-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[UpdateInfoBatch-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[UpdateInfoBatch-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
Caused by: java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
        at java.base/java.lang.Thread.start0(Native Method) ~[na:na]
        at java.base/java.lang.Thread.start(Thread.java:802) ~[na:na]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.startDaemonAwaitThread(TomcatWebServer.java:203) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:137) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:104) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:450) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:199) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:182) ~[spring-boot-2.5.3.jar!/:2.5.3]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.5.3.jar!/:2.5.3]
        ... 16 common frames omitted

As you can see I am trying to execute my jar file but I am obtaining this exception:
Caused by: java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached

So, since on my development machine it works fine (and I am using the same Java version of my dev machine) I suppose that it should be some JVM configuration or something like this. But what?
I tried to explore what show here: http://www.mastertheboss.com/jbossas/monitoring/how-to-solve-javalangoutofmemoryerror-unable-to-create-new-native-thread/
But I have not root access on this machine so I can't perform a lot of checks. The only checks that give me an output using this webadmin user was the one related to the current number of running threads, this one:
firstname.lastname@example.com [~/java/jdk-17.0.1/bin]# cat /proc/loadavg
0.15 0.27 0.30 1/365 23666

and the number of process per user:
email@example.com [~/java/jdk-17.0.1/bin]# ulimit -a
core file size          (blocks, -c) 200000
data seg size           (kbytes, -d) 200000
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 128613
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) 200000
open files                      (-n) 100
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 35
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

This is the command that should show the count the number of processes running:
firstname.lastname@example.com [~/java/jdk-17.0.1/bin]# ps -elfT | wc -l
365

I don't know if these last system information could be relevant for this specific problem.
Why am I obtanining this error? What can I try to do to fix this issue? Or what have I to ask to the system engineer handling this server to change?
Answer:
max user processes              (-u) 35

this seems really low. You should be checking the amount of processes currently run by your user - the exception, to me, seems to indicate that this limit is hit. Thus an increase on user process limits would be needed by someone with admin rights.
Also, this:

max memory size         (kbytes, -m) 200000

isn't much either for a java app. You only get 200M total, which for most java web apps isn't enough.
Your production account seems to be configured to really low amount of resources, which would either need to be increased, or then you need to change your approach for the app and start developing it for a low-resource environment, instead of regular environment.
Comment: @AndreaNobili you should inspect what your app needs. Examine the app in your development environment and experiment with different memory values. You should use `-Xmx` and `-Xms` switches to test different memory values for the app (I assume these switches work for java 17 too, at least they are the ones for 11).
Comment: @AndreaNobili having 256MB or 512MB for java web app is quite common, so you might want to test with those values. As for user processes you just need to check also that how many processes you have running. Something like 128 or 256 user processes as limit does not sound too much to ask. The default is allowing 1024 user processes.
Comment: @AndreaNobili also, your development machine should really match your production machine, otherwise you will get unpleasent surprises like this in the future too
Comment: Thank you for the information. Just to better understand. I checked with my development machine configuration and in effect I have very different values:
(max user processes (-u) 31434 and max memory size unlimited). I will ask if it is possible to increase these values. Just to better understand. Do you think that these are global system values or set for this specific user?
Comment: @AndreaNobili these are values that have been set for this user account as limits by the system administrator.
Comment: Ok, can you please suggest me some possible values to be changed?
Comment: is it possible to set the perocess number on java execution?
Comment: @AndreaNobili like I said, these are settings controlled by the system administrator.


Porque é necessário colocar public static void main(String[] args)?

Question: Quero entender a real intensão dessa linha de comando, o que ela faz ? Meu professor não comentou sobre ela apenas iniciou o projeto com ela, nesse caso criei o código:
<code>package exemplo;

import java.util.Scanner;

public class Exemplo {
    public static void main(String[] args) {
    Scanner teclado=new Scanner(System.in);
    float salario_base,salario_liquido;
    System.out.println("Informe seu salário bruto:");
    salario_base=teclado.nextFloat();
    salario_liquido=(float)(salario_base*1.20*0.93);
    System.out.println("O salário líquido é:" + salario_liquido);

    }

}
</code>
Mas pra que está servindo a publublic...
Answer: Ela é a função main do programa, ou seja, a função principal. Ela será chamada sempre que você executar o seu código, portando, o compilador só irá executar o código que estiver dentro dessa função.
Se você ainda não teve muito contato com programação, e ainda não saiba o que é uma  função, não se prenda a esses detalhes, seu professor não comentou porque talvez não seja uma informação muito útil no momento.
Se você quiser saber o significado mais detalhado desta função veja o link abaixo:

O que significa public static void main(String[] args)?


Delayed (dynamic) loading of framework(or dylib) on Mac

Question: I'm trying to load a framework (or dylib) on mac where I know the path only at runtime.
Windows solution:

Link library with /DELAYLOAD
Just before a function from the library is used, change the current directory in the program to the directory where the dll resides
Call some function from this library. The dll is loaded from the current directory

On mac, I can use weak linking to make the application startup without the library being available yet. However, as soon as some function from the library is needed, I get "image not found", and the application is aborted.
How can I tell the Mac dynamic linker during runtime where to look for the library? "dlopen" does  not work, since it only loads the library and does not resolve the symbols. Setting rpath to "." (the current directory) and changing the current directory does not work. Setting typical environment variables (DYLD_LIBRARY_PATH) only works when done before running the executable, not during runtime.
Any other ideas?
Answer: Write a wrapper script or executable that discovers the path at runtime, add the path to DYLD_LIBRARY_PATH, then calls execve to the real executable.
Answer: Use dlopen() to open the library and then dlsym() to find the symbols. If you are relying on the dynamic linker, you must know the path in advance and set it either via the rpath or with environment variables. The rpath can take relative paths, so that may work for you... but most likely, dlopen() and friends is the best solution here (although it may take some work to convert to using function pointers).
The advantage of dlopen() etc, is the same (or similar) code will work on other *nix's.
You can also look at NSAddImage(), which is OSX specific but should also do what you want.
Comment: As mentioned, dlopen and dlsym are not what I'm looking for since I'd have to rewrite all the code. Very cumbersome for c++ classes. Also, rpath does not work since I cannot change it during runtime. I didn't know NSAddImage. Will it link the symbols correctly to the already loaded but lazily linked symbols used in the code?


Doing a "linear regression" with 2d points under a linear transformation

Question: Let's say I have a list of 2D points $\vec v_i = (x_i,y_i)$ and the list of points after some linear transformation $\vec v_i'= A\vec v + b + \epsilon_i$ where $\epsilon_i$ is some deviation assumed to be small compared to the position. Is there a way to find the "best fit" matrix $A$ and displacement $b$, like there is in normal linear regression?
Example in R:
<code>points <- matrix(runif(2000), nrow = 2)
plot.points <- function(p) {
  transpose <- t(p)
  qplot(x = transpose[,1], y = transpose[,2]) + xlim(c(-5,5)) + ylim(c(-5,5))
}

set.seed(34)
A = matrix(runif(4, -1, 1), ncol = 2)

           [,1]       [,2]
[1,] -0.1104629  0.7697880
[2,]  0.9970808 -0.5231481

## b is just (2,2)
b = matrix(rep(2, 2000), nrow =2)

library(ggplot2)
plot.points(points)
plot.points(A%*%points + b)

## is there a way to reverse engineer A and b
## assuming we have points and A%*%points + b?
</code>
Comment: Is it possible the components of the deviation could be correlated?  If not, you have two separate linear regression problems, one for each component of $v$.  If so, you need an honest-to-goodness bivariate regression solution.
Comment: I was thinking about doing something like that, but the problem is specified a little differently than standard linear regression. In linear regression you have the response variable for each $x$: $y$. In this case I have a set of points, `points` and another set of points `A%*%points + b` but no direct correspondence between any two points in the sets. This makes it hard to do least squares because, what is the error for a given $\vec v$? The average distance to each $\vec v'$? I wasn't sure if the math for that holds up the same as in standard linear regression.
Comment: If there is no direct correspondence then there is little you can do, just as you can say almost nothing about the slope when given two sets of one-dimensional points.  But your question as asked strongly implies there *is* such a correspondence: any reader could be forgiven for supposing the two lists give the corresponding points in order.
Comment: Perhaps my question is ill-posed then, but I think the equivalent question in one dimension would be: given two sets of numbers $x$ and $y$, find $a$ and $b$ such that $ax + b$ "fits" $y$ as best as possible, where I can't think of a good measurement of "fits" and perhaps that is why my question is ill posed. The measure of "fit" could potentially be the sum of the squared errors between all of the points $\sum_{ij} (x_i - y_j)^2$ but I'm not sure.
Comment: Perhaps I will post a second question with the 1d version of this problem @whuber
Answer: A simple way that avoids having to solve equations or invert matrices is by defining the linearly independent functions $f_1(x,y) = 1$, $f_2(x,y) = x$, and $f_3(x,y) = y$ and then using Gram-Schmidt to create an orthogonal basis for the 3-dimensional vector space spanned by the 3 functions. If we take the first basis vector $e_1(x,y)$ to be $f_1(x,y) = 1$, then the next one $e_2(x,y)$ becomes:
$$e_2(x,y) = f_2(x,y) - \frac{\left\langle f_2,e_1\right\rangle}{\left\langle e_1,e_1\right\rangle}e_1(x,y) = x - \frac{1}{N}\sum_{i=1}^{N}x_i = x - \left\langle x\right\rangle$$
The third basis vector is:
$$\begin{split}
e_3(x,y) &= f_3(x,y) - \frac{\left\langle f_3,e_1\right\rangle}{\left\langle e_1,e_1\right\rangle}e_1(x,y) - \frac{\left\langle f_3,e_2\right\rangle}{\left\langle e_2,e_2\right\rangle}e_2(x,y)\\ &= y - \left\langle y\right\rangle - \frac{\left\langle xy\right\rangle - \left\langle x\right\rangle \left\langle y\right\rangle }{\left\langle x^2\right\rangle - \left\langle x\right\rangle^2}\left(x - \left\langle x\right\rangle\right)
\end{split}
$$
The best fit to the data is given by the projection on the 3-dimensional linear space of each of the two components of $\vec{v}' = (q_1,q_2)$. If the errors were exactly zero, we would have:
$$q_1(x,y) = \frac{\left\langle q_1,e_1\right\rangle}{\left\langle e_1,e_1\right\rangle}e_1(x,y) + \frac{\left\langle q_1,e_2\right\rangle}{\left\langle e_2,e_2\right\rangle}e_2(x,y) +\frac{\left\langle q_1,e_3\right\rangle}{\left\langle e_3,e_3\right\rangle}e_3(x,y)  $$
and
$$q_2(x,y) = \frac{\left\langle q_2,e_1\right\rangle}{\left\langle e_1,e_1\right\rangle}e_1(x,y) + \frac{\left\langle q_2,e_2\right\rangle}{\left\langle e_2,e_2\right\rangle}e_2(x,y) +\frac{\left\langle q_2,e_3\right\rangle}{\left\langle e_3,e_3\right\rangle}e_3(x,y)$$
in case of random errors this yields the least squarest fit. The inner products are readily expressed in terms of averages of the measured quantities, so, all the coefficients are easily obtained.


How can I know if a piano is worth saving? I am a repurposer of old woods

Question: I am a certified master repurposer, and I want to disassemble old pianos in order to repurpose the beautiful woods and workings, but I don't want to take apart a piano that still has a musical future. So many are available for free; so many go to the dump. Very sad.
I see some hints elsewhere on this site. Any more clues?
Thanks in advance. If you want to see what artisans are doing with disassembled pianos, go to pinterest and look at https://www.pinterest.com/pin/522417625498172672/
Comment: @user45266 - common sense should prevail. It often does here. The ideas are very interesting! Thanks, OP.
Comment: Dear SE: Just because there's a link to a site doesn't make it spam. This question does not "exist onloy to promote a product or service" and should not be closed, in my opinion. Too often good questions are flagged down because of a minor issue like this one.
Comment: Anything is better than going to the dump!! If you have the means of moving pianos you can charge people to pick up free pianos and deliver them to their house. This is how we got our free piano, paid to have it moved. If you don't know anything about pianos it might to be hard to tell at first glance if it worth saving.
Answer: If you don't mind spending a little money, find a piano tuner or repairman and pay a chunk of $$ to have them tell you what the restoration cost would be and what the final value would be.  You can then decide for yourself how you feel about dismantling each piano.
I can tell you that the vast majority of pianos that you can get for small cash are either beyond hope or never much good to begin with.  Unlike, say, top-notch string instruments, new pianos have great sound the moment they leave the factory, and hundreds if not thousands are produced every year, so I wouldn't worry too much about zombifying older ones.
Comment: I can agree except when encountering instruments from before 1900 since salvageable pianos from before then are quite rare (and the older the rarer) and important historical sources.
Answer: If the tuning pinblock, bridge, soundboard, and bass strings are intact it may be worth saving.  Not necessarily for a profit, but if there is the possibility of tuning, it might be valuable still.
Comment: I think the point is: how does the OP evaluate these?


question about double sums

Question: Suppose we have an expression
$$ \sum_{1 \leq k < j \leq n } f(k)f(j) $$
Can we express this as a double sum like
$$ \sum_{k=1}^n \sum_{j=1}^n f(k)f(j) $$
???
Answer: I'd rather say:
$$\sum_{1\leq k\leq j\leq n}f(j)\,f(k)=\frac{1}{2}\left(\left(\sum_{h=1}^{n}f(h)\right)^2+\sum_{h=1}^{n}f(h)^2\right),$$
$$\sum_{1\leq k< j\leq n}f(j)\,f(k)=\frac{1}{2}\left(\left(\sum_{h=1}^{n}f(h)\right)^2-\sum_{h=1}^{n}f(h)^2\right).$$
Answer: Not quite. As $k$ ranges from $1$ to $n-1$, $j$ ranges from $k+1$ to $n$. So you should have $$\sum_{k = 1}^{n-1} \sum_{j = k+1}^n f(k)f(j)$$
Answer: Say $n=3$. The original sum contains only the red terms in this matrix:
$$
\begin{bmatrix}
f(1)f(1) & \color{red}{f(1)f(2)} & \color{red}{f(1)f(3)} \\
f(2)f(1) & f(2)f(2) & \color{red}{f(2)f(3)} \\
f(3)f(1) & f(3)f(2) & f(3)f(3) \\
\end{bmatrix}
$$
However, your proposed sum contains all of the terms in the matrix!
This isn't hard to fix, though. Notice that the matrix is symmetric because $f(j)f(k) = f(k)f(j)$, so the original sum is half your sum, once you get rid of the diagonal terms:
$$
\sum_{1 \leq k < j \leq n } f(k)f(j) = \frac{1}{2}\left[ \sum_{k=1}^n \sum_{j=1}^n f(k)f(j) - \sum_{k=1}^n f(k)f(k)\right].
$$
Then you get Jack's answer by recognizing that
$$
\sum_{k=1}^n \sum_{j=1}^n f(k)f(j) = \sum_{k=1}^n f(k) \times \sum_{j=1}^n f(j)=\left( \sum_{k=1}^n f(k) \right)^2.
$$
Answer: No. You haven't taken into account the middle inequality in $1\leq k<j\leq n$. So your second sum should be $$\sum_{k=1}^n\sum_{j=k+1}^nf(k)f(j).$$
Comment: Note: the question was edited to make the middle inequality strict, the inner sum should then start at $j = k+1$ to accommodate the change.

question about double sums


How to make Stream.Write() output in UTF-8 format

Question: My issue is this:
I am generating and uploading a SQL file using ASP.NET, but after the file is saved to the FTP server, characters like ü are changed to &uul, ø to ø and so on... How can I prevent this from happening? I don't want the file to be formatted with ASCII code, but with UTF-8.
The code that generates and uploads the file looks  like this:
//request = the object to be made an request out of.
Stream requestStream = request.GetReguestStream();
var encoding = new UTF8Encoding();
//fileContent is the string to be saved in the file
byte[] buffer = encoding.GetBytes(fileContent);
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();

As you can see I've tried to use the System.Text.UTF8Encoding, but it doesn't work.
Comment: The error could be on the receiving side...
Comment: Opps, the second ø there is supposed to be & oslash; without the space.
Comment: It is far more likely to be the FTP side of things causing this issue than it is with the stream writing. But you've not shown that code.
Comment: Oh, I hoped it wasn't but its propably the ftp-side that's causing the trouble then. Thanks :)
Answer: Remember, with streams you can almost always wrap the streams as necessary. If you want to write UTF-8 encoded content you wrap the request stream in a StreamWriter with the correct encoding:
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8)) {
  writer.Write(fileContent);
}

Since you say you're uploading to a web service be sure to set your content encoding as well. Since you haven't posted where the request object comes from, I'll assume it's a normal HttpWebRequest.
With a HttpWebRequest you would tell the server what the content encoding is by using the ContentType property.
request.ContentType = "text/plain;charset=utf-8";

As others have mentioned, though, the FTP transfer itself may be breaking it too. If you can, make sure it's transferred in binary mode, not ASCII mode.
Answer: Put it in debug and look at what gets put in 'buffer' after encoding.GetBytes() is called. This will verify if it's the rx side causing it.


Showing the integral $\int_{\mathbb{R}} \int_{\mathbb{R}} \min\{ 1, (\max \{ |x|,|y| \})^{-3} \} dx dy$ converges

Question: I am trying to bound the following integral: $\int_{\mathbb{R}} \int_{\mathbb{R}} \min\{  1, (\max \{ |x|,|y| \})^{-3}   \} dx dy$.
I am very sure this integral converges, but whatever I try seem to get messy very quickly. Is there a non-very messy approach for this? Thank you very much!
Comment: Hint - Outside a big enough ball around $0$, the integral is bounded.
Comment: I have been trying something like that, but I am having trouble make it rigorous...
Comment: What about substituting $\max\{|x|,|y|\}^{-3} = \min\{|x|^{-3},|y|^{-3}\} \leq |x|^{-3} + |y|^{-3}$. Then the primitive to $x$ becomes something like $|x|^{-2}$ and the primitive to $y$ becomes something like $|y|^{-2}$, which is finite for $x,y > 1$. Also the volume of the half cube $[-1,1]\times[1,1]\times [0,1]$ is added to that. Now you've found a finite upper bound, and trivially 0 is a finite lower bound.
Answer: It is not difficult to compute the integral exactly, by symmetry.
Let $D=\{(x,y)\in\mathbb{R}^+\times\mathbb{R}^+: y\leq x\}$. Then:

$$\begin{eqnarray*} I = 8\iint_{D}\min\left(1,\frac{1}{x^3}\right)\,dx\,dy &=& 8\int_{0}^{+\infty}\int_{0}^{x}\min\left(1,\frac{1}{x^3}\right)\,dy\,dx\\&=&8\int_{0}^{+\infty}\min\left(x,\frac{1}{x^2}\right)\,dx\\&=&8\int_{0}^{1}x\,dx + 8\int_{1}^{+\infty}\frac{dx}{x^2}=\color{red}{12}.\end{eqnarray*}$$
Answer: Let $ f(x,y)=\min\{  1, (\max \{ |x|,|y| \})^{-3}   \}\leq 1$.
Then
$$
|x|\geq 1\vee |y|\geq 1\Rightarrow f(x,y)=\frac{1}{[\max\{|x|,|y|\}]^3}\leq\left[\frac{1}{(|x|+|y|)/2}\right]^3\leq\left[\frac{2}{\sqrt{|x|^2+|y|^2}}\right]^3=8r^{-3}
$$
So $f$ is bounded by 1 and out of the square $Q=\{(x,y)\,|\,|x|<1,|y|<1\}$ is bounded by radial integrable funtion $r^{-3}$.
Answer: For $r^2 = x^2 + y^2 > 1$, you have $\max( |x|, |y| ) \ge \frac{\sqrt{2}}{2} r$, because a square fits inside a circle. :)
So split your integral into the the part over the unit disk (clearly finite, since the integrand is bounded) and the part outside the unit disk. Call that $I$. Then
$$
I \le \int_0^{2\pi} \int_{r=1}^\infty k^3 r^{-3}   r ~ dr ~ d\theta
$$
where $k = 2 / \sqrt{2}$ is a constant that can be ignored. The inner integrand  ($r^{-2}$) anti-differentiates to $r^{-1}/(-1)$, and evaluates to 1. The outer integral throws a factor of $2\pi$. So your integral $I$ is no more than $2\pi k^3$, hence bounded.


Modify price components from Commerce Shipping without altering the module itself

Question: I use Drupal Commerce with Commerce Shipping and Commerce Flat Rate.
I have a client who wants the shipping line item in the commerce summary cart to come before the tax line item. My problem lies in that Commerce Shipping doesn't expose the weight of each shipping service when it implements the hook_commerce_price_component_type_info as seen below.
I have tried to use the mentioned hook in one of my own modules and with a lower value for the weight. This produces an error in the Commerce Price module where it tries to do the addition array(20, -50) + 1. Somehow, the Commerce Price module creates an array of the values instead of overwriting.
The weight I'm trying to overwrite is the one in the foreach loop.
Once I have solved this, I'll need to subtract the tax component on the shipping line item, but that's another problem which I can probably figure out by myself.
Line 110 to 135 in commerce_shipping.module.
/**
 * Implements hook_commerce_price_component_type_info().
 */
function commerce_shipping_commerce_price_component_type_info() {
  $components = array();

  // Define a generic shipping price component type.
  $components['shipping'] = array(
    'title' => t('Shipping'),
    'weight' => 20,
  );

  // Add a price component type for each shipping service that specifies it.
  foreach (commerce_shipping_services() as $name => $shipping_service) {
    if ($shipping_service['price_component'] && empty($components[$shipping_service['price_component']])) {
      $components[$shipping_service['price_component']] = array(
        'title' => $shipping_service['title'],
        'display_title' => $shipping_service['display_title'],
        'shipping_service' => $name,
        'weight' => 20,
      );
    }
  }

  return $components;
}

PS. Tax rate on shipping price is not the same as my problem. DS.
Comment: Have you tried http://drupal.org/project/commerce_flat_rate ? You need shipping 2.x
Comment: Sorry, should have mentioned that. That's the module I'm using with Commerce Shipping. As far as I know, there isn't any way of setting the weight of the shipping line item's weight. I should emphasize that I don't need to change the weight of each shipping service (for the shipping pane/page), only in the review pane and the checkout pane.
Answer: If I get you correctly, you want to alter the order in where this components are displayed in the checkout process.
What I've done for minor tweaks on this area is using a preprocess of the components theme function, for example:
function mymodule_preprocess_commerce_price_formatted_components(&$variables) {
}

There you've got $variables and all the components, including the shipping ones so you can tweak some things of the display.
Answer: Try the following Hook
hook_commerce_price_formatted_components_alter
For more details on this hook refer : http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce!modules!price!commerce_price.api.php/function/hook_commerce_price_formatted_components_alter/DC


Multiple image in one post but all in one container

Question: I have been stuck in a logic in one of my projects I am working on. This is not WordPress post. I want to display multiple images may be 1,2,3.... up to 10 in a same div container, which will be uploaded from the backend system. This should be displayed in one view similar to the screen shot below.

I have tried to arrange the images in a div container without JavaScript. I am new to jQuery and finding it difficult without a clue to proceed.
Codepen sample here
I know it should possible using jQuery only.
If you need more clarification please comment I will update my question.
**

Note: Facebook post have the multiple Image upload in one view I'm trying the same Output.

**
Comment: Solution is more worth even reputation...  Don't comment out of topic SOF is not a place to chat...
Comment: what do you mean by "one view"? make an image in image editor so that it is clear what you want. And yes upload your code here.
Comment: Please see my edited description
Comment: @Preveen Kumar, Your Proud should worth anything...Useless...?
Comment: @KarthiKeyan What I would say you is, you must still clarify more on your question. Do you agree? Well, I have been working on JavaScript and jQuery till these years, but still I am unable to understand your question, even after a lot of talking with you. Is this my fault, if so, I am sorry!
Comment: IMHO, reputation is very worth, but please, do not waste it. That's all I would like to say.
Answer: I guess you might be looking for jQuery.Masonry plugin. This will arrange the images based on:

Number of images.
Screen resolution.

$(document).ready(function () {
  $('.grid').masonry({
    // options
    itemSelector: '.grid-item',
    columnWidth: 200
  });
});

  ...

Comment: Hmm... Yikes... *gives up*
Comment: Please read clearly before answer, i know the masonry, isotope .. but my requirement is different.. this is CMS img posting not possible to add code here...
Comment: what about the post detail on the right?, and CMS client can add image in there own post that time not possible to add
Comment: OKay... What kind of CMS are you using da?
Comment: @KarthiKeyan Laravel framework  ísnt cms ... its framework like symfony
Comment: We customize it to CMS
Comment: Arranging Images of an unknown size and number needs an algorithm, so you always end up with a jQuery plugin – even CSS flexbox solutions provide no help here. jQuery plugins are just code based on jQuery, so if you can run custom jQuery code, you can at least paste the plugin source in your script. A lightweight solution for masonry would be [Freetile](https://alternativeto.net/software/freetile) or [Salvattore](http://salvattore.com). If you're running your images through a PHP framework, you should at least have the option to preprocess them in a simple way, like a adding cropping container
Answer: You could use this
.post-img {
  float: left;
  width: 40%;
  max-height: 400px;
  -moz-column-count:3;
    -moz-column-gap: 3%;
    -moz-column-width: 30%;
    -webkit-column-count:3;
    -webkit-column-gap: 3%;
    -webkit-column-width: 30%;
    column-count: 3;
    column-gap: 3%;
    column-width: 30%;
}

to stack them vertically (pinterest style), css only, as demonstrated here by some guy: http://jsfiddle.net/jalbertbowdenii/7Chkz/ Or try using this plugin for a different type of layout: http://masonry.desandro.com/
EDIT
http://jsfiddle.net/ffkdurw9/ here you can see a js to alternate the column numbers based on your predifined style preferences. I assume 1 img full size, 2 images half size 3 or more you go for 3 columns
EDIT 2 css columns layout does not work with ie8, but since even Microsoft isn't supporting it anymore...you should ask for a ton of money to do that yourself :))
EDIT 3 the js provided in the fiddle above will not work properly if there are multiple elements of this format. You will need to find an equivalent to jQuery.each() or use jQuery to handle that.
Comment: Thanks, But Is it provide dynamic solution? that means 1, 2, 3, ...images. it's possible to post any number of image here.
Comment: not really no, you must assume an initial number of children. What you could do is use javascript to detect the number of children in your post-img, then pass a class based on how many columns you need (1 for 1 child, 2 for 2 children or 3 for 3 or more children I suppose). I'll update my answer with how that might look like
Comment: @KarthiKeyan I added a jsfiddle example of how you could use js to change between 3 predefined styles for the column layout
Answer: should use width and height in img tag (For Fix)
Example
.post-img {
   float: left;
   width: 40%;
   max-height: 400px;
   background-color: red; //custom
   padding: 10px; // custom
   margin: 10px; // custom
 }

.post-img img {
  max-width: 100px; // custom
  max-height: 100px; // custom
}

Comment: did you see the facebook post image upload? i need that kind of output.. in my side i'm working on that kind of output.. thanks
Comment: yeah I see it. you will need **jquery** to select and custom @KarthiKeyan :P
Answer: Use float for each image.

#image-container img{
  float:left;
  max-width:33.33%
}
Comment: Thanks for your effort but try to under stand my requirement. and post a valuable things


Como configurar múltiplos Nginx em um servidor?

Question: Preciso configurar dois servidores nginx em um servidor windows.
Um deles é responsável pelo processamento do site, e já esta operando usando as configurações padrão do nginx, o que preciso, é de outro nginx, responsável pelo streaming de mídia/videos, como eu poderia configurar-los para funcionar na mesma maquina, como ficaria a configuração?
Eu preciso de dois servidores nginx para isso ou apenas um? Daria para fazer isso com dois?... Separando as operações, caso o servidor de mídia precisasse ser desligado, e o WebServer não por exemplo?
Qual a vantagem de ter o WebServer e o servidor de mídia em um único nginx?
Configuração do WebServer nginx com apache e php, nginx.conf:
#user  nobody;
worker_processes  2;

error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    include       proxy.conf;
    index  index.html index.htm index.php;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    # Hide nginx version information.
    server_tokens off;

    # Update charset_types due to updated mime.types
    charset_types text/xml text/plain text/vnd.wap.wml application/x-javascript application/rss+xml text/css application/javascript application/json;

    root   C:/xampp/htdocs;

    sendfile        on;

    # Tell Nginx not to send out partial frames; this increases throughput
    # since TCP frames are filled up before being sent out. (adds TCP_CORK)
    tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    # Compression
    # Enable Gzip compressed.
    gzip  on;
    gzip_comp_level   5;
#    gzip_http_version 1.0;
    gzip_min_length   256;
    gzip_proxied      any;
    gzip_vary         on;
    # Compress all output labeled with one of the following MIME-types.
    gzip_types
        application/atom+xml
        application/javascript
        application/json
        application/ld+json
        application/manifest+json
        application/rdf+xml
        application/rss+xml
        application/schema+json
        application/vnd.geo+json
        application/vnd.ms-fontobject
        application/x-font-ttf
        application/x-javascript
        application/x-web-app-manifest+json
        application/xhtml+xml
        application/xml
        font/eot
        font/opentype
        image/bmp
        image/svg+xml
        image/vnd.microsoft.icon
        image/x-icon
        text/cache-manifest
        text/css
        text/javascript
        text/plain
        text/vcard
        text/vnd.rim.location.xloc
        text/vtt
        text/x-component
        text/x-cross-domain-policy
        text/xml;

    server {
        listen       *:80;
        #listen       [::]:80  default ipv6only=on;
        #server_name  localhost;
        #server_name  app.meusite.com;

        charset utf-8;

        #https://github.com/h5bp/server-configs-nginx
        include h5bp/basic.conf;

        location / {
            root   C:/xampp/htdocs;
        }

        location ~ .php$ {
            # essentially the same as passing php requests back to apache

            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:8185;
        }

        location ~ .custom$ {
            # essentially the same as passing php requests back to apache

            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:8185;
        }

        #Adding location for phpmyadmin
        location /phpmyadmin {
            proxy_pass         http://127.0.0.1:8185/phpmyadmin;
#            allow 127.0.0.1;
#            deny all;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

O que eu poderia fazer para conseguir que servidor de stream nginx funcionasse na mesma maquina com esse WebServer?
Comment: Você pretende usar dois DNS, tipo http://site.com e http://media.site.com ou tudo no mesmo domínio, tipo http://site.com e http://site.com/media/videos ?
Comment: site.com e media.site.com @rodorgas
Answer: Basta adicionar duas diretivas server. O nginx saberá diferenciar pelo domínio quem deve processar a requisição. Um exemplo de configuração seria:
server {
    listen       80;
    server_name  example.org  www.example.org;
    ...
}

server {
    listen       80;
    server_name  media.example.org;
    ...
}

Você pode testar no seu computador, sem precisar usar um DNS público, editando o arquivo hosts (Windows: C:\Windows\drivers\etc\hosts, Linux: /etc/hosts) para redirecionar os domínios site.com e media.site.com para o endereço loopback 127.0.0.1.
Não há vantagem em ter duas instâncias independentes do nginx no mesmo servidor, já que servir múltiplos domínios é algo muito convencional e, portanto, uma funcionalidade básica dos servidores HTTP.
É muito comum gerenciar essa situação usando duas pastas, sites-available e outra sites-enabled (é essa a configuração padrão em muitas distros linux). No nginx.conf, não definimos a diretiva server nenhuma vez, e ao invés disso:
[...]
http {
    [...]
    include /etc/nginx/sites-enabled/*.conf;
}

Para cada site que você precisar servir, você cria um arquivo de configuração em sites-available, esses sim com as diretivas server. Para colocar no ar, basta criar um atalho em sites-enabled e dar reload no nginx. De maneira similar, quando quiser tirar do ar basta deletar o link em sites-enabled e dar reload novamente.
Answer: Before starting, make sure LEMP stack is installed on your VPS. You can check the Nginx server status with the following command:
systemctl status nginx
Best method to host multiple websites is to create a separate document root directory and configuration file for each website. So, you will need to create a directory structure for both websites inside Nginx web root:
To do so, run the following command for each website:
mkdir /var/www/html/web1.webdock.io
mkdir /var/www/html/web2.webdock.io
Next, you will need to create sample website content for each website:
First, create a index.html file for web1.webdock.io website:
nano /var/www/html/web1.webdock.io/index.html
Add the following html markup which will be served when you connect to the site:

web1.webdock.io
Welcome to the web1.webdock.io with Nginx webserver.

Save and close the file.
Next, create a index.html file for web2.webdock.io website:
nano /var/www/html/web2.webdock.io/index.html
Add the following html markup which will be served when you connect to the site:

web2.webdock.io
Welcome to the web2.webdock.io with Nginx webserver.

Save and close the file. Then, change the ownership of both website directories to www-data:
chown -R www-data:www-data /var/www/html/web1.webdock.io
chown -R www-data:www-data /var/www/html/web2.webdock.io
Create Virtual Configuration
Next, you will need to create a virtual host configuration file for each website that indicate how the Nginx web server will respond to various domain requests.
First, create a virtual host configuration file for the web1.webdock.io website:
nano /etc/nginx/sites-available/web1.webdock.io.conf
Add the following lines:
server {
listen 80;
listen [::]:80;
root /var/www/html/web1.webdock.io;
index index.html index.htm;
server_name web1.webdock.io;
location / {
try_files $uri $uri/ =404;
}
}
Save and close the file. Then, create a virtual host configuration file for the web2.webdock.io website:
nano /etc/nginx/sites-available/web2.webdock.io.conf
Add the following lines:
server {
listen 80;
listen [::]:80;
root /var/www/html/web2.webdock.io;
index index.html index.htm;
server_name web2.webdock.io;
location / {
try_files $uri $uri/ =404;
}
}
Save and close the file. Then, enable each virtual host with the following command:
ln -s /etc/nginx/sites-available/web1.webdock.io.conf /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/web2.webdock.io.conf /etc/nginx/sites-enabled/
Next, check Nginx for any syntax error with the following command:
nginx -t
If everything goes fine, you should get the following output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Finally, restart the Nginx service to apply the configuration changes:
systemctl restart nginx
Test Your Websites
Now, open your web browser and type the URL http://web1.webdock.io and http://web2.webdock.io. You should see both websites with the content we have created earlier:
web1.webdock.io
Fonte : https://webdock.io/en/docs/how-guides/shared-hosting-multiple-websites/how-configure-nginx-to-serve-multiple-websites-single-vps


Algorithms for weighted maximum likelihood parameter estimation

Question: What are the computational or algorithmic considerations for weighted maximum likelihood parameter estimation?
That is, I want to get
$$
\theta^* = \arg\max\limits_\theta \sum_i w_i \log(\mathcal{L}(\theta|x_i))
$$
assuming we have a weight $w_i$ for each data point, such that $\sum_i w_i=1$. How is that generally done and are there alternative approaches to finding $\theta^*$?
References are appreciated in addition to full answers.
Answer: There are a number of ways to handle importance weights. Note that "weights" as a general term can be ambiguous. R's glm method, for instance, takes a weight parameter that is interpreted differently.
This paper has a good discussion of a few approaches to handling importance weights.

By far the most common approach when using stochastic optimisation methods is to just multiply each stochastic step by the importance weight for the sampled data point. This can work poorly if you have a mixture of very large and small weights. If there is less than a factor of 20 between your various weights it should work fine, although it might be slow to converge.
Another approach when using SGD optimisation is rejection sampling, with probability proportional to $w_i/w_{\max}$. This is almost never used in practice though.
Pre-sampling your dataset before applying a standard optimization algorithm is more common. Sample with replacement a new dataset with $w_i/w_{\max}$ proportional sampling. Typically you would take $2n$ to $10n$ samples, where n is the size of your original dataset.
The linked paper suggests another approach which I believe is implemented in the Vowpal Wabbit package.

The popular liblinear package supports importance weights as well. If you're using LBFGS you can specify the loss and derivative manually, including the importance weights as you have in your post.
Comment: Thanks for this very helpful answer! Do you happen to know of a citation for the pre-sampling method? Your answer is now the first hit for "weighted maximum likelihood", by the way.


Flow of vector field $V_p = \frac{d}{dt} \left|_{t=0} \right. \ p \cdot e^{2\pi it}$ on a manifold $M$ with an $S^1$-action

Question:
Let $M$ be a smooth manifold endowed with an action from the Lie group $S^1$ (identified as complex numbers of absolute value $1$) as such: $$\cdot:M \times S^1 \to M, (p,z) \mapsto p \cdot z $$ and such that $p \cdot 1 = p, \forall p \in M$ and $(p \cdot z_1) \cdot z_2 = p \cdot (z_1z_2), \forall z_1, z_2 \in S^1.$ Now define the vector field $V$ such that $$V: p \mapsto V_p, \text{ with } V_p = \frac{d}{dt} \left|_{t=0} \right. \ p \cdot e^{2\pi it}. $$

What is the flow of $V$ and why does $p \cdot z = p , \forall z \in S^1 \iff V_p=0$? I tried looking locally in a chart $(U,\varphi)$ around a point $p \in M$ and specifically finding an integral curve $\gamma_p$ of $V$ (i.e. $\gamma_p(t) = V_{\gamma_p(t)}),$ but I don't know how to get past the action of $S^1$ to specifically solve the equation and find $\gamma_p$.
Answer: The flow of $V$ is $\phi_t(x)=x.e^{2\pi it}$ since ${d\over{dt}}_{t=0}\phi_t(x)=V(x)$,
$p=p.z$ implies that ${d\over{dt}}_{t=0}p.e^{2\pi it}p={d\over{dt}}_{t=0}p=0=V(p)$. On the other hand if $V(p)=0$, $\phi_t(p)=p$ for every $t$ which is equivalent to $p.z=p$ for every $z\in S^1$.


Create a scrolling div with jquery masonry grid. Only works on resize but not on initial page load

Question: I want to create a div that houses a jquery masonry grid inside, and has a scrollbar based on browser height once the page loads The scroll bar needs to adjust in real time as the browser is resized as well. I can get it to work on resize, but not when the page initially loads. I have tried reordering the code, and writing it in several different ways. I think masonry is disabling the scroll after all of the grid items load.
Here is the jsbin: http://jsbin.com/ucEYaJay/4/. You have to resize the browser to see the scrollbar.
Answer: Is this $('.scroll-pane').load function getting called?
Try putting the setScrollPaneHeight(); at the very end of jQuery(document).ready function
Comment: I have switched those two calls a few times, and changed `$('.scroll-pane').load` to `$(document).ready(function()`. Nothing changes. I am researching asynchronous jquery and callbacks. Nothing working so far.
Answer: I found the answer based on this SO question: http://bit.ly/19C4EFB
By changing this:
    $('.scroll-pane').load($(this), function() {
        setScrollPaneHeight();
    });

to this:
    var $scrollpane = $('.scroll-pane');

    $scrollpane.imagesLoaded( function(){
        setScrollPaneHeight();
    });

Now the scrollbar loads as expected. Link to the updated jsbin http://jsbin.com/ucEYaJay/12.


enums vs. classes: code duplication, composition, extension, generics

Question:
Note: I realize that this is very similar to the question eliminating
  duplicate Enum code, but I think it may be useful to discuss this
  separately since I'm also mentioning issues like extension
  (sublclassing) and generics. I apologize if this seems redundant.

I'm implementing some optimizations in a program that I wrote a while ago. The current one attempts to eliminate code duplication that occurred as a result of the lack of support for abstract enums in Java (...and of sub-optimal design, I'll admit it).
Here's a simplified version of the current problem.
There's an interface IConfigResourceDescriptor that provides the necessary information to load some XMLs into certain classes (which implement IResourceRoot):
public interface IConfigResourceDescriptor {
    String getResourceName();
    String getResourceLocation();
    <T extends IResourceRoot> Class<T> getRootClass();
    IConfigType getConfigType();
    ...
}

I have different sets of configurations that can be defined by different applications or different parts of the same application depending on what is required there.
For example here I show 2 sets, ResourceDescriptorA and ResourceDescriptorB, such that one is more oriented towards the business logic (ResourceDescriptorA) and the other towards the user interface (ResourceDescriptorB). As you can see their code is identical; the only reason they're separate is that it makes sense to keep these 2 sets of configurations independent from each other, but from the point of view of their implementation they're exactly the same.
public enum ResourceDescriptorA implements IConfigResourceDescriptor {
    MODEL("model.xml", "config/", Model.class, ConfigTypeA.MODEL),
    RULES("rules.xml", "config/validation/", Rules.class, ConfigTypeA.RULES),
    HELP("help.xml", "config/", Help.class, ConfigTypeA.HELP);

    private String resourceName;
    private String resourceLocation;
    private Class<? extends IResourceRoot> rootClass;
    private IConfigType configType;

    private <T extends IResourceRoot> ResourceDescriptorA(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        this.resourceName = resourceName;
        this.resourceLocation = resourceLocation;
        this.rootClass = rootClass;
        this.configType = configType;
    }

    public String getResourceName() {
        return resourceName;
    }
    public String getResourceLocation() {
        return resourceLocation;
    }
    public <T extends IResourceRoot> Class<T> getRootClass() {
        return rootClass;
    }
    public IConfigType getConfigType() {
        return configType;
    }
    ...
}

public enum ResourceDescriptorB implements IConfigResourceDescriptor {
    DIALOGS("dialogs.xml", "config/", Dialogs.class, ConfigTypeB.DIALOGS),
    FORMS("forms.xml", "config/", Forms.class, ConfigTypeB.FORMS),
    MENUS("menus.xml", "config/", Menus.class, ConfigTypeB.MENUS);

    private String resourceName;
    private String resourceLocation;
    private Class<? extends IResourceRoot> rootClass;
    private IConfigType configType;

    private <T extends IResourceRoot> ResourceDescriptorB(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        this.resourceName = resourceName;
        this.resourceLocation = resourceLocation;
        this.rootClass = rootClass;
        this.configType = configType;
    }

    public String getResourceName() {
        return resourceName;
    }
    public String getResourceLocation() {
        return resourceLocation;
    }
    public <T extends IResourceRoot> Class<T> getRootClass() {
        return rootClass;
    }
    public IConfigType getConfigType() {
        return configType;
    }
    ...
}

Solution
My idea is to move the code to a helper class and reference that from the enums.
Also, to avoid having lots of methods that just wrap invocations to the actual IConfigResourceDescriptor (the helper class), I've defined a new interface IConfigResourceDescriptorProvider which simply returns the IConfigResourceDescriptor, which then can be used to get the actual description of the configuration.
The enums now implement IConfigResourceDescriptorProvider rather than IConfigResourceDescriptor.
New helper class which contains the actual implementation:
public class ConfigResourceDescriptor implements IConfigResourceDescriptor {

    private String resourceName;
    private String resourceLocation;
    private Class<? extends IResourceRoot> rootClass;
    private IConfigType configType;

    public <T extends IResourceRoot> ConfigResourceDescriptor(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        this.resourceName = resourceName;
        this.resourceLocation = resourceLocation;
        this.rootClass = rootClass;
        this.configType = configType;
    }

    public String getResourceName() {
        return resourceName;
    }
    public String getResourceLocation() {
        return resourceLocation;
    }
    public <T extends IResourceRoot> Class<T> getRootClass() {
        return rootClass;
    }
    public IConfigType getConfigType() {
        return configType;
    }
    ...
}

New interface implemented by the enums. It simply returns the actual descriptor:
public interface IConfigResourceDescriptorProvider {
    IConfigResourceDescriptor getResourceDescriptor();
}

The enums are simplified: the constructor creates a ConfigResourceDescriptor (helper class) using the values of the parameters. The ConfigResourceDescriptor is the actual descriptor.
public enum ResourceDescriptorProviderA implements IConfigResourceDescriptorProvider {
    MODEL("model.xml", "config/", Model.class, ConfigTypeA.MODEL),
    RULES("rules.xml", "config/validation/", Rules.class, ConfigTypeA.RULES),
    HELP("help.xml", "config/", Help.class, ConfigTypeA.HELP);

    private IConfigResourceDescriptor resourceDescriptor;

    private <T extends IResourceRoot> ResourceDescriptorA(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        resourceDescriptor = new ConfigResourceDescriptor(resourceName,
                  resourceLocation, rootClass, configType);
    }

    public IConfigResourceDescriptor getResourceDescriptor() {
        return resourceDescriptor;
    }
}

public enum ResourceDescriptorProviderB implements IConfigResourceDescriptorProvider {
    DIALOGS("dialogs.xml", "config/", Dialogs.class, ConfigTypeB.DIALOGS),
    FORMS("forms.xml", "config/", Forms.class, ConfigTypeB.FORMS),
    MENUS("menus.xml", "config/", Menus.class, ConfigTypeB.MENUS);

    private IConfigResourceDescriptor resourceDescriptor;

    private <T extends IResourceRoot> ResourceDescriptorB(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        resourceDescriptor = new ConfigResourceDescriptor(resourceName,
                  resourceLocation, rootClass, configType);
    }

    public IConfigResourceDescriptor getResourceDescriptor() {
        return resourceDescriptor;
    }
}

The fact that ConfigResourceDescriptor is a class and not an enum also means it can be extended to provide extra functionality. Maybe then I'll have a ResourceDescriptorProviderC that instantiates AdvancedConfigResourceDescriptor instead of ConfigResourceDescriptor and will be able to provide more functionality:
public class AdvancedConfigResourceDescriptor extends ConfigResourceDescriptor {
    // additional methods
}

The fact that now the enumerations do not implement IConfigResourceDescriptor but rather IConfigResourceDescriptorProvider means that where I used to do...
ResourceDescriptorProviderA.MODEL.getResourceName();

...now I have to do...
ResourceDescriptorProviderA.MODEL.getResourceDescriptor().getResourceName();

...but the use of resource descriptors is very centralized in my code and I only need to make a few changes. I like this better than having to define all the wrapper methods in all the enums that implement the interface.
I don't have any external contract so I won't break any client by changing this.

And the question is...
Is this ok or is there anything I'm not anticipating that could be problematic? Do you see any big (or small, or medium) no-nos in this approach? Is there a better approach?
This is something that has come up repeatedly and I'm never sure what the correct approach is.
I tried to look for good and bad practices concerning the use of enums but (surprisingly enough) I only found very basic stuff or examples that are too specific to be of use for me. If you can recommend good articles/blogs/books that I could read on the subject I would also appreciate it.
Thank you!

Generics
Another advantage of using a class instead of an enum is that I can make it (and the interface IConfigResourceDescriptor) generic:
public interface IConfigResourceDescriptor<T extends IResourceRoot> {
    String getResourceName();
    String getResourceLocation();
    Class<T> getRootClass();
    IConfigType getConfigType();
    ...
}

public class ConfigResourceDescriptor<T extends IResourceRoot> implements IConfigResourceDescriptor<T> {

    private String resourceName;
    private String resourceLocation;
    private Class<T> rootClass;
    private IConfigType configType;

    public ConfigResourceDescriptor(String resourceName,
       String resourceLocation, Class<T> rootClass, IConfigType configType) {
        this.resourceName = resourceName;
        this.resourceLocation = resourceLocation;
        this.rootClass = rootClass;
        this.configType = configType;
    }

    public String getResourceName() {
        return resourceName;
    }
    public String getResourceLocation() {
        return resourceLocation;
    }
    public Class<T> getRootClass() {
        return rootClass;
    }
    public IConfigType getConfigType() {
        return configType;
    }
    ...
}

Answer: I cannot see any problems with your approach. There is one potential future issue you may come across but it should be easily avoided.
The issue will arise when you wish to add functionality to your enums. It may then be a little unnerving deal with the fact that the data attached to the enum is in a surrogate object while the functionality is in the enum especially if the functionality depends on the data.
I like your approach and intend to investigate its use for myself.
Meanwhile there are two other techniques you may like to experiment with.
One similar to yours but the enum is an inner-class of an object which inherits from a generic superclass whose generic type includes the enum. Here is a post containing an example. The trick here is to pass an EnumSet of the enum to the parent constructor so it can provide common functionality.
The second technique may be of less interest to you because it actually involves making a proxy combination of an enum and another object. Here is a recently posted example.
Comment: Thank you for your answer. I think I'll stick to my implementation but I quite like what you posted in your [first link](http://stackoverflow.com/questions/14772855/making-a-code-using-enum-generic/14773325#14773325). I'll definitely keep that in mind if I run into that situation.
I'll wait a bit before marking this as the answer but it'll probably be the one :)
Thanks again!


Reading random text file in R

Question: I have about 500 text documents stored in a directory.  I want to randomly select one to read in the contents (this process will be repeated several times).  The names of the files are not sequential.  By this I mean they are not named something like 1.txt, 2.txt, 3.txt,...   The names are basically random characters.
How can I do this?
Thanks
Answer: First, select one file randomly from the current directory:
file <- sample(list.files(), 1)

Then do whatever you want  with it, e.g. read all lines:
readLines(file)

If you want to repeat this several times, you could do it in one step:
readLines(sample(list.files(), 1))

Answer: Do a list.files and then access each file by its index.
 lisfil <- list.files("E:\\Data") #Replace E:\\Data with your directory name
 lenlisfil <- length(lisfil)
 for (i in 1:lenlisfil) {
    #Do something to the current file such as:
    print(lisfil[i])
 }

Comment: You need to shuffle `listfil` somewhere in your code.
Comment: @chl: I assumed that getting the filenames into a variable was his main question.
Comment: Yes, I just re-read the question and it makes sense as filenames are assumed to follow no particular order.

Reading random text file in R


Executar código JavaScript no VS Code

Question: Não estou conseguindo executar códigos js através do VS code.
Usando a recomendação de um post instalei o Code Runner usando o Control+Alt+N ou F1. Sempre tinha a seguinte mensagem :

[Running] node "c:\Users\thiag\OneDrive\Documentos\Udemy\Desenvolvimento-Web-udemy\Seção 8 - JavaScript\163 - atividades-para-fixacao-do-conteudo\1.js"
  'node' is not recognized as an internal or external command,
  operable program or batch file.
[Done] exited with code=1 in 0.207 seconds

Então instalei o Quokka.js. A mensagem acima se repediu e o código não foi executado.
Alguém pode me ajudar ?
Código :
<code>console.log('Teste')
</code>
Comment: Eu não entendi muito bem, mas se tu criar um arquivo html que chame ou execute esse arquivo no navegador, não te resolveria?
Comment: Sim, mas o desejo era executar direto no  vs code.
Comment: Talvez esse link te ajude: https://stackoverflow.com/questions/31778413/run-javascript-in-visual-studio-code
Comment: Foi um dos links que deixei na pergunta. Já li esse post.
Answer: Amigo, pela mensagem de erro você não deve ter o nodejs instalado em sua maquina.
Javascript é uma linguagem originalmente criada para rodar no client side, mas com o nodejs você pode usar ela como um script no server-side.
Para poder executar seus arquivos .js no terminal como se fossem um script você precisa instalar o Node.js.
Answer: Como o colega disse, o pré-requisito é instalar antes o Node. Porém, não precisa instalar nenhuma extensão adicional. Vá no menu Run > Add Configuration, "selecionar a opção Node.js (na command pallet) e salvar o arquivo (criado), sem necessidade de configurações adicionais". Isso irá criar um arquivo launch.json para o projeto (numa subpasta oculta ".vscode"), de uso exclusivo do VS Code, evitando que ele sempre pergunte qual o environment ou interpretador que você quer usar.
Fonte: Duarte, Luiz. Programação Web com Node.js: Completo, do Front-end ao Back-end . LuizTools. Edição do Kindle - Amazon.
Para executar, teclar Ctrl + F5 ou F5. Para depurar passo-a-passo, teclar F10.
Outra alternativa bastante prática seria instalar a extensão "Node Exec" e executar apenas teclando F8.

Executar código JavaScript no VS Code


SSH Duplicates Text With Forced PTY

Question: Can someone explain why SSH duplicates stdin back to to the screen when PTY allocation is forced and how I can disable it?
~% ssh -V
OpenSSH_5.5p1 Debian-6+squeeze2, OpenSSL 0.9.8o 01 Jun 2010
~% echo "This should only show up once." | ssh server.tld -tt '/bin/cat'
This should only show up once.
This should only show up once.

Answer: This actually turned out to be a pretty simple fix that I feel silly for overlooking. When you use -tt with SSH, SSH creates a pty but leaves the echo functionality enabled. To keep the text from being echoed back, prefix the command with stty -echo like so: ssh -t server.tld "stty -echo && command"
Answer: I'm going to take a long shot here and guess that this is the local echo of the pty that you allocated. STDIN is being treated as the input of your terminal which is then being echoed back to you.
Off the top of my head I can't think of a sane way to deal with this, and I'm honestly inclined to say that it's not a good idea to try to do this anyway.
If you reply with a comment on why you feel that you must implement something this way, I will try to help you find an alternative solution out of band. I do not think that it will change this answer, however.
Comment: In what I have seen, I figured there probably is not an elegant solution to this problem. Right now, I am resorting to creating a pty, spawning ssh with the pty configured for stdin and forwarding all stdin from the parent process to the ssh client. I am trying to wrap the ssh client so that when the ssh client is used in a pipe, on the remote server, the called process sees the same values for isatty on std(in|out|err) that it would see if it were in a pipe series locally.
Comment: Cool, that's a start. Are you able to tell me what you're trying to solve by faking the terminal? It'd help to make sure that this is in fact the best route to go.
Comment: I thought that was covered by my response. Locally, various program may change behaviour depending on whether or not you do `A | program`, `program | B`, `A | program | B` or `A | program | B 2> error.log`, etc. I need to be able to wrap any program so that the command so that it behaves the same way way in middle of a pipe even if it's across SSH.
Comment: I was reaching for specific examples I guess. It's generally not something that I've had to do in my professional career. This isn't to say that there aren't legitimate reasons why you would need to do so, but I wanted to make sure that this wasn't going in the direction of "a hack for a hack for a hack".
Comment: Off the top of my head, `ls`'s colorization looks at whether or not stdout is a TTY, and `dialog` uses stderr by default to draw dialogue boxes and controls. Honestly, I cannot think of any other programs whether this is the case, but the whole point of the wrapper is to be able to integrate any remote SSH command into a local pipe such that the behaviour is virtually identical, and making the isatty returns identical is important to ensure this. Contrived example: `echo "X" | ls --color` shows color, but `echo "X" | ssh server.tld ls --color`  does not, and forcing the tty makes dupe text.
Comment: Yeah, there is no alternative solution for that. They're designed to operate that way because the output is only designed for consumption by a real terminal. Breaking that barrier introduces problems like `ssh -tt server.tld "ls --color" > ansijunk.txt` and `ssh -tt server.tld "ls --color" | less`, which is generally why the line is not crossed. You really need the knob for this sort of behavior to be in the client side but I suspect the only workarounds you're going to find are on the serverside.
Comment: Working around the isatty values is pretty easy. Essentially, if at any of stdout, stderr or stdin returns true for isatty() for the wrapper, I just tack on a "/bin/cat |" to the front (stdin) or " | /bin/cat" to the back for stdout and stderr with some exec magic for the latter. Although kludgey, it works for all `sh` compatible shells. The only problem at this stage is that SSH PTY allocation insists on echoing text back to the screen when I force it with `-tt` which is what I need a solution for.

SSH Duplicates Text With Forced PTY


Como é que posso mostar imagens(url) da BD (MySQL) no Android Studio

Question: Como é que posso mostar imagens (url) da Base de Dados (MySQL) no Android Studio?
MainActivity.java
package com.example.APP;

import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    String urladdress="http://3m22p.dx.am/app_conexao.php";
    String[] nome;
    String[] comentarios;
    String[] imagem;
    ListView ListView;
    BufferedInputStream is;
    String line = null;
    String result = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView=(ListView)findViewById(R.id.lview);

        StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
        collectData();
        CustomListView customListView = new CustomListView(this,nome,comentarios,imagem);
        ListView.setAdapter(customListView);
    }
    private void collectData()
    {
        //conexão
        try{
            URL url = new URL(urladdress);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            is = new BufferedInputStream(con.getInputStream());
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        //Conteudo

        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine())!=null){
                sb.append(line+"\n");
            }
            is.close();
            result = sb.toString();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        //JSON

        try{
            JSONArray ja = new JSONArray(result);
            JSONObject jo = null;
            nome = new String[ja.length()];
            comentarios = new String[ja.length()];
            imagem = new String[ja.length()];

            for (int i=0;i<=ja.length();i++){
                jo = ja.getJSONObject(i);
                nome[i] = jo.getString("nome");
                comentarios[i] = jo.getString("comentarios");
                imagem[i] = jo.getString("imagens");
            }
        }
        catch(Exception ex) {

            ex.printStackTrace();
        }
    }
}

CustomListView.java
package com.example.APP;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;

public class CustomListView extends ArrayAdapter <String>{

    private  String[] nomes_col;
    private  String[] comentarios;
    private  String[] imagem;
    private Activity context;
    Bitmap bitmap;

    public CustomListView(Activity context,String[] nomes_col,String[] comentarios,String[] imagem) {
        super(context, R.layout.layout,nomes_col);
        this.context=context;
        this.nomes_col=nomes_col;
        this.comentarios=comentarios;
        this.imagem=imagem;
    }

    @NonNull
    @Override

    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){

        View r = convertView;
        ViewHolder viewHolder = null;
        if (r==null){
            LayoutInflater layoutInflater = context.getLayoutInflater();
            r = layoutInflater.inflate(R.layout.layout,null,true);
            viewHolder = new ViewHolder(r);
            r.setTag(viewHolder);
        }
        else{
            viewHolder = (ViewHolder)r.getTag();
        }

        viewHolder.tvw1.setText(nomes_col[position]);
        viewHolder.tvw2.setText(comentarios[position]);
        new GetImageFromURL(viewHolder.ivw).execute(imagem[position]);

        return r;
    }
    class ViewHolder{
        TextView tvw1;
        TextView tvw2;
        ImageView ivw;

        ViewHolder(View v){
            tvw1 = (TextView)v.findViewById(R.id.tvprofilename);
            tvw2 = (TextView)v.findViewById(R.id.tvcomentarios);
            ivw = (ImageView)v.findViewById(R.id.ImageView);
        }
    }
    public class GetImageFromURL extends AsyncTask<String,Void, Bitmap>{

        ImageView imgView;
        public GetImageFromURL(ImageView imgv){
            this.imgView = imgv;
        }
        @Override
        protected Bitmap doInBackground(String... url) {
            String urldisplay = url[0];
            bitmap = null;

            try{
                InputStream ist = new java.net.URL(urldisplay).openStream();
                bitmap = BitmapFactory.decodeStream(ist);
            }
            catch(Exception ex){
                ex.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap){

            super.onPostExecute(bitmap);
            imgView.setImageBitmap(bitmap);
        }
    }
}

BD em MySQL

Código php do ficheiro: app_conexao.php
Comment: sua pergunta é muito ampla, não consegue reduzir pra um problema mais específico? pode compartilhar o código do que já fez?
Comment: Ja pus ai em cima bro
Comment: Use a biblioteca Glide ou picasso
Comment: Como é que insiro no meu código Murilo ?
Comment: A partir do momento onde, no seu código tem  String urladdress="http://3m22p.dx.am/app_conexao.php"; isso parece significar que a base de dados esta num servidor Web, ao seja, não esta no Android.
Neste caso, não é um problema de Android mas um problema de PHP. Quem faz o codigo de app_conexao.php? Vc?
Comment: vou por o codigo do ficheiro php acima, Peter
Comment: Ah OK! Na BDD vc tem URL da imagen e vc quer mostra a imagem no Android? Isso?
Answer: Para ver no android uma imagem quando vc tem URL:
 URL url_img = new URL("http://meu_servido.com/image.jpg");
 Bitmap data_bmp = BitmapFactory.decodeStream(url_img.openConnection().getInputStream());
 imageView.setImageBitmap(data_bmp);

E suficiente mudar o nome do URL conforme na valor que tem na base de dados. Por exemple se na BDD a imagem tem so o nome (eg "casa") basta "colar" tudo junto tipo
url_img = "http://meu_servidor.com/"+nome_na_BDD+".jpg";
No caso d imagem "casa", vai dar http://meu_servidor.com/casa.jpg, no caso de "bicicleta" vai dar http://meu_servidor.com/bicicleta.jpg etc...
Comment: Mas eu não quero uma imagem em especifico, quero que cada nome tenha a sua propia imagem, que foi colocada (através de um link) na BD
Comment: Fiz modicação na resposta. Depois, depende do que vc tem na sua base. Saber se vc tem o URL completa, so um pedaço etc...
Answer: Utilize biblioteca pra fazer isso, facilita.
Primeiro acrescente a biblioteca em build.gradle(app):
implementation group: 'com.github.bumptech.glide', name: 'glide', version: '4.9.0'

Dentro do seu adapter ao invés de usar:
new GetImageFromURL(viewHolder.ivw).execute(imagem[position]);

use:
    //método da biblioteca para carregar as imagens
        Glide.with(context)
                .load(imagem[position])
                .apply(new RequestOptions()
                        .override(90, 90)). //aqui você define altura e largura em px
                into(viewHolder.ivw);

Desse modo você pode excluir o método que criou de asynctask
Comment: És o maior, oh bro FUNCIONA! Muito Obrigado.
Comment: ok Obrigado vou tentar isso
Comment: @TurmaBciccopn Se puder marcar minha resposta como útil, ajuda outros usuários.


CASE RETORNANDO MAIS DE UMA LINHA EM UMA SUBCONSULTA

Question: Estou com um problema em uma subconsulta que me retornar o tipo do pagamento (CREDITO OU DEBITO)
e se o pagamento foi em cartão ou não.

Porem, se eu tiver um pagamento com os dois tipos de cartão a subconsulta vai retornar dois registros e vai acabar quebrando, o que eu poderia fazer pra quando tiver dois tipos de pagamento eu considerar apenas um, no meu caso queria considerar apenas o credito.
Considero comissões através do tipo do pagamento; CREDITO + DEBITO = CREDITO (quero montar um case caso um dos tipos foi credito ele considere apenas o credito como tipo de pagamento)
segue o consegui fazer:
<code>CASE
        WHEN X.cartao = 'S' AND X.tipo = 'CREDITO' THEN 'CREDITO'
        WHEN X.cartao = 'S' AND X.tipo = 'DEBITO'  THEN 'DEBITO'
        WHEN X.cartao = 'S' AND X.tipo = 'CREDITO' AND X.tipo = 'DEBITO' THEN 'CREDITO' --
   ELSE 'N' END cartao,
</code>
Comment: Inclua seu `SQL`, somente seu `CASE` não faz sentido algum.
Comment: É impossível que `X.tipo = 'CREDITO'` e `X.tipo = 'DEBITO'` simultaneamente e portanto esta terceira condição nunca será satisfeita. Como você não explicou suficientemente como estão organizados seus dados talvez possam existir múltiplas linhas em sua tabela, uma para cada cartão?
Answer: Bom dia,
Acho que uma alternativa seria utilizar Top(1) com Order by dentro da subconsulta. Como 'CREDITO' vem antes de 'DEBITO' em ordem ascendente, a subconsulta deverá retornar 'CREDITO' quando existirem os 2 tipos de cartão. Ex:
<code>(
  select top(1)
    CASE
        WHEN X.cartao = 'S' AND X.tipo = 'CREDITO' THEN 'CREDITO'
        WHEN X.cartao = 'S' AND X.tipo = 'DEBITO'  THEN 'DEBITO'
        WHEN X.cartao = 'S' AND X.tipo = 'CREDITO' AND X.tipo = 'DEBITO' THEN 'CREDITO' --
        ELSE 'N'
    END cartao,
    -- ...

  order by cartao
)
</code>
Espero que ajude


Which core module provides the default send email action for use in rules?

Question: There is a core module (might be related to core actions) that allows your to send an email via VBO. What is the name or where is that function located in core?
For e.g. When I am modifying the system mail settings, what "module" in core provides this functionality? (See screenshot)
Answer: There is no "module", at least not one that can be turned on and off like other modules. Emails are normally handled by drupal_mail() and a bunch of other functions found in the system.mail.inc file under /modules/system and mail.inc found in /includes .  These work together to create the framework, using templates that you can set up in order for other modules (like VBO) to actually send emails.
drupal_mail():

Sending an e-mail works with defining an e-mail template (subject,
  text and possibly e-mail headers) and the replacement values to use in
  the appropriate places in the template. Processed e-mail templates are
  requested from hook_mail() from the module sending the e-mail. Any
  module can modify the composed e-mail message array using
  hook_mail_alter(). Finally drupal_mail_system()->mail() sends the
  e-mail, which can be reused if the exact same composed e-mail is to be
  sent to multiple recipients.
Comment: What batch of code provides the re-usable action to send mail in rules then?
Comment: I have no idea, and no reason to know. you would have to look through the Rules code for that
Comment: It's not provided by rules, it's provided by core for rules. I just need to know which core module has this functionality built in. I realize the core module that provides this functionality provides for more than this feature but one of the modules still provides it.
Comment: I don't believe there is a 'module' - it is part of the core API using drupal_mail() and related functions as indicated in the answer. I don't know why you keep thinking there's a module - most of core is done through the API, not through actual modules
Comment: I found it, it is in the system.module https://api.drupal.org/api/drupal/modules!system!system.module/function/system_send_email_action/7
Answer: VBO gets those actions from rules.
The functions are into rules module:
PATH_TO_YOUR_MODULES/rules/modules/system.rules.inc
Answer: It appears to be a part of the system.module; precisely the system_send_email_action() function.


listview not showing items android

Question: I am have sql DB and I am trying to display queried values in a listView. I  created a custom adapter for the listView.  problem is
I am not able to see any data displayed on my listView.
code of main

public class _songs_playlist extends AppCompatActivity {
    ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
    private static int SPLASH_TIME_OUT=2000;
    AlertDialog alertDialog;
    private boolean loggedIn = false;
    String type;
    String result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__songs_playlist);

        new JSONParse().execute();
        MyCustomAdapterSongs itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);

        ListView listView = (ListView) findViewById(R.id.listView1);
        listView.setAdapter(itemsAdapter);
        itemsAdapter.notifyDataSetChanged();
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
            alertDialog.setTitle("Upadting Data");
            pDialog = new ProgressDialog(_songs_playlist.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {

                HTTPHandler sh = new HTTPHandler();
                String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
                try {

                    //Fetching the boolean value form sharedpreferences

                    URL url = new URL(login_URL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                    result = "";
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    Log.e("RESULT", result);
                    JSONObject jsonObject = new JSONObject(result);

                    JSONArray result1 = jsonObject.getJSONArray("result");
                    for (int i = 0; i < result1.length(); i++) {
                        JSONObject c = result1.getJSONObject(i);
                        String id = c.getString("songID");
                        String names = c.getString("songName");
                        String ss = c.getString("singerName");
                        listofsoongs.add(new songsarray(ss,id,names));

                    }

                    return jsonObject;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;

        }

        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            if(true)

            {

            }
            else
            {

            }

        }
    }
}

code of custom array adapter

public class MyCustomAdapterSongs extends ArrayAdapter<songsarray> {

    Context context;
    ArrayList<songsarray> items;
    public MyCustomAdapterSongs(Activity context, ArrayList<songsarray> songsarrays) {

        super(context, 0, songsarrays);
        this.context=context;
        this.items=songsarrays;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.itemlist, parent, false);

        }

        TextView nameTextView = (TextView) listItemView.findViewById(R.id.textView1);

        nameTextView.setText(currentAndroidFlavor.getSingername());
        Log.e("hhhh", nameTextView.getText().toString());

        TextView numberTextView = (TextView) listItemView.findViewById(R.id.textView2);

        numberTextView.setText(currentAndroidFlavor.getSongname());
        Log.e("jjjj", numberTextView.getText().toString());

        CheckBox ch=(CheckBox)listItemView.findViewById(R.id.checkBox1);

       ch.setSelected(currentAndroidFlavor.isSelected());

        return listItemView;
    }

    @Override
    public int getCount() {
        if(items == null)
            return 0;
        return items.size();
    }

    @Override
    public songsarray getItem(int i) {
        return items.get(i);
    }

}
Answer: Call itemsAdapter.notifyDataSetChanged() within onPostExecute.
Your list is empty until the AsyncTask finishes there.
You'll have to make the adapter a member variable of the Activity class
Answer: As in your code I can see you are updating the list in doInBackground but you are not notifying the adapter for the changes.
In  onPostExecute method you need to call itemsAdapter.notifyDataSetChanged() and make sure it you are not calling it inside doInBackground as in background thread you can't to UI related work.
Answer: Check the EDITS in this code snippet

`

public class _songs_playlist extends AppCompatActivity {
    ArrayList<songsarray> listofsoongs = new ArrayList<songsarray>();
    private static int SPLASH_TIME_OUT=2000;
    AlertDialog alertDialog;
    private boolean loggedIn = false;
    String type;
    String result;

//EDIT 1: Make these member variables
    MyCustomAdapterSongs itemsAdapter;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__songs_playlist);

        //EDIT 2: get references your views before AsyncTask
        listView = (ListView) findViewById(R.id.listView1);
        new JSONParse().execute();

    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            alertDialog=new AlertDialog.Builder(_songs_playlist.this).create();
            alertDialog.setTitle("Upadting Data");
            pDialog = new ProgressDialog(_songs_playlist.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {

                HTTPHandler sh = new HTTPHandler();
                String login_URL = "http://2f179dfb.ngrok.io/getsong.php";
                try {

                    //Fetching the boolean value form sharedpreferences

                    URL url = new URL(login_URL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                    result = "";
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    Log.e("RESULT", result);
                    JSONObject jsonObject = new JSONObject(result);

                    JSONArray result1 = jsonObject.getJSONArray("result");
                    for (int i = 0; i < result1.length(); i++) {
                        JSONObject c = result1.getJSONObject(i);
                        String id = c.getString("songID");
                        String names = c.getString("songName");
                        String ss = c.getString("singerName");
                        listofsoongs.add(new songsarray(ss,id,names));

                    }

                    return jsonObject;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;

        }

        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
//EDIT 3: set your adapter here as this method will be called on the UI Thread
            itemsAdapter = new MyCustomAdapterSongs(this, listofsoongs);
            listView.setAdapter(itemsAdapter);

            }

        }
    }
}
`

listview not showing items android


Cannot add foreign key constraint

Question: Ajuda com o erro no MySql
create table cliente(
    endereco varchar(256),
    codigo integer primary key auto_increment,
    telefone varchar (18),
    tipo varchar(20)
);

create table fisica(
    cpf varchar(20),
    foreign key(cpf) references cliente(tipo)
);

Comment: Por que você possui uma tabela que só possui uma coluna, que inclusive é chave estrangeira para outra? Não faz sentido essa tabela existir, inclusive associando CPF ao tipo. Adiantando, para você criar uma chave estrangeira, a coluna na outra tabela precisa ser chave primária. O que exatamente está tentando fazer? Não ficou claro na sua pergunta.
Comment: Qual o erro que esta dando ao executar esses comandos?
Answer:

Todo cliente é uma pessoa (Pode ser Física ou Jurídica);
Toda pessoa tem um tipo (Física ou Jurídica);

Criei uma modelagem parecida com a sua mas, com alguns ajustes:
Abaixo o script para criação dos objetos:

CREATE TABLE IF NOT EXISTS `mydb`.`Cliente` (
  `codigo` INT(11) NOT NULL AUTO_INCREMENT,
  `numero_contrato` INT(11) NOT NULL,
  `dtcadastro` DATETIME NOT NULL,
  `dtrescisao` DATETIME NULL DEFAULT NULL,
  `pessoa` INT(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`codigo`),
  INDEX `fk_cliente_01_idx` (`pessoa` ASC),
  CONSTRAINT `fk_cliente_01`
    FOREIGN KEY (`pessoa`)
    REFERENCES `mydb`.`Pessoa` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `mydb`.`Pessoa` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `tipo` INT(10) UNSIGNED NOT NULL,
  `cpf_cnpj` VARCHAR(14) NULL DEFAULT NULL,
  `nome` VARCHAR(60) NULL DEFAULT NULL,
  `email` VARCHAR(150) NULL DEFAULT NULL,
  `cep` INT(11) NULL DEFAULT NULL,
  `logradouro` VARCHAR(100) NULL DEFAULT NULL,
  `numero` VARCHAR(20) NULL DEFAULT NULL,
  `complemento` VARCHAR(30) NULL DEFAULT NULL,
  `bairro` VARCHAR(70) NULL DEFAULT NULL,
  `cidade` VARCHAR(70) NULL DEFAULT NULL,
  `uf` VARCHAR(2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_pessoa_01_idx` (`tipo` ASC),
  CONSTRAINT `fk_pessoa_01`
    FOREIGN KEY (`tipo`)
    REFERENCES `mydb`.`TipoPessoa` (`codigo`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `mydb`.`TipoPessoa` (
  `codigo` INT(10) UNSIGNED NOT NULL,
  `nome` VARCHAR(20) NULL DEFAULT NULL,
  PRIMARY KEY (`codigo`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

Apenas uma dica pesquise mais sobre MER (Modelo Entidade e Relacionamento), e procure utilizar ferramentas para a modelagem, no caso do MySql você pode utilizar o Workbench não sei se conhece: https://dev.mysql.com/downloads/workbench/ ele lhe dará uma visão melhor do seu projeto :)
Espero que isso lhe ajude!

Cannot add foreign key constraint


How to pass large json result from ansible play into python script

Question: I get an 'Argument list too long' error when passing very large json result to python script from within an Ansible playbook.
The base playbook is:
<code>- name: "The Playbook"
  hosts: "localhost"

  tasks:
    - name: "Get JSON from API"
      uri:
        url: "https://my.real.api.url.goes.here.com"
        method: GET
        return_content: yes
        headers:
          Content-Type: "application/json"
          Authorization: "my api token goes here and works."
      register: result

    - name: Run Py script
      command: python get_tenants.py {{ result }}
      become: yes
      become_user: root
      register: pyout
</code>
I've also tried passing the result as:
<code>{{ result | map(attribute='content') }}
</code>
which passes a pointer to a map but not the map itself as a single item.
I've also tried passing the result as:
<code>{{ result | map(attribute='content') | list }}
</code>
Regardless, I get:
<code>"failed": true, "msg": "[Errno 7] Argument list too long", "rc": 7
</code>
How would I go about passing a large JSON result from ansible into a python script?
The first idea I had was to save the results to file and then use the file within the python script. It seems to me, however, that there has to be a better way...
Comment: If you're using Ansible 2.4+, maybe try passing it to the script via stdin instead?
Answer: Try it with a here document if your script is able to read input from STDIN:
<code>- name: "The Playbook"
  hosts: "localhost"

  tasks:
    - name: "Get JSON from API"
      uri:
        url: "https://my.real.api.url.goes.here.com"
        method: GET
        return_content: yes
        headers:
          Content-Type: "application/json"
          Authorization: "my api token goes here and works."
      register: result

    - name: Run Py script
      shell: |
        python get_tenants.py <<EOF
        "{{ result.content }}"
        EOF
      become: yes
      become_user: root
      register: pyout
</code>


Reading a angularjs promise object?

Question: I have a service that returns a study object as shown:
$scope.study = StudyService.studies.get({id: $routeParams.studyIdentifier});

When I print out the study object using:
console($scope.study);

I get this message on the chrome console:
Resource {$promise: Object, $resolved: false, $get: function, $save: function, $query:
function...}

So how do I read this study object. I like to be able to print its contents. For instance study has an id, and a list of cases. I like to be able to print:
console.log(study.id);
console.log(study.cases.length);

How do I accomplish this?
Comment: show yo code. You should make a jsfiddle.
Answer: I assume that since you are receiving a promise as a response from your service you are using 'ngResource'. If so, then here is some documentation on using that module and how to handle the objects it returns.
https://docs.angularjs.org/api/ngResource/service/$resource
For your example though, you would need to just do the following
StudyService.studies.get({id: $routeParams.studyIdentifier}).$promise.then(function(study) {
  $scope.study = study;
});

Hope this helps!

Reading a angularjs promise object?