Dúvida com a utilização de placeholder e onfocus em HTML

Question: Galera, tô criando uma tela de login onde quero usar placeholder e onfocus pra quando o user clicar na box desaparecer o que está escrito (por exemplo: "e-mail") e, caso ele apague tudo de novo, a palavra "e-mail" volte a aparecer.
Consegui fazer com o seguinte código

                <input type="password" placeholder="senha" onfocus="this.placeholder = ''" onblur="this.placeholder = 'senha'" />

Porém, preciso deixar a palavra sem esse blur e não consigo.
EDIT
Colocando o código inteiro
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Login trevoso</title>

 Login

        <input type="text" placeholder="e-mail" onfocus="this.placeholder = ''" onblur="this.placeholder = 'e-mail'" />

        <input type="password" placeholder="senha" onfocus="this.placeholder = ''" onblur="this.placeholder = 'senha'" />

ENVIAR

Esqueceu a senha?

Comment: Você já está usando ali o placeholder="Texto no campo"
Comment: @maxixilianoMeyer tente ser mais claro
Comment: Pelo que entendi, ele quer que quando o usuário apagar a senha, que reapareça o placeholder... inclui o snippet pra facilitar o entendimento, mas ainda não aprovaram a edição... não sei se dá pra fazer só com HTML... @AndréBaill
Comment: Mas @gustavox o próprio placeholder faz isso
Comment: Isso, @Gustavox. Que reapareça o placeholder, mas sem o blur
Comment: @AndréBaill olha o snippet (Executrar trecho de código)... Quando vc apaga a senha ele não volta o texto do placeholder...
Comment: Postei uma resposta com a simulação, ao meu ver, seria isso
Comment: @MaximilianoMeyer quando você diz: "sem esse `blur`" você quer dizer a cor da fonte? Tirar a cor cinza e colocar preta no placeholder?
Comment: Isso@Gerep Além disso o blur tá mudando a formatação que eu fiz, deixando a fonte maior, por exemplo, cortando a parte de cima da palavra que fica muito grande pra caixa
Comment: @MaximilianoMeyer, você pode atualizar o exemplo mostrando esse problema com a fonte?
Comment: Coloquei pra ti um exemplo, talvez seria essa sua idéia?
Comment: @Gerep Coloquei o código inteiro
Comment: @AndréBaill vou testar
Comment: @MaximilianoMeyer o seu problema com a fonte esta nesta linha `font: italic 18px/10px sans-serif;` porque você esta fazendo desse modo?
Comment: @Gerep faz parte das "intruções" da tarefa. A fonte precisa ser em itálico e ter esse tamanho. Obrigado pelo toque, reparei que tinha coisa a mais ali mesmo, tirei o 10px e ficou de boas, não corta mais o texto
Comment: @MaximilianoMeyer, na minha resposta eu expliquei um pouco melhor o que acontece nessa linha.
Comment: @MaximilianoMeyer, para ajudar a comunidade, escolha a resposta que te ajudou.
Comment: @Gerep Não havia marcado nenhum, pois para mim eles não funcionaram direitinho. Bem, marcarei a melhor resposta, pois mesmo assim poderá ajudar os demais.
Answer: Você pode usar o mesmo placeholder para elaborar isto, ao você digitar ele some, quando você remover a escrita, retorna o placeholder. Segue o exemplo.
Neste meu exemplo, você poderá trocar a cor também da escrita, creio que deva lhe ajudar.

::-webkit-input-placeholder {
   color: orange;
   font: 12px verdana, arial, sans-serif;
}

:-moz-placeholder {
   color: orange;
   font: 12px verdana, arial, sans-serif;
}

::-moz-placeholder {
   color: orange;
   font: 12px verdana, arial, sans-serif;
}

:-ms-input-placeholder {
   color: orange;
   font: 12px verdana, arial, sans-serif;
}
<input type="password" placeholder="Digite sua senha"/>
Comment: Obrigado André, mas nesse caso ele não apagou o o placeholder quando  clico no campo de inserção.
Comment: Resolveu o problema do placeholder, mas ainda não deu certo no onfocus (não apagou o que estava na tela para o usuário clicou na box)
Comment: @MaximilianoMeyer fiz um teste aqui com este código incluindo `onfocus="this.placeholder = ''"` e ele some quando clica em cima, mas não reaparece quando apaga tudo...
Answer: Cada navegador tem sua implementação (pseudo-element/class) do placeholder.

::-webkit-input-placeholder {   /* WebKit browsers */
   color: red;
}

:-moz-placeholder { /* Firefox 18- */
   color: red;
}

::-moz-placeholder {  /* Firefox 19+ */
   color: red;
}

:-ms-input-placeholder {  /* Internet Explorer 10+ */
   color: red;
}

    <input type="password" placeholder="senha" onfocus="this.placeholder = ''" onkeyup="this.placeholder = 'senha'" />

Fonte: https://css-tricks.com/snippets/css/style-placeholder-text/
Em relação a fonte não estar centralizada no input:
font: italic 18px/10px sans-serif;

Você esta definindo o tamanho da fonte e também a propriedade line-height. O problema não é definir os dois juntos, o problema esta nos valores.
Comment: @gustavox, muito obrigado pela dica, já esta atualizado: https://jsfiddle.net/ug5L491t/1/
Comment: @gustavox, atualizado também =)
Comment: Abração @gustavox e muito obrigado pela ajuda. Quem sbe um dia eu consiga te retribuir
Comment: Resolveu o problema do placeholder, mas ainda não deu certo no onfocus (não apagou o que estava na tela para o usuário clicou na box)
Comment: @MaximilianoMeyer, não entendi o problema com `onfocus()`, quando você clica no campo novamente ele deveria apagar o que o usuário digitou?!
Comment: Não. Funciona assim. Na caixa está escrito "e-mail". Com o onfocus quando o usuário clicar na caixa a palavra "e-mail" desaparecem, na verdade ela é substituída por nada, mais exatamente por " " que está setado em onfocus="this.placeholder = ''"
Comment: @MaximilianoMeyer, quando eu clico no campo, ele remove o que esta no `value` e colocar o seu `""`, o que mais você precisa que faça? É isso que não estou entendendo. Para você o "email" ou "senha" não esta sendo removido quando você clica no campo?
Comment: @Gerep, precisa que quando apagar o que foi digitado, que reapareça o placeholder.
Comment: @Gerep exatamente. Mas no exemplo que você me passou isso não está acontecendo. Está dando certo aí para você?
Comment: @MaximilianoMeyer, o placeholder volta quando você tira o foco do campo. Eu digitei um e-mail, apaguei o valor, tirei o foco do campo e o `placeholder` voltou a aparecer
Comment: @MaximilianoMeyer, sim, aqui esta funcionando perfeitamente
Comment: @MaximilianoMeyer https://jsfiddle.net/ug5L491t/, dê uma olhada por favor e veja se esta funcionando.
Comment: @MaximilianoMeyer aqui também tá funcionando, mas só volta o `placeholder` quando perde o foco, e acho que vc precisa como com `onkeyup` né...
Comment: @Gerep fiz um teste aqui, acho que se mudar seu fiddle pra `onkeyup="this.placeholder = 'e-mail'"` fica 100% o que AP precisa (btw, que navegador vc tá usando AP?)...
Comment: Lembra de arrumar também na resposta (no snippet). Dei +1 na sua resposta, e acho que solucionou né @MaximilianoMeyer? Se tiver solucionado, não esqueça de dar um voto positivo e marcar a resposta como aceita.
Comment: Obrigado pela ajuda galera. Abração. Vou dar o +1 sim
Comment: Vou aceitar sim, é que tô testando aqui ainda uheuheh.


Pivot Longer with Multiple Variables at Once

Question: I have a dataset that looks like the first image and I want to make it look like the second image. I can pivot_longer by either age or speed, but not both at the same
top is original, bottom is what I want to pivot to
Answer: We can use pivot_longer with names_sep
library(tidyr)
pivot_longer(df1, cols = -ID, names_sep="_", names_to = c(".value", "grp"))

-output
# A tibble: 8 x 4
#     ID grp     age speed
#  <int> <chr> <dbl> <dbl>
#1     1 t1       10   100
#2     1 t2       11   300
#3     2 t1       11   500
#4     2 t2       12   100
#5     3 t1       10   200
#6     3 t2       11   300
#7     4 t1       12   100
#8     4 t2       13   400

If the column names have multiple _, then we can use a regex lookaround
names(df1) <- c("ID", "age_T1", "age_T2", "speed_total_T1", "speed_total_T2")
pivot_longer(df1, cols = -ID, names_sep="_(?=T)", names_to = c(".value", "grp"))

-output
# A tibble: 8 x 4
#     ID grp     age speed_total
#  <int> <chr> <dbl>       <dbl>
#1     1 T1       10         100
#2     1 T2       11         300
#3     2 T1       11         500
#4     2 T2       12         100
#5     3 T1       10         200
#6     3 T2       11         300
#7     4 T1       12         100
#8     4 T2       13         400

data
df1 <- structure(list(ID = 1:4, age_t1 = c(10, 11, 10, 12), age_t2 = c(11,
12, 11, 13), speed_t1 = c(100, 500, 200, 100), speed_t2 = c(300,
100, 300, 400)), class = "data.frame", row.names = c(NA, -4L))

Comment: Thank you for the comment. Unfortunately, that doesn't turn the first image in the question above into the second image. Instead is only keeps "T1" to "T4" as column names
Comment: @Ben Regarding the 'T1' to "T4", that was my earlier code, which i updated
Comment: oh I'm sorry the speed variable is actually titled speed_total_T1 through T4
Comment: Yes, my apologies. Is there a way to do it?
Comment: @Ben Based on the example I showed, would this be the correct column names `c("ID", "age_T1", "age_T2", "speed_total_T1", "speed_total_T2")`
Comment: Fantastic! Thank you so much


Como criar botão no code behind do Android?

Question: Estou desenvolvendo um aplicativo onde baixo algumas umas imagens da internet quando o aplicativo é aberto.
Estou querendo, quando eu tiver estas imagens baixadas, criar um botão para cada imagem e colocar ela no background. Mas, como não sei quantas imagens vou baixar, não posso criar os botões no XML. Queria criar no java. Como faço isso?
Com a resposta do cicero funcionou, só estou com um problema a imagem ficou maior que a tela e está sendo cortada, tem como eu diminuir ela dentro do código ou só se tratar ela antes de colocar no código?
Answer: Você pode fazer das duas formas, tanto no XML como via código.
A vantagem de ser via XML é que você não escreve tanto no código.
ImageButton:
ImageButton imageButton = new ImageButton(this);
    imageButton.setBackgroundColor(getResources().getColor(android.R.color.transparent));

    File file = new File("caminho para a imagem");
    Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
    imageButton.setImageBitmap(bmImg);

    //Se quiser algum tamanho especifico
    ViewGroup.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    imageButton.setLayoutParams(layoutParams);

        //aí você adiciona essa imagem onde quiser, num ViewGroup
        layoutPai.addView(imageButton);

Via XLM:
Arquivo imagebutton.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:id="@+id/imageButton" />

No código:
 ImageButton imageButton = (ImageButton)LayoutInflater.from(this).inflate(R.layout.imagebutton, null);

onde está null acima, você pode passar o pai, que será o ViewGroup
File file = new File("caminho para a imagem");
Bitmap bmImg = BitmapFactory.decodeFile(file.getPath());
imageButton.setImageBitmap(bmImg);

//aí você adiciona essa imagem onde quiser, num ViewGroup
layoutPai.addView(imageButton);

Comment: obrigado vou tentar.
Comment: Cicero meu projeto deu um erro assim : Default Activity not found, mais só tenho uma Activity e ela não te nenhum erro.
Comment: @IlgnerOliveira fez a referencia da activity no `Manifest.xml` ?
Comment: sim. nem mexi
Comment: Isso é pq existe algum erro no seu projeto. Veja se ao lado do Run lá em cima na IDE, o bonequinho do Android onde está o nome do seu projeto está com X vermelho de erro. Esse erro que vc viu ocorre quando existe algum erro no projeto ou mesmo no manifest mesmo, como o @Antony Alkimim mencionou acima.


How to determine the minimum number of edges to form a rigid structure in ${\mathbb R}^d$ ($d = 2,3$)?

Question: Let $x_1,\ldots,x_n$ be $n$ points in ${\mathbb R}^d$ ($d = 2,3$). Then, what is the minimum number of edges to form a rigid structure?
Thanks!
Answer: See Laman's Theorem for $\mathbb{R}^2$.  The case for $\mathbb{R}^3$ is more complicated - see the double banana.
If you want a lower bound, take the number of degrees of freedom of the points and subtract the dimension of the Euclidean group.  This works because each edge can remove one degree of freedom.  However, having this number of edges doesn't guarantee that the structure is rigid.
In $\mathbb{R}^d$, each point has $d$ degrees of freedom, and the Euclidean group has dimension $\frac{d(d+1)}{2}$.  Therefore, the minimum number of edges required is $dn-\frac{d(d+1)}{2}$.  Therefore, in $\mathbb{R}^2$, the number of edges required is $2n-3$ and in $\mathbb{R}^3$, the number of edges required is $3n-6$.
This argument requires that nontrivial subgroups of the Euclidean group do not stabilize the set, so we must assume that the vectors between the points span $\mathbb{R}^d$.
Comment: In that case, there's a motion that fixes the points - around the axis.  Therefore, the Euclidean motions have fewer degrees of freedom.  You need the vectors between the points to span $\mathbb{R}^d$ for these formulas to apply.
Comment: Thanks very much for your help and detailed answer! [+1]
Comment: Hmm... It seems that for $d = 3$ and $n = 2$, $3n-6 = 0$ cannot reflect the minimum number of edges.
Comment: Thanks a lot! [+1] It seems that spanning vectors in ${\mathbb R}^{d-1}$ is sufficient for applying these formulae :-)
Comment: Note that these conditions are necessary, but not sufficient, even in the spanning case.
Comment: Thanks for your comments :-)


mvn archetype:create SHA-256 MessageDigest not available

Question: This is my first time to try maven. My os in linuxmint.I have install maven successful.

mvn -v
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)
  Maven home: /home/gzx/danale/environment/apache-maven-3.3.9
  Java version: 1.8.0_111, vendor: Oracle Corporation
  Java home: /usr/java/jdk1.8.0_111/jre
  Default locale: zh_CN, platform encoding: UTF-8
  OS name: "linux", version: "4.4.0-53-generic", arch: "amd64", family: "unix"

But when I have used mvn archetype:create

mvn archetype:create -DgroupId=org.sonatype.mavenbook.ch03 -DartifactId=simple -DpackageName=org.sonatype.mavenbook

it showed a strange error.

[WARNING] Error injecting: org.sonatype.plexus.components.cipher.DefaultPlexusCipher
  com.google.inject.ProvisionException: Unable to provision, see the following errors:Error injecting constructor, org.sonatype.plexus.components.cipher.PlexusCipherException: java.security.NoSuchAlgorithmException: SHA-256 MessageDigest not available
    at org.sonatype.plexus.components.cipher.DefaultPlexusCipher.(Unknown Source)
    while locating org.sonatype.plexus.components.cipher.DefaultPlexusCipher

It was so strange, how should I do?
Comment: Does it call **SHA-256 MessageDigest** when using 'mvn archetype:create'   ? But there is noting wrong of my java environment, and the version of jdk is not very old. So this problem is really strange.
Answer: I think maybe you have already figured your problem. But I got this bug yesterday and I fixed it today. I should write my solution down. Maybe someone will fall this trap.
Actually this problem is because Java cannot find the class "SHA-256 MessageDigest". But it is provided by JRE default. It should be found automatically.
If you access your JAVA_HOME, you may find a file whose name is jsse.pack in JAVA_HOME/jre/lib, and there is not a file named jsse.jar. That is the problem. Type
unpack200 jsse.pack jsse.jar

(unpack200 will be recognized as soon as you have set your Java path)
and the problem should be soloved.
Note:
Some JDK's have jsse.rar not jsse.pack, therefore, running "unpack200 jsse.rar jsse.jar" command will get the desired result, and will not delete the "jsse.rar" file (in case of *.pack files, they get replaced by the *.jar files).
Comment: Thanks all the same! Your solution maybe work, but I find `mvn archetype:generate` are recommended and `mvn archetype:create` has been abandoned.
Comment: For me (in Java 1.8), I had no jsse file, with "pack" extension, just "rar" extension. Running "unpack200 jsse.rar jsse.jar" will do just fine. Problem solved for me.


Can't test connection to mysql using Intellij

Question: I'm on OSX Mavericks, running Intellij 12, trying to add a datasource already defined in XML, using the persistence facet.
I can find and select the source fine, but when I try to test the connection I get:

Connection to XXXXX failed: Exception in thread "main"
  java.lang.ClassNotFoundException: com.mysql.jdbc.Driver   at
  java.net.URLClassLoader$1.run(URLClassLoader.java:366)    at
  java.net.URLClassLoader$1.run(URLClassLoader.java:355)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.net.URLClassLoader.findClass(URLClassLoader.java:354)    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:425)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:358)     at
  java.lang.Class.forName0(Native Method)   at
  java.lang.Class.forName(Class.java:190)   at
  com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)

Looks like it's just a classpath problem, but I'm having a surprisingly rough time figuring out what I have to do to get the mysql jar on the classpath.
Every question I've found deals with adding the jar to the classpath of your compiled or testing application, that's NOT what I'm looking for here. My application connects to mysql fine, it's the IntellijIDE that's having problems. Where do I need to add the path to this file?
Answer: For Intellij 15 (maybe lower versions) this works:
Add the JDBC library using Intellij:

Goto View -> Tool Windows -> Database.
In the Database window, select a database and click the icon for data source properties (cmd+i).
In the next window goto MySQL in the Drivers section. In the window left under driver files click download. That's it.
Comment: i have a question if you can answer it. So i fallowed your answer, it worked, BUT i have the driver as a maven dependencie, why heck do i need to download it???
Comment: Because Intellij does not use your projects' Maven dependencies. What Intellij needs is separated from your projects.
Answer: In IntelliJ goto
View -> Tool Windows -> Database
Inside Click + button -> DataSource -> MySql
as shown below

In below screen enter your mysql connection details and click Test Connection...
make sure you download mysql driver for connection
Answer: Either of the following options should work
add jar to the global libraries of the project.
put jar in the lib directory of intellij.
put jar in the ext lib of the jre that intellij is running under.
Answer: Go to Itellij IDEA menue: File-->project structure-->Modules-->choose your module-->Dependencies-->Click + to add Library-->Choose mysql-connector-java-->Apply & OK
Answer: My IntelliJ 2018.2.5 is pure standalone, without Maven and is not showing a Database menu under View/Tool Windows.  The only thing that worked for me was documented here: Adding Jar files to IntellijIdea classpath
and the solution was to add the JAR to Project Structure.  I do not understand why IntelliJ does not pick up CLASSPATH.  Adding the JAR to IntelliJ's lib tree also did NOT do it.
Answer: I had this same issue, I did all suggested until I noticed there is a "Problems" index in the Project Structure window of IntelliJ. It said that there was a problem because my directory "lib" was not included in the Artifact. I just clicked "Fix" and after that, everything worked. Maybe this helps someone else.


Application.Wait and Excel VBA Run-time error '13' Type mismatch

Question: I don't understand why I have this row Application.Wait in error (highlighted in yellow) ?
Sub Wait_Random()
Dim Low As Double
Dim High As Double
Low = 90 '<<< CHANGE AS DESIRED
High = 126 '<<< CHANGE AS DESIRED
r = Int((High - Low + 1) * Rnd() + Low)
Application.Wait Now + TimeValue("00:00:" & CStr(r))
End Sub

I have found that the problem is that this code is trying "to add a number to a string of characters". But I am lost ! Thanks in advance ;)
Answer: It's because your r variable always greater than 59 sec. (actually it's alwasys greater 90). You should change Low and High so that r would never be greater 59:
Sub Wait_Random()
    Dim Low As Double
    Dim High As Double
    Dim r as Integer
    Low = 1 '<<< CHANGE AS DESIRED
    High = 59 '<<< CHANGE AS DESIRED
    r = Int((High - Low) * Rnd() + Low)
    Application.Wait Now + TimeValue("00:00:" & CStr(r))
End Sub

Or another way you could use
Application.Wait DateAdd("s", r, Now)

to add r seconds. In that case r could be greater 59.
Comment: Thanks.;) Your fist answer works fine ;) The second one does not seems to work on excel 2003. Don't worry I keep the first one. ;) Many thanks again. ;)
Comment: Same problem on my part for the second solution (it works fine the first time and the next time it seems to be blocked)...Well, please don't worry. ;) Thanks ;). BTW, I have seen that you have removed the +1 of the first solution. Thanks. ;)
Comment: Hi, Many thanks. ;) I can can confirm that your last code is working too with more than 59 seconds. ;) Thank you again. ;)
Comment: Strange - just tested it in Excel 2003 and it works:) btw, glad it helps!
Comment: @Erb, found my error:) see updated answer. When using `Application.Wait Now + r` - we add `r` *days*. To add `r` seconds use `Application.Wait DateAdd("s", r, Now)`


Rails, generate MD5 hash of the record's ID and save that also

Question: After saving a rails model, I'd like to generate an md5 hash of the ID and save it in the database with the object.
My question is, how do I define the method that does this? I need the ID to do the calculation, but this isn't done until after the save?
Answer: Use an after_create callback in the model to do this.
class YourClass < ActiveRecord::Base
  after_create :hash_it

  private

  def hash_it
    self.md5_hashed = id.md5_your_hash_method
  end

end

fyi the 4 'after' callbacks available are:
after_validation
after_create
after_save
after_commit

Comment: you should detail further to avoid recursion issues
Comment: maybe this should be after_create ? yes that is sounding better
Comment: now I am wondering - how will this get saved to the database?  Does rails do another save for me? Or should this really be after_create? Or is the ID available at the point?
Comment: Original posters "after save" had led me there, but this is the ID we're talking about so I certainly do not expect it to change after original initial creation/population.
Comment: You need to save the record after setting this or use `update_attribute`.


Interpreting PCA results of first two components

Question: I don't like the looks of my PCA graph here. PCA coordinates should be uncorrelated, yet the variance between the coordinates of the second component increases as the first component decreases. What's the explanation for this?
Colors represent various groups. I also should specify I have over 1000+ variables in my original matrix. I need 26 components to reach 80% of the variance explained, which is probably bad.
Answer: Principle components analysis (PCA) only ensures that the PCs are uncorrelated. In other words, their expectations are not linearly related. That does not ensure independence of the PCs; higher moments of the PCs may be related. What you have here is a linear relation between the first moment of PC1 and the second moment of PC2. (Also, possibly a relationship between second moments of both PC1 and PC2.)
First: good for you for looking at the data. You avoided doing something mindless by looking -- and that is always worthy of commendation. That is the mark of the better analyst.
Second: you can explicitly reformulate the PCA optimization to account for second moments. However, that might be more involved than you want and it will not protect you from other relationships, say  or, you can go with independent components (ICA).  ICA should be an easy change and it is relatively fast, even for large amounts of data. If you need a reference for ICA, Hyvarinen, Oja, and Karhunen is the go-to text on ICA.


Longitudinal redundancy check in Javascript

Question: I'm working with a system that integrates a Point of Sell (POS) device, I use chrome serial to scan ports and be able to read credit card data.
The problem I'm facing is that I need to concat the LRC from a string in this format:
STX = '\002' (2 HEX) (Start of text)
LLL = Length of data (doesn't include STX or ETX but command).
Command C50 {C = A message from PC to POS, 50 the actual code that "prints" a message on POS}
ETX = '\003' (3 HEX) (End of text)
LRC = Longitudinal Redundancy Check
A message example would be as follows:
'\002014C50HELLO WORLD\003'
Here we can see 002 as STX, 014 is the length from C50 to D, and 003 as ETX.
I found some algorithms in C# like this one or this one and even this one in Java, I even saw this question that was removed from SO on Google's cache, which actually asks the same as I but had no examples or answers.
I also made this Java algorithm:
private int calculateLRC(String str) {
    int result = 0;
    for (int i = 0; i < str.length(); i++) {
        String char1 = str.substring(i, i + 1);
        char[] char2 = char1.toCharArray();
        int number = char2[0];
        result = result ^ number;
    }
    return result;
}

and tried passing it to Javascript (where I have poor knowledge)
function calculateLRC2(str) {
    var result = 0;
    for (var i = 0; i < str.length; i++) {
        var char1 = str.substring(i, i + 1);
        //var char2[] = char1.join('');
        var number = char1;
        result = result ^ number;
    }
    return result.toString();
}

and after following the Wikipedia's pseudocode I tried doing this:
function calculateLRC(str) {
    var buffer = convertStringToArrayBuffer(str);
    var lrc;
    for (var i = 0; i < str.length; i++) {
        lrc = (lrc + buffer[i]) & 0xFF;
    }
    lrc = ((lrc ^ 0xFF) + 1) & 0xFF;
    return lrc;
}

This is how I call the above method:
var finalMessage = '\002014C50HELLO WORLD\003'
var lrc = calculateLRC(finalMessage);
console.log('lrc: ' + lrc);
finalMessage = finalMessage.concat(lrc);
console.log('finalMessage: ' + finalMessage);

However after trying all these methods, I still can't send a message to POS correctly. I have 3 days now trying to fix this thing and can't do anything more unless I finish it.
Is there anyone that knows another way to calculate LRC or what am I doing wrong here? I need it to be with Javascritpt since POS comunicates with PC through NodeJS.
Oh btw the code from convertStringToArrayBuffer is on the chrome serial documentation which is this one:
var writeSerial=function(str) {
  chrome.serial.send(connectionId, convertStringToArrayBuffer(str), onSend);
}
// Convert string to ArrayBuffer
var convertStringToArrayBuffer=function(str) {
  var buf=new ArrayBuffer(str.length);
  var bufView=new Uint8Array(buf);
  for (var i=0; i<str.length; i++) {
    bufView[i]=str.charCodeAt(i);
  }
  return buf;
}

Edit After testing I came with this algorithm which returns a 'z' (lower case) with the following input: \002007C50HOLA\003.
function calculateLRC (str) {
    var bytes = [];
    var lrc = 0;
    for (var i = 0; i < str.length; i++) {
        bytes.push(str.charCodeAt(i));
    }
    for (var i = 0; i < str.length; i++) {
        lrc ^= bytes[i];
        console.log('lrc: ' + lrc);
        //console.log('lrcString: ' + String.fromCharCode(lrc));
    }
    console.log('bytes: ' + bytes);
    return String.fromCharCode(lrc);
}

However with some longer inputs and specialy when trying to read card data, LRC becomes sometimes a Control Character which in my case that I use them on my String, might be a problem. Is there a way to force LRC to avoid those characters? Or maybe I'm doing it wrong and that's why I'm having those characters as output.
Comment: Do you know which type of LRC is required by your POS device? There are two different algorithms in your code samples and in the wiki article you linked (one using addition and one using XOR).
Comment: @JackA. hello, it uses XOR form
Answer: I solved LRC issue by calculating it with the following method, after reading @Jack A.'s answer and modifying it to this one:
function calculateLRC (str) {
    var bytes = [];
    var lrc = 0;
    for (var i = 0; i < str.length; i++) {
        bytes.push(str.charCodeAt(i));
    }
    for (var i = 0; i < str.length; i++) {
        lrc ^= bytes[i];
    }
    return String.fromCharCode(lrc);
}

Explanation of what it does:
1st: it converts the string received to it's ASCII equivalent (charCodeAt()).
2nd: it calculates LRC by doing a XOR operation between last calculated LRC (0 on 1st iteration) and string's ASCII for each char.
3rd: it converts from ASCII to it's equivalent chat (fromCharCode())  and returns this char to main function (or whatever function called it).
Answer: Your pseudocode-based algorithm is using addition. For the XOR version, try this:
function calculateLRC(str) {
    var buffer = convertStringToArrayBuffer(str);
    var lrc = 0;
    for (var i = 0; i < str.length; i++) {
        lrc = (lrc ^ buffer[i]) & 0xFF;
    }
    return lrc;
}

I think your original attempt at the XOR version was failing because you needed to get the character code. The number variable still contained a string when you did result = result ^ number, so the results were probably not what you expected.
This is a SWAG since I don't have Node.JS installed at the moment so I can't verify it will work.
Another thing I would be concerned about is character encoding. JavaScript uses UTF-16 for text, so converting any non-ASCII characters to 8-bit bytes may give unexpected results.
Comment: Applying the XOR operator (`^`) to a string and a number appears to always return the number. See, for example: http://jsfiddle.net/ttycfeax/ . So your original XOR implementation would always return zero because you were not converting to a number using `charCodeAt`. Your "HELLO WORLD" test should not have problems with extended characters.
Comment: I bet I'm having unexpecetd results because of 8 bit bytes, I always get a 0 when `console.log('lrc: ' + lrc);` is executed... I'll try debuging it and see what's happening. Thanks. If it works I'll accept later :)
Comment: I modified a little your algorithm, now it sends a message to POS, however message isn't showing on POS screen, I have a theory about it, my LRC sometimes becomes a [control character](http://ascii.cl/control-characters.htm) and it might be a problem, is there a way I could force LRC to avoid those chars? Or are they valid chars on an LRC calculation? See edit for algorithm edit.
Comment: actually the error for not showing message on POS screen was because of a typo, but still the control character is it ok to have them? or can I avoid them?
Comment: As far as I understand, the LRC itself could be any 8-bit number, which may or may not be a value that can be interpreted as a printable character.


Text to speech converter

Question: I am going to create a Text to speech converter, which can be executed in both Windows, and Linux based systems. Can someone please help me answer the following questions;

What language should i use; Java, C++ or any other?
The program i am going to create should be able to read large chunks of data.
There should be good sound quality.
What are the libraries available to achieve this?

Please share your experiences as well.
Comment: 2 and 3 aren't questions
Comment: Considered reusing existing work?
Comment: @Thorbjørn Ravn Andersen  yes, and it should be free (open source or free to use once)
Comment: I think @Thorbjørn mean that you should look at a dead project or splinter off from a new one, as you'll be reinventing the wheel once more (but I don't discourage that at all. It's the best way to learn).
Comment: This question was answered for Java in [this thread](http://stackoverflow.com/questions/143390/java-text-to-speech-engines-overview).  There are many libraries.
Comment: @Blender, no, I was thinking of simply just using an existing, living third party library.  If it is a learning experience, it is another matter though.
Answer:
Use the language you're most comfortable with. I learned the hard way when I tried to re-code my raytracer in C++, coming from a Python background. It took me weeks to get it to function...
Basically, you'll get frustrated by the nuances of a new language before you can get to coding something, so I suggest you stick with what you know.

That's independent of the language. Just makes sure to read the data in chunks (like 2048 kilobytes at a time). Reading a big file to RAM is not a great idea, as you can't be sure your end user has enough RAM (audio files can get BIG).

This is trivial. I can't help you program good sound quality. That's up to you.

There exist a few implementations of TTS for Linux, so that's all I can recommend. Look at Festival, as it is one of the ones you can actually understand.
Answer: Long time ago i had that same idea. I think it is not too complicated and can be done. This is how i would do it:
1- I would use Java, because it is platform independent.
2- If you are going to create an standalone application, it will be the local computer that will do the processing an not an application server, as in the case of web apps. Also i suppose that your program, will be used only by one user at a time. I think you will not have big issues with the amount data to process, if u implement some buffering mechanism.
3- The quality of the sound will depend in various factors such as: noise when recording,format, speed of the sound... Notice that many text to speech applications that exist on the web, the sound quality is ok, but you will never get the feeling that it is a real person, who is reading. (I recommend you a female voice, it sounds better).
4- Regarding to the libraries and another gadgets, this is what i think you might need:
-Java Standard Development Kit(To be able to work with java)
-A good IDE: There a many out there you can get for free. My favourite is eclipse but if you are a beginer with java, you might like to start with netbeans many people say it is more intuitive for learning.
-JLayer Mp3 library This will help you play the sounds in java.
-javax.swing Is a java library that is included in the development kit and allows you to create rich graphical user interfaces. Also if you are new to swing, i would recommend you a great swing IDE, called JFormDesigner, have a look at it, im sure it will speed your development alot(It is a great tool).
I hope my answers can give you some tips.
Update
I think it would be correct to mention also, that the only minimum requirement the users of your app will have in order to run the app is:
JRE(Java runtime enviroment)
Comment: @sfrj: But Java has a runtime requirement, and C++ can be compiled to run on almost any platform.
Comment: @Blender The only requirement to run a java program that uses the gadgets i mentioned, is to have installed the java runtime enviroment in the machine, that is what makes java platform independent. I don't think it is a big effort for a user to install the JRE(Java Runtime Enviroment). Unfortunately windows does not have it installed by default, but there are some other systems that do have it, for example: Ubuntu. I never worked with C++, im sure it is a great language too, but i think java is also a really good choice for solving this problem.
Comment: @sfrj: Java is a great language for this, I agree, as many of the Speech to Text engines are written in it. I think Windows would be the only problematic OS, as it doesn't ship with the JRE.
Answer: This project of text to speech can be made using computer generated voice
so no problem of storing a database for each word and its pronunciation.
Just use the language in which u feel master to urself and apply the concept.....
Answer: I do not know anything about text to speech except that it's not easy. That being said, I suggest you stick with the language you are most familiar with. I'm sure Java and C can do it.

Text to speech converter


Azure Scheduler that updates both Azure Database and On Premise SQL Server Database

Question: I have a REST Service that needs to update data into Azure SQL Server database and also into On Premise SQL Server database. Both databases should have same data in certain database tables.
Scheduling Service that runs in Azure and process data transfer into Azure Database and then into On Premise database e.g. after every 5 minutes is okay. Also other techniques too e.g. REST updating both Azure database and then On Premise database.
I'm quite new using these Azure techniques using both configurations and programming with C#.
I have read about Function Apps, Azure Data Factory, Azure Logic Apps and Synchronizations but don't know what technique is ok to transfer data from Azure to Azure database and then On Premise database.
How have you solved this kind of issue?
Best regards,
Michael
Answer: Whatever service you use, will need to be able to access both SQL servers. Accessing Azure SQL is easy, but I imagine your on-premises SQL server is not exposed to the internet, so you need a way to connect to that.
Functions are a nice simple tool for running any sort of code without having to worry about servers etc, however, it does not have a way to reach into your on-prem environment. You could do something with having messages written to service bus and then run another application on-premises and have that collect the message and write it to the on-premises DB. All a bit painful though.
Both Data Factory and Logic Apps have a slightly better solution because the both have the premise of a "Data Gateway" an app you run on-premise which allows the Azure service to talk to on-premise resources without directly exposing them to the internet.
If you want to provide a REST endpoint and write to both databases at the same time then logic apps are probably the way to do it. It can present a REST endpoint to call and you can then build a workflow with this data to write to both places, using the data gateway for on-premises. If however, you are happy to write to the Azure SQL DB and then have a process sync that data to on premises, then Data Factory can do that for you.
Some useful links:
Logic Apps Data Gateway
Data Factory Integration Run Time
Copy Data To/From SQL Using Data Factory


Subsets of universal sets

Question: Was going through previous exam questions and came across this:
Let $A$, $B$, and $C$ be subsets of a universal set $U$ and suppose $n(U) = 100$, $n(A) = 31$, $n(B) = 34$, $n(C) = 35$,
$n(A \cap B) = 12$, $n(A\cap C) = 10$, $n(B \cap C) = 17$, and $n(A \cap B \cap C)$ = 6.

What is ($A′ \cap B \cap C$)?
What is ($A \cup B \cup C$)?
Comment: you can draw a Venn diagram or  directly use the inclusion-exclusion principle.
Answer: Let A, B, and C be subsets of a universal set U and suppose $$|U| = 100, \; |A| = 31, \; |B| = 34, \; |C| = 35, \\|A \cap B| = 12, \; |A \cap C| = 10, \; |B \cap C| = 17,\\ |A \cap B \cap C| = 6$$

1.What is $|\overline{A} \cap B \cap C|$?

Exclude the intersection.
$|\overline{A} \cap B \cap C| = |B\cap C| - |A \cap B\cap C|$

2.What is $|A \cup B \cup C|$?

Use the inclusion-exclusion principle.
$|A\cup B \cup C| = |A|+|B|+|C| - |A\cap B| - |A\cap C| - |B\cap C| + |A\cap B\cap C|$
Comment: Whats with all this + and - stuff?
Comment: @user3458730 - in your question you write $n(U)=100$; is this meaning the number of elements of $U$ ? In Graham's answer, the number of menebers of $A$ is (more "formally") written as $|A|$. Thus, $+$ and $-$ are "standard" arithmetical operations on numbers. When you ask "What is (A'∩B∩C)?" you are askin - we presume - about the number of memebers of this set, because you do not give us info about its members : so the above answer.

Subsets of universal sets


Python - how to preserve unsorted list order in dictionary without separate data structures

Question: I have a list whose elements are arranged using some external business logic, and should not be sorted alphabetically or in any other order.
I also have a dictionary whose keys are the list elements.
This compels me to maintain two different data structures. If I add an element to the list, I have to add the key to the dictionary, and vice versa. It's a duplication of databases. I would like to avoid that.
I am planning to avoid it using tuples in a list L: [(k1, v1), (k2, v2), ...] where k1, k2, etc are in the right order.
Is there a better built-in data structure that will let me address this more elegantly? Efficiency in random access would be preferred. Right now, accessing L[k3] is basically O(n). On the other hand, dict(L) would not preserve order, when I want to print the keys out.
Answer: You can use the collections.OrderedDict() dictionary subclass to maintain order. Adding new keys adds them to the 'end' of the order, deleting keys preserves the remaining order.

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

When creating an OrderedDict() instance from a list, do feed it (key, value) pairs in sequence, to set the initial order. Don't be tempted to pass in a regular dictionary, since such objects don't have a specific order you'll end up creating an instance with that same arbitrary order.


Different user registration

Question: small question
I've created a content type 'Player' with the necessary fields. With the 'Inline Entity Form' module i've added this tot the default user registration form.
Now when a user register, he immediately creates a node for the content type 'Player'. And when he edit his user profile, he also edit the node.
Now I want to have the option, that a user can choose to register as a player or a coach. When a coach register, he should fill in other fields, and so create a node for the content type 'Coach' .
With which modules can I realize this?
Answer: You can achieve this using Profile 2 and Profile2 Registration Path
As the project page of Profile2 Registration Path mentions

Profile2 Registration Path enables you to set a unique registration
  path for each Profile2 profile type. Users who register via that
  unique path will be presented with fields from the chosen profile
  type(s).
Comment: Thx for the answers!

Extra Question

With that profile2 module, I Can also use my solution " of creating a node during registration with the 'Inline Entity Form' " ??
Comment: You should be able to do it. There is nothing specific in the module that would stop you from using inline entity forms to do what you are doing.
Comment: I tried , but there seems to be an issue with the integration of Inline entity form in profile2. The field of the entity are correctly loaded in the registration form. But after saving registration, the node is not created, and the values are not saved
Answer: You can use profile2 and Profile2 Registration Path module.

Different user registration


What does it mean to say, "X was the Nth overall pick for this season"?

Question: I am a recent NFL enthusiast and have just started following the games but some terminology still stumps me. I understand the draft process in general and know that every year each of the 32 teams get to pick new players over two days with 7 rounds given to each of them. So, when a player is said to be the "first overall pick for a season, does it mean that he was the first one to be drafted by any team for that year? Or does it mean he was just picked in the first (of the seven rounds) round? If each team gets one pick (ideal circumstances), that would mean 32 picks per round. So could the player (said to be the first overall pick) have been picked in any order as long as it's in the first round or does he have to strictly be the very first pick of the first round?
Answer: Let's take a look at the 2014 NFL Draft for example.

So, when a player is said to be the "first overall pick for a season, does it mean that he was the first one to be drafted by any team for that year? Or does it mean he was just picked in the first (of the seven rounds) round?

The Houston Texans have the first pick in the first round, or the first overall pick. Thus, X will be the first overall pick for this [draft] and he will go to the Houston Texans as the first pick in the first round.
The Houston Texans have the first pick in the second round, or the 33rd overall pick. Thus, X will be the 33rd overall pick for this [draft] and he will go to the Houston Texans as the first pick in the second round.
The draft order does not change round by round, meaning if Houston has the first pick in the first round, they will have the first pick in each of the following rounds. However, a team may trade draft picks with another team for players or other draft picks of another team.

If each team gets one pick (ideal circumstances), that would mean 32 picks per round

Not exactly.
Compensatory selections are made starting at the end of the third round. Teams who gets these picks based on how they did during free agency (the # of players lost to free agency vs. the # of players signed from free agency).

So could the player (said to be the first overall pick) have been
  picked in any order as long as it's in the first round or does he have
  to strictly be the very first pick of the first round?

He doesn't have to strictly be the very first pick...nor second, nor third, nor fourth, nor fifth, nor sixth...nor seventh. He doesn't even have to be selected in the first round.
This is based on team needs, personnel, and best available (determined by the NFL combine, pro days, and how his collegiate performance may translate into the NFL). Mock drafts attempt to predict this phenomenon.
Answer: If there are 32 teams and 7 draft rounds, there are 32*7 or 224 overall picks. That is, picks 1-32 take plac3 in the first round, 33-64 in the second, 65-96 in the third, 97-128 in the fourth, 129-160 in the fifth, 161-192 in the sixth, and 193-224 in the seventh. The first "overall" pick is the first of 224, that is the first pick in the first round.
Each team's first round pick is likely to be better than the seventh round pick (barring "surprises" and "latebloomers.") But within the first round, number 1 is likely to be way better than number 32. Which is why the team with the worst record from the previous year gets to pick first. Unless it has traded away its pick, or lost it to another team for signing away one of its free agents (not likely).
Comment: So, why was the final pick of the 2014 NFL Draft the [256th pick](https://en.wikipedia.org/wiki/2014_NFL_Draft#Player_selections)? Also, would you say the 1st pick of the [2000 NFL draft](https://en.wikipedia.org/wiki/2000_NFL_Draft#Player_selections) was "way better" than the 199th pick? Why would the 1st pick "likely to be way better" than the 32nd pick?
Comment: @edmastermind29: There were something like 32 draft picks traded by teams for other picks or players. The "receiving" teams got higher numbered draft picks, while the "yielding" teams got "blanks" for their draft picks. The outlier distribution of top athlete abilities (e.g., in the Grand Slam), is that the best is likely to be way better than the 50th or 100th There is usually a consensus of ranks but sometimes players slip through the cracks. Mike Trout, objectively number 1 in his class, was selected as number 25 overall (passed over by 24 teams), at a stage where players usually decline.
Comment: Was Mike Trout #1 in his class before his stellar MLB play thus far (ie, in scouting reports and such)?
Comment: @edmastermind29: That's the point. "Occasionally," someone falls through the cracks. Trout was number 1 "ex post." Usually that translates tightly into, say, "top five" ex ante, but there's always the exception to the rule. Normally, a 20-something first round pick is someone like Kolten Wong, an obvious talent who nevertheless (so far) has had "teething problems" in the majors.
Comment: Yes. Those who fall through the cracks end up being an incredible steal for the team who ends up selecting him. However, work ethic, character, expectations, and to a lesser degree, management seem to be the reason why those who are viewed as exceptional talents, and are selected high, under perform.
Comment: @edmastermind29: Here's a model of baseball ranks and values: http://www.hardballtimes.com/matthew-murphy-3-post-bringing-it-all-together/ Measured in WAR, the value of a number 5 draft pick is less than half (on average) of a number 1 draft pick (using data from 1991-2005). And the average WAR value of the number 10 draft pick is less than half that of the number 5 pick.
Comment: Wow, that's an exponential decline. I think that best illustrates the talent/production level of those picked at the beginning of drafts. Great find.

What does it mean to say, “X was the Nth overall pick for this season”?


Clustering numeric, categorical, and multivalue categorical data

Question: I have data that look like this:
<code>amount    creator    accounts
100       john       cash, accounts payable
325       jane       accounts receivable, cash
200       john       tax account, accounts payable, cash
</code>
How should these data points be clustered?
Thoughts so far:

Popular, consensus answer seems to be to one-hot encode the categorical and multivalue_categorical fields, and then scale the numeric field to [0,1]. This causes two primary problems: extremely sparse/high-dimensional data (4,000 dimensions in my case), and a numeric column that is perhaps not weighted appropriately.
Attempt to apply differing algorithms to each data type and mash them together somehow. This could involve market-basket type analysis for the multivalue_categorical, k-modes for the categorical, and k-means for numeric (or k-prototypes for the categorical and numeric).

Is there any method/implementation that would allow for these three types of data to be clustered without one-hot encoding the categorical and multivalue categorical? I have looked into SOM as an unsupervised NN that performs clustering, but I haven't seen evidence that it can handle multivalue categorical.
Comment: If you can determine a distance measure that is appropriate for your data, you can use any clustering method that can operate over a distance matrix instead of the raw data. You need to think about the issue of sparsity (what would it mean to have clusters in sparse data, what would you want to detect?), & the ontological status of your multivalue variable (is that really $1$ variable, or a bunch? How do they go together more than they go w/ the other variables?).
Comment: thank you for the nudges in the right direction! i updated my question to reflect a more realistic example of the data (clustering journal entries, essentially). given that data, do you have any further thoughts? i guess the root of my question is whether it's even possible to have a distance metric that fits all three types of data.
Comment: You introduced a new tag [mixed-data].  Can you please provide a tag wiki?
Comment: @kjetilbhalvorsen, see the discussion here: [A new tag - for mixture of data types](https://stats.meta.stackexchange.com/q/5184/).
Comment: how many variables of each type are there in your dataset?
Comment: @g3o2 currently, there is one multivalue categorical, two categorical, and two numeric
Answer: With mixed data types the basic answer is to use Gower's distance (see @ttnphns' thorough explainer here: Hierarchical clustering with mixed type data - what distance/similarity to use?).  The gist of it is that you get the distance measure of your preference for each variable individually, then average them.  You can also do a weighted average of the constituent distances, if you think some should be given more credibility than others.
For your continuous variable, the absolute difference should be fine.  Simple matching is presumably fine for your categorical variable, creator.  That is, $1$, if two rows have the same creator, and $0$ otherwise.  Then you just need to find a metric for your multivalue categorical variable.  I think it is fine for you to think of this as a single variable, but I suspect it is ultimately better to think of it as a set of binary variables, where all possible options constitutes the set.  From there, if the option is listed, that amounts to having a $1$ in that column, and $0$ otherwise.  Thus, you have a high-dimensional binary space.  There have been lots of measures defined for binary data (see: Choi, Cha, & Tappert, A Survey of Binary Similarity and Distance Measures, pdf, for a list of 76!).  You need to decide which makes sense.  The constituent distance measures each gets normalized, and then you use whichever clustering algorithm you like that can work with a distance matrix instead of the raw data (see, e.g., my answer here: How to use both binary and continuous variables together in clustering?).
Answer: Do not choose an approach, just because it is easy to implement.
One hot encoding, normalization, etc. are all just hacks that get you at least something, but not necessarily something good!
Instead, do the math: what is a better clustering in your problem? Until you can evaluate how well it solves your problem, you might as well just use random partitions...
Comment: that's exactly why i was looking for something that was not just a popular consensus thrown out every time. do you have any thoughts on what a sound approach might be, based on the data types?
Comment: Clustering is more of an art than of a science. Once the business problem is clearly defined, clustering is naturally easier. The tricky part is to get to that clear problem definition. Evolving from any starting point through an iterative and interactive process towards a better point of problem understanding is a typical and familiar clustering process. So why not ... Whatever you choose, without any __domain knowledge__, even the best approach won't get you very far anyway.
Comment: i think i have the clear problem definition, the semantics of how to deal with mixed data types (particularly multivalue categorical) is what's tripping me up.
Comment: Your problem definition must include how to handle (weight etc.) variables, and how to measure differences and similarities.
Comment: that's what i'm here for - learning about the different ways to measure differences and weight values. i have realistic sample data and data types included.
Answer: Given that there are only two numeric and three categorical variables in your dataset, one of which has many categories, you could investigate the opportunity of transforming the two numeric ones into ordered categorical ones.
That way, the clustering problem becomes all categorical, with the dedicated distance functions at hand.
Fo binning there are at least three approaches in descending order of relevance:

define the bins based on domain knowledge;
inspect the distribution of each numeric variable to set the cutoff points for each bin;
set the bins so that each bin has roughly the same number of observations.

As an algorithm, hierarchical clustering should get the job done.
Comment: thank you - I hadn't really thought seriously about this approach. So this would still involve two distance functions, right? One for the multivalue, and one for the normal categorical?
Comment: It depends on how you want to weight the variables and what you want to do with the multivalue one. The latter can be used in several ways: as a categorical variable, as a text variable or even split into binary tokens. The most naïve way of weighting is to apply a separate distance calculation on each of the 5 variables, then to aggregate, that is if each one presents a separate analysis theme. If there are less than 5 themes, then you should apply a distance function on each group of variables that belong together, then aggregate thereafter.
Comment: i was thinking along the lines of a market basket comparison - not sure if there is a traditional distance function for market baskets that would fit in well
Comment: you mean along the lines of [association rule learning](https://en.m.wikipedia.org/wiki/Apriori_algorithm) ? That would mean that you want to analyze the co-occurrence of transactions? I guess that you should edit your original post then and specify what you really expect to retrieve from your data. This does change your original question a lot btw.
Comment: is there a distance function for association rule learning?
Comment: please edit both your question and original post, also specify if your data are transactions...
Comment: In association rule mining, you would probably tokenize the string variable, e.g. by comma-separating. The objective is then to find sth out about the tokens rather than about each observation: e.g 66% of cash co-occurs with payables, etc.


How to customize pagination for the taxonomy term view page for different vocabulary?

Question: I have 3 vocabularies as shown in this screenshot:

And I have default Taxonomy term view page with 10 items per page as shown in this screenshot:

I want to display 12 items per page only for the taxonomy term pages which are related to the terms of Categories vocabulary. Should I create new Taxonomy term view page for Categories vocabulary or is it possible to configure pagination using HOOK_preprocess_taxonomy_term ?
Answer: I've used the Taxonomy Views Integrator module which helped me set custom pagination and view modes by creating taxonomy view page for different taxonomy terms and vocabularies. Some details about this module (from its project page):

The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.
TVI will try not to interfere with views or taxonomy/term page displays if no TVI views exist for the current page request.


How to get call state of outgoing android call

Question: I am originating a call from Android Studio. The code is as follows:
I want to get the state of the call at any point. The link: https://developer.android.com/reference/android/telecom/Call.html
shows the state of the call can be obtained by using the Class call.. SO if I use Call.getState() I should be able to get the current state. But I get the compilation error:
Error:(28, 20) error: Call() is not public in Call; cannot be accessed from outside package.  There are several call states defined in the enum: Dialing, Ringing, Connected, DIsconnected, Holding, etc.
When I run the code, it does make the call as I can see the screen of emulator making the call.
The developer guide does not provide any examples of using these classes.
Thank you for your help.
package com.example.ramesh.makeacall;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.telephony.*;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

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

    }
    private void call() {

        try {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:5555551212"));
            System.out.println("====before startActivity====");
            startActivity(callIntent);

        } catch (ActivityNotFoundException e) {
            Log.e("helloAndroid","Call failed",e);
        }
    }

    }

Answer: Try to use like this(Haven't tried it though) -
Call.Callback callback = new Call.Callback() {
    @Override
    public void onStateChanged(Call call, int state) {
        super.onStateChanged(call, state);
        if(state == Call.STATE_RINGING){
            //you code goes here
        }
    }
};

Comment: How to used it bro
Answer:  public class MyPhoneStateListener extends PhoneStateListener {
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                handleRinging(incomingNumber);
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                handleOffHook();
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                handleIdle();
                break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }
}

and register statelistener :
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
Comment: Thanks. The above code gives only 3 call states. I am trying to use the class Call as defined in : https://developer.android.com/reference/android/telecom/Call.html .  This gives several states, like CALL_ACTIVE, CALL_DISCONNECTED, CALL_HOLD, etc.  How can I use the class Call()?
Comment: Ok. From what I understand since the Call Class is not public as per the android doc,,  the class  Call cannot be used.  Is there a way to get around it so I can get the current state of the call besides the  3 mentioned above?


Best modelling approach with binary outcome and some non-linear relationships, including some "definite 0" regions?

Question: I have 5 predictors and a binary outcome.
One of the predictors (X4) is already very informative of the outcome. Basically, for all X4 values that are 0:100, all outcomes are 0. For values 100:150, the vast majority of outcomes are "1" except for a few near the edges of that range. For values 200 on, all outcomes are 0 again.
So really, a decent model already could be "0 for all values except for if X4 is 100:150... for that range, use a logistic regression". Would that have to be a GAM model? Or could random forest be good? Or a neural network?
So far I simply used a dummy variable that is 0 unless X4 is in the range 100:150, and include interaction effects between that variable and all the others. This gives me near perfect prediction on the test set, but I'm curious if there's a non-manual way to do this (I wanted the machine to do the learning, not me!)
Comment: Could you edit your post to include a scatterplot of outcome vs X4? That will give a better idea of what models might be appropriate.
Answer: If you managed to get a low test error with your simple model then you will probably get a good fitting as well with other models.
However, unlike other models, a random forest classifier (RFC) offers a really nice way to test whether or not the model has learned your intuition/information about the importance of features. This can be done through the feature importance property of RFC.  See this as an example.


How to go about writing multiple melody notes in between chords

Question: In my music theory instruction, we are taught how to utilize one nct between two chords in a chord progression (i.e. check voices for direct and hidden parallel fifths and octaves between chords on strong beats and make sure that the weak beat pitch doesn't create new parallels in between the two chords). However, I was not taught how to do so utilizing multiple melody notes (ncts & chord tones). What is the process and rules for doing so?
*Side note: I am familiar with the concept of counterpoint. However, I want to know the "rules" or practice in the context of Four-part Tonal Harmony. I.e. using major and minor scales, modern meters, cadences, and triadic harmony, Not four-part counterpoint.
Comment: What is "four-part tonal harmony"? Get out of the realm of counterpoint, and textures quickly become homophonic and often fail to have a constant number of monophonic voices (e.g. "oom-pah" accompaniment alternates between 1 note and 2-3 notes at a time).
Answer: The standard approach to teaching counterpoint, and it sounds like your class took this approach as well, is based on a method devised by Johann Fux (Wikipedia: Fux) and first published in 1725 in his Gradus ad Parnassum.
Fux introduced the idea of "species" of counterpoint. The first is note against note; the second is two notes against one note.
In the third species, one is allowed to use more notes (four, specifically), so that's where the answer to your question lies. For a comprehensive list of the rules for third species see on this site: Fux's Third Species (two part) melodic movement - except for cambiata movement to and from dissonance only by step?
There are a couple of other questions on this site dealing with specific details of the third species.

Counterpoint (Fux): 3rd species, 3 voices, closing formulas
Can you leap to a 4th on weak beats in 3rd species counterpoint

To learn third, fourth, and fifth species, you can go right to the source with Alfred Mann's translation, The Study of Counterpoint from Johann Joseph Fux's Gradus Ad Parnassum.
Comment: In my experience, the Fux book is one that leaves more questions than answers.  If you find that you really want to learn how to write perfect, elegant counterpoint you should get a copy of Jeppesen's Polyphonic Vocal Style of the 16th Century.
Comment: Thank you for your insight. I am familiar with the concept of counter point (I am not familiar with all the rigorous rules of counterpoints, yet). However, I want to know the "rules" or practice in the context of harmony. I.e. using major and minor scales, modern meters, cadences, and triadic harmony.
Comment: @Philomath_theory I recommend to update your question to make that clear. You also will get better answers if you describe in more detail the sorts of rules you learned already and the exercises you did to learn them, since it sounds like the class(es) you took didn't follow the traditional music-theory-teaching route. In general, the rules you're seeking have their origin Fux's rules for counterpoint, but you'll need to be more specific about the context in which you're trying to apply them. This is a huge subject area, so a general question isn't likely to get you what you want.
Comment: Thank you for the reply. I went ahead and took your advice and updated my question. To clarify, I would like to know the "rules" or practice in the context of Four-part Tonal Harmony.
Comment: @Philomath_theory It's a good update. Just know, those rules come straight out of Fux.
Comment: Ok, thank you! And, thank you for the links! I went ahead a read through the references you posted. I understand that when utilizing one nct between two chords in a chord progression, I have to check voices for direct and hidden parallel fifths and octaves between chords on strong beats and make sure that the weak beat pitch doesn't create new parallels in between the two chords. But, how does this procedure change when using multiple melody notes (ncts & chord tones)? The link didn't explicitly specify.
Comment: @Philomath_theory Let's see what other answers you get to your question. In general, what you're asking is the subject of an entire college-level music theory class, so not something I can easily summarize.
Comment: Lolol, no doubt. But, I do appreciate your effort a lot.
Comment: Perhaps you can answer this. Let's say I have a two chord progression written in four-part harmony that consists of a I chord and a V6 chord in the scale of C major in 4/4 time. The bottom 3 notes of both chords are whole notes. The top melody notes are quarter notes. Let's say I compose a melodic line that consists of the notes C, D, E, F, G. The notes C starts on the I chord and the note G ends on the V6 chord. When checking for parallels between strong beats, do I have to check for parallels between beat 1 and beat 3 in the first measure, and beat 3 and beat 1 in the second measure?
Comment: @Philomath_theory Please open that as a separate question. That way the answer, which might be useful to others, won't get buried here in the comments.
Comment: Ok, I went ahead and posted it here: https://music.stackexchange.com/questions/117041/what-is-the-proper-way-to-check-for-parallels-when-using-multiple-ncts-and-chord .


Invalid DateTime - Ruby

Question: I'm trying to format a datetime string that I receive as a parameter. However, I'm getting an invalid date error.
The parameter params[:job][:start] for example has the value of 02/22/2018 5:20 PM.
I am getting an invalid date error from the code below. I am trying to format the date parameter to this format YYYY-MM-DD HH:MM:00 +0000
Please notice that the parameter being sent is in 12 hour time and the format that I am trying to format that parameter to is in 24 hour time.
DateTime.strptime(params[:job][:start],"%Y/%m/%d %H:%M:00 +0000")

Comment: You're parsing it as if it's YYYY/MM/DD format but you clearly state it's in MM/DD/YYYY format.
Answer: You should parse the string into the DateTime instance in the first place:
DateTime.strptime('02/22/2018 5:20 PM', '%m/%d/%Y %l:%M %p')

Then you might spit it out in any format you want.
More info on formatters.

Invalid DateTime - Ruby


Why does java require a cast for the instantiation of a bounded type parameter to its upper bound class?

Question: Java requires the instantiation of a bounded type parameter to its upper bound class to have a cast, for example:
<T extends Integer> void passVal (T t) {
    Integer number = 5;
    t = (T) number; // Without cast a compile error is issued
}

T is already restricted to Integer or one of its sub classes (I know, there aren't any) upon declaration, and it seems to me that any bounded type parameter may only be instantiated to its upper bound class or one of its sub classes, so why is the cast needed?
Also, I know that this isn't the case if I instantiate the parameter through invocation outside of this method, so don't offer that as a answer; the question is specific to bounded type parameters being instantiated within their declaring class/methods.
Answer: T doesn't mean Integer, it must be valid for Integer or any class that extends from it. Let's say that StrangeInteger extends from Integer and replace T with StrangeInteger:
void passVal (StrangeInteger t) {
    Integer number = 5;
    t = (StrangeInteger) number;
}

It attempts to assign a Integer variable to a StrangeInteger variable, you can't do that unless number was a StrangeInteger or a derived class in the first place. In fact your code should (conceptually) throw an Exception at runtime unless t is an Integer, but it won't actually do that in this case due to type erasure (see Edit 2).
The situation is similar to:
Object obj = "Hello"
String t = (String)obj; // this will not fail, but requires a cast

Object obj2 = getDBConnection();
String t2 = (String)obj2; // this will fail at runtime

Edit: Integer is indeed final, so T can only be Integer, but it's possible that the compiler is not checking if the upper bound is final, after all it makes little sense for an upper bound to be final, so allowing that special case adds complexity for very little real gain.
Edit 2:
TL; DR: You are confusing upper and lower bounds, but there are caveats with type erasure. This will break as soon as you do anything that is worth doing using generics rather than just using the base type.
English is not my first language so I may be not totally clear.
I think you are struggling with the difference between using a generic type with an upper bound and just using the upper bound as type. The idea of generics (from C++ and other languages) is that the code must be valid if you replace T by any type T allowed by the bounds, so you can't call any method that is not defined in the upper bound.
A being an upper bound on T also means that you can always assign a T object to an A variable. You can't assign safely an A object to a T variable (unless A == T), you could only do that if A was a lower bound on T, not an upper bound. Also see Understanding upper and lower bounds on ? in Java Generics.
Java uses type erasure to implement generics, there are a few advantages, but that causes some limitations that are not always apparent. Because of type erasure in this case the cast itself won't fail, after type checking T is replaced by the upper bound in the type erasure step, i.e. (T)number is replaced by (Integer)number. An exception will still occur if you do anything that causes a cast to the subclass, for example if you return the altered t and assign the result to a variable of the subclass, because the compiler adds an implicit cast.
This will also fail if you call a method that depends on an subclass of T, which is a common pattern, for example:
List<Person> persons = ...
Comparator<Person> nameComparator = (p1,p2) -> p1.getName().compareTo(p2.getName())
java.util.Collections.sort(persons,nameComparator);

The following code sample display the behavior in several cases. I used System.err on everything to avoid order issues in the output.
import java.util.function.Consumer;
import java.util.function.Function;

class A {
    @Override public String toString(){ return "A";}
    public String foo(){ return "foo";}
}

class B extends A {
    @Override public String toString(){ return "B";}
    public String bar(){ return "bar";}
}

class C extends B { }

public class Main {

    public static void main(String[] args) {
        Function funA = a -> a.foo();
        Function funB = b -> b.bar();
        Function<C,String> funC = c -> c.bar();
        Consumer ignoreArgument = b -> {
            System.err.println("  Consumer called");
        };

        B b = new B();
        System.err.println("* voidTest *");
        voidTest(b);
        System.err.println("------------");
        System.err.println("* returnTest *");
        returnTest(b);
        System.err.println("returnTest without using result did not throw");
        System.err.println("------------");
        try {
            System.err.println("Returned " + returnTest(b).toString());
            System.err.println("returnTest: invoking method on result did not throw");
        }
        catch(Exception ex) {
            System.err.println("returnTest: invoking method on result threw");
            ex.printStackTrace();
        }
        System.err.println("------------");
        B b2 = null;
        try {
            b2 = returnTest(b);
            System.err.println("returnTest: assigning result to a B variable did not throw");
        }
        catch(Exception ex) {
            System.err.println("returnTest: assigning result to a B variable threw");
            ex.printStackTrace();
        }
        System.err.println("------------");
        System.err.println("* functionTest funA *");
        functionTest(b, funA);
        System.err.println("------------");
        System.err.println("* functionTest funB * ");
        functionTest(b, funB);
        System.err.println("------------");
        System.err.println("* consumerTest *");
        consumerTest(b, ignoreArgument);
        // The following won't work because C is not B or a superclass of B
        // Compiler error functionTest(T, Function<? super T,String>) is not applicable for the arguments (B, Function<C,String>)
        // functionTest(b, funC);
    }

    private static <T extends A> void voidTest(T t){
        System.err.println("  Before: " + t.toString());
        t = (T)new A(); // warning Type safety: Unchecked cast from A to T
        System.err.println("  After: " + t.toString());
    }

    private static <T extends A> T returnTest(T t){
        System.err.println("  Before: " + t.toString());
        t = (T)new A();
        System.err.println("  After: " + t.toString());
        return t;
    }

    private static <T extends A> void functionTest(T t, Function<? super T,String> fun) {
        System.err.println("  fun Before: " + fun.apply(t));
        t = (T)new A();
        try {
            System.err.println("  fun After: " + fun.apply(t));
        }
        catch(Exception ex) {
            System.err.println("  fun After: threw");
            ex.printStackTrace();
        }
    }

    private static <T extends A> void consumerTest(T t, Consumer<? super T> c) {
        System.err.print("  Before: ");
        c.accept(t);
        t = (T)new A();
        try {
            System.err.println("  After: ");
            c.accept(t);
            System.err.println("    c.accept(t) After: worked");
        }
        catch(Exception ex) {
            System.err.println("    c.accept(t) After: threw");
            ex.printStackTrace();
        }
    }
}

The output under OpenJDK 11 is:
* voidTest *
  Before: B
  After: A
------------
* returnTest *
  Before: B
  After: A
returnTest without using result did not throw
------------
  Before: B
  After: A
returnTest: invoking method on result threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
    at Main.main(Main.java:35)
------------
  Before: B
  After: A
returnTest: assigning result to a B variable threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
    at Main.main(Main.java:45)
------------
* functionTest funA *
  fun Before: foo
  fun After: foo
------------
* functionTest funB *
  fun Before: bar
  fun After: threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
    at Main.functionTest(Main.java:83)
    at Main.main(Main.java:57)
------------
* consumerTest *
  Before:   Consumer called
  After:
    c.accept(t) After: threw
java.lang.ClassCastException: class A cannot be cast to class B (A and B are in unnamed module of loader 'app')
    at Main.consumerTest(Main.java:97)
    at Main.main(Main.java:60)

I'm not entirely sure resultTest why didn't caused an exception if the result is completely ignored, maybe a cast is not required by the language in that case, or the compiler removed it. Calling a method defined in the upper bound on the result still caused an exception. Finally an observation from consumerTest is that it didn't need to call  bar() to cause a ClassCastException, it just needed to pass t to the consumer that expects a B argument.
Comment: If you return T and pass a B argument the return type will be B, not A. Also you can pass an instance of a generic type that is specific to the type argument, an example is a custom Comparator for [Collections.sort(list,comparator)](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)).
Comment: The funny thing is that your code as it is will actually work. Because of [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html), a quirk of Java generics, the cast itself won't fail. It will throw a ClassCastException later if you return t and use the result or call anything that needs T instead of A. I will edit my answer later with more details.
Comment: I thought this answered my question, but after experimentation I'm still a little confused. It seems like what you're are saying is that the cast is required to avoid cast errors at runtime. If we were to create two classes A and B, B extends A. A has a method and B declares it's own as well, and then we create a method with a type parameter of upper bound A, and use the reference of that parameter to access methods of the type parameters class will are only allowed to access methods defined in A, not B. So you are allowed to pass sub classes but it will be treated as the upper bound class
Comment: It seems like if you pass that parameter an instance of B when calling the method, behind the scenes java will instantly convert by saying: A a = new B(); because the type parameter's upper bound is A. If that's the case it's hard to imagine a scenario where a cast error can occur, making the cast redundant. What am I getting wrong?
Comment: Thank you for going out of your way to provide such an elaborate answer! So here's what I think I've been missing: 1. You should not assign a instance of a upper bound to the bounded type within the declaring class/method, because it is risky and may cause run time errors when the method/class is invoked/instantiated in a meaningful way. 2. I now realize that the cast is required because java does not know at compile time if you are down casting.
Answer: The language specification does not currently include explicit checks for finalized types in any sense.
I checked:

§8.4.4 - Generic Methods

And, even though they don't apply to your case, I took the liberty of checking:

§8.1.2 - Generic Classes and Type Parameters
§8.8.4 - Generic Constructors
§9.1.2 - Generic Interfaces and Type Parameters

Even though Integer is final, if it wasn't, your code could break.

What you have, assuming the compiler doesn't check for finalized types, would be similar to:
class Super
class Sub extends Super

<T extends Super> void passVal (T t) {
    Super super = new Super();
    return (T) super;
}

Which would break if we called:
passVal(new Sub());

Comment: Are you sure it would break? I'm not getting an error, it seems as though your return is literally saying return (Super) super; I just tried it with two classes A and B, B extends A; created a method with bounded parameter of A, then passed it an instance of B, and got no run time error. The method created an object of A (super) and then returned (T) super.


why do i get Notice: Undefined offset: 65 and how to fix it

Question: I keep getting this Notice: Undefined offset: 65 on line 31 which is this line if($k[$c]) $p = preg_replace('/\b'.base_convert($c, 10, $a).'\b/', $k[$c], $p);. How can I fix this?
//function to get source html
function get_data($url) {
    $curl_handle=curl_init();
    curl_setopt($curl_handle,CURLOPT_URL,$url);
    curl_setopt($curl_handle,CURLOPT_TIMEOUT,10);
    curl_setopt($curl_handle,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:184.108.40.206) Gecko/20080311 Firefox/220.127.116.11');
    curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
    $html = curl_exec($curl_handle);
    curl_close($curl_handle);

    return $html;
}

//function to extract string beteen 2 delimeters
function extract_unit($string, $start, $end) {
    $pos = stripos($string, $start);
    $str = substr($string, $pos);
    $str_two = substr($str, strlen($start));
    $second_pos = stripos($str_two, $end);
    $str_three = substr($str_two, 0, $second_pos);
    $unit = trim($str_three);

    return $unit;
}

//function to decode packer endcoding
function js_unpack($p,$a,$c,$k) {
  while ($c--)
    if($k[$c]) $p = preg_replace('/\b'.base_convert($c, 10, $a).'\b/', $k[$c], $p);

  return $p;
}

//url source;
$adcrunch = get_data("http://adcrun.ch/BuVE");

//gather js_packer arguments
$arg_p = extract_unit($adcrunch, 'return p}(\'', ';\',');
$arg_a = extract_unit($adcrunch, '});\',', ',');
$arg_c = extract_unit($adcrunch, ',10,', ',\'|a0x1');
$arg_k = extract_unit($adcrunch, ',\'|', '\'.split');

$p = $arg_p;
$a = $arg_a;
$c = $arg_c;
$k = explode('|', $arg_k);

echo js_unpack($p, $a, $c, $k);

Comment: There's no array element `$k[65]`. Either check that an array key exists before calling it, or do something else to check your array bounds after `$c--`
Answer: Undefined offset means there is no index 65 in the array $k
You could "avoid" the warning by doing either:
if(isset($k[c]))

or
if(array_key_exists($c, $k))

Shai.
Comment: Thanks but can I ask you if this code (http://pastebin.com/DrCc3ncq) matches the js_unpack function? because When I add `if(array_key_exists($c, $k))` it returns a blank page.
Comment: I'm not familiar with PHP versions of the packer, but you can try this : http://drupal.org/files/issues/js-packer.inc_.txt
Answer: Try this one instead
if(isset($k[$c]) && $k[$c])

$c is probaly 65, and $k[65] does not exist
Answer: Or you use
if(array_key_exists($c,$k)) ...


Drupal 7 Views url translated alias with contextual filter

Question: I want to translate the url of my view. So I've made a translated alias for it. But when I add a contextual filter I get a 404 error.
For example: I've a view with the url example.com/overview with alias example.com/overzicht this works. This works also example.com/overview/[category], but this doesn't work: example.com/overzicht/[category]
How can I fix this?
Comment: Hmm... that should work :) Although I don't have an environment to test now. You've done it the right way as http://www.bariswanschers.com/blog/translating-views-paths-drupal ie. Seems like an old sandbox tries to solve the problem but it feels that should have been solved by now http://cgit.drupalcode.org/sandbox-yusupov-1178106/tree/aliasarg.module. Some discussion https://www.drupal.org/node/504616#comment-1752596
Comment: you also can write some code to do that , if you are familiar with drupal coding I can guide you how to solve this problem using hook_views_query_alter() .
Answer: I've finally found the solution for my problem, after a couple of hours :).
It was solved after installing the Extended Path Aliases module.
Answer: The "Sub-pathauto (Sub-path URL Aliases)" module also does the trick (and has an official D8 version as well).


How to relocate vector table and change starting addressin cortexm3 using uvision(Keil)?

Question: I'm using a STM32F107 cortex m3 microcontroller. I'm using the Keil uvision IDE for the project. I have an application which is running properly at the starting location i.e 0x0800 0000. If I change the starting location to 0x0800 4000 the application is not working properly. I made changes to the vector table location using this function as such:
NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x8004000)

i.e changed SCB->VTOR = 0x8004000 to this location.
But even after doing this interrupt is not happening. Should I do anything more to make this project work?
Comment: This is not the answer to your question, but I'd suggest that you make a global or static array, which is large enough to contain a duplicate of the vector table and pointing the vector to this, instead of setting the address directly. The reason for my suggestion is that as your program grows, it might allocate variables that overwrite the vector table, as variables get allocated. Another solution is to edit the linker-script and reserve enough space for a vector table there.
Comment: I suspect you are trying to say that the vector table in your application is re-located to 0x0800.0000 after boot up, and now you're trying to move it to 0x0800.4000?  Have you verified that the vector table is actually located by your toolset at the new address?  And you say "the interrupt is not happening" - what exactly does that mean?  A lot has to go right in between a peripheral asserting an interrupt and you running your ISR - stack setup, enable interrupts at CPU, NVIC interrupt priority, proper interrupt vector installed, peripheral interrupt unmasked, etc.
Comment: When I looked at the map file ,the vector table is located at 0x0800 4000 itself. I think there is some initialization error.  checking on that
Answer: You should not use NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x8004000), use NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x4000). The second argument is the "offset", not the absolute address.
Comment: One should take care of vector table alignment. ARM says: "The vector table base must always be aligned to at least the number of exception vectors implemented". See VTOR register description for details.
Answer: Add the below instruction just after the HAL_Init();
SCB->VTOR = (FLASH_BASE | 0x4000);
You also need to update the interrupt vector address in the STM32F1xc_flash.icf file as below.
define symbol ICFEDIT_intvec_start = 0x08004000;
Answer: I did this for my STM32L496, and it was important to set the new vector table before calling HAL_Init(), because it calls HAL_MspInit(), which may use the SysTick to measure timeouts while setting up some peripherals.


Increase security of DB INSERT

Question: Currently, I have a PostGIS DB, and I have the basics working. However, I am inserting directly into the database using pg_query. I have been recommended to use pg_query_params to help prevent against SQL injections, but am unsure how to implement this. Below is a cut-down example of my current insert statement for a site location. How would I, for example, utilise pg_query_params with this example? I know I will have to implement further security, but it is a starting point.
EDIT: I was going to use the drupal form API but it gave me headaches. I realize that would do a lot of this stuff automatically.
$sql = "INSERT INTO sites_tbl (river_id ,sitename ,the_geom) VALUES ('$_POST[river_id]','$_POST[sitename]',st_geomfromtext('POINT($geomstring)',27700))";
$result = pg_query($sql);

Comment: I had it on there and then I was told to put it here. My question does say I am looking to prevent sql injection on the query....
Comment: This is better suited for stackoverflow,  also this query is vulnerable to SQL Injection.
Answer: Because you are using strings rather than parameters, your example is vulnerable to SQL injection. It's best to avoid pg_ functions. In your case there are two things you need to take into account:

Learn the Drupal API (considering you are using Drupal this would be the best for code consistency

or

Use stored procedures
Use a library like PDO or pg_query_params which takes care of parameterized queries

Normally you use stored procedures in addition to PDO, unfortunately sometimes this is not manageable because you have too much code. My advice is to use as much stored procedures as possible.
Comment: So I couldn't just convert the insert to utilise params? I am researching the drupal form api now
Comment: I've added the page for pg_query_params

Increase security of DB INSERT


Fourier series of $f(x)$ and its convergence

Question: sorry for the inappropriate format. I'll edit asap. question is about convergence of series.
Can you explain why is "f(x)=1 ,f(x)=1/2"  please.
Answer: Since $f$ is piecewise smooth, its Fourier series converges at $x=a$ to the average of the left and right hand limits of $f$ at $x=a$. If $f$ is continuous at $x=a$, then this says the Fourier series of $f$ converges pointwise to $f(a)$.
Since $f(x)={1\over 2}$ on $-\pi<x<0$ and this is continuous, the Fourier series also converges pointwise to ${1\over 2}$ on $-\pi<x<0$.
Similarly, the Fourier series converges pointwise to $1$ on $0<x<\pi$.
More interesting is that we can also deduce the value of the Fourier series at $x=\pm\pi,0$ from the result above.
Comment: I did know that rule.  but how stupid of me didnt see what the function is. probably cz of sleeplessness :)


Using Datamining/Statistics for Log Monitoring

Question: I have a large set of log files that I want to characterize or possibly add some kind of decision tree or some kind of analytics.  But I don't know exactly what.  What kind of analysis have you done with log files, a lot of log files.
For example, so far I am collecting how many requests are made to a particular page for a given log file.
Servlet = 60 requets
Servlet2 = 70 requests, etc.
I guess right there, filter by only the most popular requests.  Also, might do something like 60 requests given a 2 hour period.  60 / 160 minutes.
Comment: What kind of log files are they? Apache, /var/log/messages, Windows Events, etc...?
Comment: How did you put a bounty on a new question?
Answer: Deciding what analysis to do depends on what decisions you're trying to make based on that analysis. For example, I currently monitor logs for exceptions reported by our application (all exceptions in the client application are logged with the server) to decide what should be high priority client bugs to investigate. I also use log searching software to monitor for any Exceptions reported by our server software which may need more immediate investigation. On top of the logs generated by everything anyway, I also use some monitoring software to track usage of our web server and database server which records usage stats etc. in a database. The final aim of this is to predict future usage levels and purchase more hardware as appropriate to keep up with demand.
Two (free) tools I've been using are:
Hyperic for monitoring, it's pretty easy to set up and might be able to start logging a lot of data you may be interested in, ie requests per second on a web server.
Splunk for searching log files, it's very easy to get set up and work with and gives you excellent searching capabilities over your log files. If you're working with log files right now and haven't tried out splunk I definitely recommend it. I have noticed a couple of moments of 100% cpu whilst using it on our main production server so stopped running it on that machine recently, just a word of warning.
Not sure what your aim is with this analysis, mine has been very much about looking for any errors I should know about, and planning for future capacity needs. If you're interested in the latter I'd also recommend The Art of Capacity Planning.