Scala IDE throwing java.lang.NoClassDefFoundError: org/codehaus/janino/JaninoRuntimeException

Question: I am getting Runtime Exception for Spark DataFrame code when I'm trying to execute spark code in Scala IDE (Eclipse Version 4.7).
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.SQLContext
object Demo {
  def main(args:Array[String]){
    val conf=new SparkConf().setAppName("Local App").setMaster("local[2]")
    val sc=new SparkContext(conf)
    val spark=new SQLContext(sc)
    import spark.implicits._
    val data =Seq((1,"ab"),(2,"abc"))
    val dataRDD=sc.parallelize(list)
    val df=dataRDD.toDF()
    df.show() // Getting Exception here
  }
}

Above code is working fine when I am executing using spark-shell. But problem is when I use with Scala IDE. I am using Mac OS. Exception Message and POMbelow:
Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/janino/JaninoRuntimeException
    at org.apache.spark.sql.catalyst.expressions.codegen.GenerateSafeProjection$.create(GenerateSafeProjection.scala:194)
    at org.apache.spark.sql.catalyst.expressions.codegen.GenerateSafeProjection$.create(GenerateSafeProjection.scala:36)
    at org.apache.spark.sql.catalyst.expressions.codegen.CodeGenerator.generate(CodeGenerator.scala:930)
    at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:2860)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2150)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2150)
    at org.apache.spark.sql.Dataset$$anonfun$55.apply(Dataset.scala:2842)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:2841)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2150)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2363)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:241)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:637)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:596)
    at org.apache.spark.sql.Dataset.show(Dataset.scala:605)
    at Demo$.main(Demo.scala:15)

pom.xml
`
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Demo</groupId>
  <artifactId>Demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>Demo</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.2.1</version>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.2.1</version>
</dependency>
  </dependencies>
</project>

`
Comment: Do you use Maven?
Comment: Yes, Maven 4.0.0 that available with Scala IDE 4.7
Comment: Please update the question and provide pom.xml
Comment: I updated my Pom.xml
Answer: I have found solution for this issue.
Solution: In Scala IDE go to :

Help -->Install New Software --> Unchecked Contact all update sites during
  install to find required software

Below I have attached screenshot.
Comment: This is helpful bot Mac and window version of Scala IDE.


Aceitar somente números no aplicativo console C#

Question: Boa noite, estou tentando fazer com que o comando Console.ReadLine() leia somente números, ignorando caracteres, tem algum jeito ?
exemplo:
static void main()
{
    int x;

    Console.WriteLine("INSERINDO VALOR PARA X");

    x=int.Parse(Console.ReadLine()) //em execução quero que o console só aceite números inteiros do teclado.

}

Comment: Muito obrigado pelas resoluções, consegui implementar em meu código, mas estou tendo dificuldades para apagar a tecla que foi digitada, no caso de clique errado. Alterei esse código para reconhecer o Backspace más ele trava o console.
Comment: Mas esse comentário é dirigido para quem? Para mim ou para Daniel. Quando assim faça o comentário na resposta, pressionando o botão `comentar` em baixo da resposta, que assim o autor da resposta será notificado.
Comment: Se é C# por quê a tag C?
Answer: Gabriel, se existe alguma forma nativa de fazer isso, desculpe mas não conheço.
Geralmente, as pessoas adotam um loop que mantém o usuário "preso" enquanto o que ele digitar não for um número, sendo que o cast é feito de uma forma que não gera exceção.
Veja um exemplo:
using System;

class ReadLineInt {
  static void Main() {
    int x;

    Console.WriteLine("INSERINDO VALOR PARA X");

    while(!int.TryParse(Console.ReadLine(), out x)) {
         Console.WriteLine("Insira apenas números inteiros");
         Console.WriteLine("INSERINDO VALOR PARA X");
    }

    Console.WriteLine("Número digitado: " + x);
  }
}

Comment: Interessante, vou adaptar este exemplo para ver como fica, muito obrigado.
Answer: Você pode implementar um método que faça a leitura exclusiva de números pressionados dentro do Console.
Para isso você terá iniciar um loop e terá que testar a cada iteração se uma tecla foi pressionada com Console.KeyAvailable que retorna um booleano indicando se houve o pressionar de uma tecla.
Se Console.KeyAvailable acusar um pressionar de teclas é instruir a leitura da tecla com Console.ReadKey(); passando true como primeiro parâmetro de forma a evitar que a tecla lida seja impressa na tela do 'Console'.
Então teste a natureza da tecla pressionada:

Se for um número acumule na string de retorno do método.
Se for a tecla enter encerra a iteração.
Se a tecla for back space remove o último caractere do console(vide altrações no código).
Qualquer outro valor ignore.

Usando switch case when com a sintaxe da versão 7 ou superior do C#:
using System;

class Exemplo
{
    public static string lerNumeros()
    {
        ConsoleKeyInfo cki;
        string entrada = "";
        bool continuarLoop = true;
        while (continuarLoop)
            if (Console.KeyAvailable)
            {
                cki = Console.ReadKey(true);
                switch (cki.Key)
                {
                    case ConsoleKey.Backspace:
                        if (entrada.Length == 0) continue;
                        entrada = entrada.Remove(entrada.Length - 1);
                        Console.Write("\b \b"); //Remove o último caractere digitado
                        break;
                    case ConsoleKey.Enter:
                        continuarLoop = false;
                        break;
                    case ConsoleKey key when ((ConsoleKey.D0 <= key) && (key <= ConsoleKey.D9) ||
                                              (ConsoleKey.NumPad0 <= key) && (key <= ConsoleKey.NumPad9)):
                        entrada += cki.KeyChar;
                        Console.Write(cki.KeyChar);
                        break;
                }
            }
        return entrada;
    }
    public static void Main()
    {
        Console.WriteLine("Insira o valor para X.");

        int x = int.Parse(lerNumeros());

        Console.WriteLine("\nO valor de X é '{0}'.", x);

        Console.ReadKey();

    }
}

Usando if independente da versão da linguagem:
using System;

class Exemplo
{
    public static string lerNumeros()
    {
        ConsoleKeyInfo cki;
        string entrada = "";
        while (true)
            if (Console.KeyAvailable)
            {
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Backspace){
                    if (entrada.Length == 0) continue;
                    entrada = entrada.Remove(entrada.Length - 1);
                    Console.Write("\b \b"); //Remove o último caractere digitado
                }
                if (cki.Key == ConsoleKey.Enter)
                {
                    break;
                }
                if ((ConsoleKey.D0 <= cki.Key) && (cki.Key <= ConsoleKey.D9) ||
                    (ConsoleKey.NumPad0 <= cki.Key) && (cki.Key <= ConsoleKey.NumPad9))
                {
                    entrada += cki.KeyChar;
                    Console.Write(cki.KeyChar);
                }

            }
        return entrada;
    }

    public static void Main()
    {
        Console.WriteLine("Insira o valor para X.");

        int x = int.Parse(lerNumeros());

        Console.WriteLine("\nO valor de X é '{0}'.", x);

        Console.ReadKey();

    }
}

Código no Repl.it
Comment: Consegui resolver meu problema com esses exemplos, só falta a parte de incluir o backspace que ainda estou verificando. Muito obrigado.


Android custom keyboard: change candidate height

Question: I'm writing a custom keyboard and I want to use the candidate.
But the candidate view is set to a certin height which is to small for my needs.
I cant seem to set the height of the candidate. if I set the height to certine dp i get half black screen.
Thank you!
Answer: The height of the Android Custom Keyboard candidate view could be chang from CandidateView.java file. Open the file and find the below line:
final int desiredHeight = ((int) mPaint.getTextSize()) + mVerticalPadding
                + padding.top + padding.bottom;

And add number with it as follow:
final int desiredHeight = ((int) mPaint.getTextSize()) + mVerticalPadding
                + padding.top + padding.bottom + 20;

The 20 at the end of code line increases the height of candidate view.


Is it possible to prove the demiclosedness principle for non uniformly convex Banach space?

Question: The demiclosedness principle asserts that if $K$ is a closed convex subset of a uniformly convex Banach space $X$ and if $T:K\rightarrow X$ is nonexpansive, then $Id-T$ is demiclosed.
The proof can be found in "Nonexpansive nonlinear operators in a Banach space" by Browder (1965).

Do you know if it is possible to prove the same result without the requirement that the space is uniformly convex? Thank you in advice for your help.
Answer: Suppose $X$ is a nearly uniformly convex (NUC) Banach space with Opial's condition, $C$ is a nonempty weakly compact convex subset of $X$, and $T: C\rightarrow C$ is a mapping of asymptotically nonexpansive type and $T^N$ is continuous for some $N \geq 1$. Then $I - T$ is demi-closed at zero.
So the conclusion is that the condition UC can be relaxed to NUC.


Does good intonation alone really make you "louder"? If yes, why?

Question: I have multiple times heard this claim, from very different sources.
There certainly seems to be some correlation between intonation and "loudness", in the sense that ensembles with great harmony playing/singing tend to give an impression of inherent power – without needing any brute force or particularly loud instruments.

That sounds more powerful to me than a not-so-great brass ensemble, let alone any vocal harmonies that were severed with autotune. (Please nobody tell me 12-edo is good intonation!)
However, is there really any direct way in which good tuning makes a voice louder? At least if we consider loudness as purely physical power (Fletcher-Munson weighted or not), this seems doubtful: energy is conserved, it doesn't care whether frequencies match up exactly. So if there's any such relation, I suppose it would have to be a more complex psychoacoustic kind of loudness.
Does such a thing really happen, or is it merely the case that good players will generally have, apart from better intonation, also a "better tone" – which in itself already sounds subjectively firmer/louder, regardless of intonation?
Comment: not any attempt to answer, however - did Robert Plant exactly hit every single note? No. Does he sound like he could break windows? Yes. QE[not at all]D
Comment: Plant had an ear for the blending of sound waves, so whether or not he showed up as 'in tune' on a tuner, his pitch was always perfect for the musical context at hand.
Comment: Amplitude, at any rate, is rather useless as an indicator for loudness. (Otherwise, there would be no point in compressing/limiting record masters.) If anything, you need to talk about amplitudes of some single frequency, but I also don't think that's helpful – after all, white noise sounds louder than any sine wave of the same ampliture, though it's Fourier transform is lower at every single frequency. (Do correct me if I'm thinking wrong here!) That's why I discussed _power_ (i.e. RMS), but as I said the argument _can't_ really be true in that sense, since energy is conserved.
Comment: You need to qualify your question to distinguish between perceived amplitude and *actual* amplitude.
Comment: @jjmusicnotes: I don't _know_; as I said I just heard this claim "it makes you louder", and I'd like to know in which sense of "loud" this is true or whether it's simply bogus.
Comment: I want to give a different viewpoint. When the cello was recorded with my band the engineer had noticed that the F was always quieter than the rest of the notes. It turned out that the acoustics of the body of the cello was to blame. So remember, the room, the instrument, your body will have resonant frequencies which will boost or cut certain frequencies.
Comment: @atoth: sure, but such instrument resonances should never influence your intonation!
Comment: I did an interview with an acoustic engineer and she told me that it's a bad idea to sing in the bathroom as the resonances that sound good in it might actually be very out of tune, so it can mislead people. Even in a rehearsal room.
Answer: Intonation is certainly important, but I'd like to add an observation about other factors. 30 years ago in music school I studied operatic singing (I'm a tenor).
With regard to being "louder", first there is learning to sing with greater volume, but second, and just as important, is learning to cultivate a certain resonance in the voice that involves learning to manipulate formants and resonant frequencies in the resonant cavities of the nasal passages, the mouth, the larynx and the chest, along with the use of diaphragm-muscle breath support, and vibrato, to learn to create a sound that "projects" or "cuts through" an orchestra or instrumental accompaniment so the audience can hear the singer clearly even though the singer is not using a microphone and is not being amplified.
This is a technique developed through trial and error and guided by the experience of a voice teacher, to produce what opera singers call the bel canto vocal tone. It is not, broadly speaking, something that is learned by entirely scientific or physiological measurements or study. But students learning opera singing are certainly taught a few things about the anatomy and physiology of the parts of their bodies used to produce the voice, and how to become aware of and eventually manipulate and control those parts.
Something of the same sort applies to different styles of singing as well. You gave an example of the neo-string-band music of Nickel Creek. In this video they are crooning rather softly, but they can also sing in the "high lonesome" old-time style, which doesn't use vibrato and which is miles away from opera singing. Yet the "high-lonesome" old-time singing style was developed long before there was such a thing as singing into a microphone through an amplification system; it's a style of singing that permits singers to be heard clearly over a string band unamplified.
It's fair to say that any instrumentalist who performs unamplified learns how to do something similar with their instrument. One way or another they learn that certain techniques of creating a certain acoustic tone will "cut through" and be heard over an orchestra or band, whereas other tones will be "buried beneath" the orchestra or band and won't be clearly heard.
Comment: These are some psychological effects and techniques to make a sound more apparent among other sounds (eg. bringing a solo to the front). But the effect of goood intonation making the overall sound of a solo performer or an ensemble stronger is missing. Vice versa ensembles with worse intonation sound weaker over all, even though they apply such loudness techniques.
Answer: I recognize the phenomenon and I believe that - among other factors (see below) - it must have to do with the way sound waves combine, i.e. with constructive or destructive interference. I think that your argument concerning energy conservation is not valid, because e.g. in active noise control sound waves are designed to cancel each other, so there is energy in both sound waves but the total sum is small (or, ideally, zero).
So if two notes are slightly out of tune, the total energy is possibly smaller than when they're exactly in tune. The same is true if voices are in harmony because of the harmonics which form a coherent spectrum if the interval between the fundamental notes is sung/played correctly.
So far the argument was purely physical. I believe that there are other factors. One of them is the way singers articulate the vowels when singing in harmony. The total sound becomes more coherent if, apart from singing in tune, the articulation (i.e. the filtering of the sound) matches closely. In a similar manner, when instruments play in unison or in harmony, the result will sound better/louder/more coherent if the phrasing and sound quality matches well.
Yet another factor is timing. And I'm talking about small timing differences, which can make a huge difference. So if a band or choir is very tight, i.e. if their timing is very well synchronized, they will be able to produce more power than otherwise.
I know that all arguments put forth here are speculations in the sense that I have no experimental evidence to back them up, but from my experience as a musician I'm pretty sure that all of them make a difference concerning the coherence and power of the total sound of an ensemble.
Comment: What do you mean by a "true stereo signal"? For an ordinary stereo-mic recording, the channels certainly are locked (at some complex, but fixed relation, for any stationary source). For a mix with signals not panned hard left/right even more so. — If you record the stereo channels as completely separate takes, then there is indeed no phase correlation, but that's almost never done (and for such a signal, you would in fact _not_ notice a difference when reversing one channel's polarity).
Comment: ANC uses a known _phase relation_ between a microphone on the outside of headphones, and the hp-speakers on the inside to always generate destructive interference _at one single spot_, namely the eardrum. This does (of course) not violate conservation of energy: summed over all space, the active NC actually makes the noise louder. Just because only your eardrums notice the sound at all, you feel it's made quiter. — Real musical instruments, even when played in perfect just intonation, don't phase-lock. Even if they did, room reflections would scramble the phases. So this argument doesn't work.
Comment: @leftaroundabout: I still think it does to a certain extent. ANC is of course an extreme example (BTW, there also is such a thing as *global* ANC). Connecting one of two stereo speakers out of phase will have a clear effect anywhere you listen. Similarly a wrong (out-of-phase) connection of one speaker of a 4x12 cab, etc. What I'm saying is that sound waves with frequencies slightly out of tune will produce some similar effect of weakening the total sound impression as opposed to sources that are coherent in pitch and timbre.
Comment: If you connect one of two stereo speakers with inverse polarity, the speakers are still phase-locked together. That's what never happens with instruments in an ensemble, regardless of intonation. (And FWIW, the "clear effect anywhere" of phase reversal only happens in the bass range, due to wavelength>≈separation; for treble frequencies the switching of the phase may be notable as _some change in sound_, but only near-field monitors make it really obvious which polarity is correct.)
Comment: @leftaroundabout: I do agree about the non-existence of 'phase-locking' of an ensemble. Yet, I don't think that's the point because, coming back to my over-simplistic example, for a true stereo signal there is no phase locking either, reversed polarity or not.
Comment: @leftaroundabout: The question is what you mean by "phase-locked". A correlation between left and right (which obviously exists in a "normal" stereo signal) does not represent "phase-locking" in any sense that I know of.
Comment: I mean by "phase-locked channels", each channel can be interpreted as the result of an [LTI transformation](https://en.wikipedia.org/wiki/LTI_system_theory) applied to the same signal. So for any given frequency, there is only a fixed (and often small!) phase difference between both channels. Whereas when instruments are playing together, each note will, regardless of pitch, have a completely random phase difference.
Comment: @leftaroundabout: According to that definition, whatever enters my left ear is phase-locked with what enters my right ear. So a live band would achieve perfect phase-locking inside my head.
Answer: The short answer is "Yes" and the facts behind that are "Resonance" and "Harmonics".

Resonance: Resonance happens when an object sounds a note, another object tuned to the same note starts vibrating and giving sound of the same note. So we get a louder tone when there are resonating objects around.
Harmonics: When a note is played the base frequency and its multiples are also sounded (eg. a vibrating 440Hz A string gives sounds in 880, 1320, 1760Hz...etc frequencies as well). Base note is the first harmonic that we perceive as the name of the note. Its following harmonics are also sounded with less and less magnitude (octave, octave + perfect fifth, second octave, second octave + major third...etc.).

So, if you play a note you can make resonate and sound everything around you tuned to the same note, its octave, perfect fifth, major third, minor third, seventh, ninth...etc. resulting in a very strong sound. Harmonics and acoustic resonance is very effective on instrument boards, well tuned open strings, sounding instruments with good intonation, vocal cords, and naturally on acoustic ensembles.
This effect multiplies a lot in ensembles making resonate every instrument around. If every player has a very good intonation, chords and crossing notes will sound not only louder but better in quality and closer to the composer's imagination. Good intonation is also very helpful in playing good quality quiet tones and chords with little effort. This is one of the reasons why good players and ensembles can make the same instruments sound different and better than average players.
Comment: Resonance _between_ different instruments or even voices? Seems unlikely to me, do you have any references on this? For empty strings on a single instrument this can of course have a great effect (Sitar etc.), but I can't see this working for e.g. a string ensemble (where each string is _much_ stronger affected by the bow than by the vibrations from other instruments; after all those need to be picked up again by the body and then sent to the strings through the bridge).
Comment: Allthough... I once played with a metal band, and the bass drum literally made my bow bounce on the strings, so strongly was it picked up by the cello body. But then, I was sitting right next to the drummer and it was an estimated 30 dB louder than a string ensemble could ever get, so...
Comment: Right, resonance between instruments is just "sympathetic resonance"...
Comment: @leftaroundabout It is not just resonating strings but also instrument bodies, already playing closed strings, fingered air tubes and other overlapping harmonics being played by other players. Also take into account that all successfully overlapping harmonics will be resonating and sounding from all instrument bodies, objects and room back to you. Poor intonation in ensembles does not give that effect by first hand experience.

Besides that, composer's success in writing and instrumenting a chord is also very effective acquiring chords full of sound.

Vocal cords of course work mostly one way.


is there any possible conflict for fields with the same machine name?

Question: i am trying to debug a paragraph not displaying fields and i am having

/admin/reports/fields

a same machine name for a field in 3 different paragraphs
field_call_to_action_ref    paragraph   Entity reference revisions (module : entity_reference_revisions)

    Bloc compositeParagraphe standardElement d'accordéon

Comment: This is no problem, as long as the field is of the same type and it is OK for you that they share the same field storage having all the same basic field settings, restricting you to change only settings which are stored in the content type like the field label and form/display settings.
Answer: Machine names for fields must be unique per entity type.
The means that with nodes, fields must be unique across all content types. So you can't create two fields with the same machine name on different content types, as both content types are nodes, and machine names must be unique for the entity type. (Edit - you can however re-use the same field on multiple content types, but it will be the same field, not two fields with the same machine name).
You can have a field_image on a node, and field_image on a taxonomy term. Here, the machine name is the same, but unique to each entity type, so there is no problem.


Display Author Pane in view (with Display Suite View Mode)

Question: I'm new to Drupal, but I couldn't find an answer for my problem in any other thread.
I've installed and configured Author Pane and I'm able to see it in places like a node page or advanced forum topic.
Now I'm creating a View that returns a list of nodes, and configured one of its Display Suite view modes for displaying each result (this view mode includes the Author Pane block for that content type).
The list of nodes is displayed OK, but the Author Pane is not being shown. The section of the view mode layout where the Author Pane should be displayed is empty.
I've already tried making a relationship with Author and setting the Author:name as one of the view's fields (I've read sth like that in some other posts), but nothing changed. It's like Author Pane cannot find any user context information.
Can someone help me with this issue ?
As a (maybe) related issue, I have another view that ends up in a block, which should also display the Author pane. This block appears at the bottom of a node page, which also has Author Pane configured. In that view block, Author Pane is actually being display for each results but always with the information of the user of the page's node! So, every secondary node related with the primary node displays the same Author information as the primary node, instead of its own author's information. I think both issues are related. There is some problem with Author Pane trying to get user information from views.
Thanks everybody in advance!
Comment: have you added the author pane block in your display suit view mode?
Comment: Yes, its a two columns layout view mode, and if I configure it as the default view mode for the node page, the Author Pane gets displayed. The problem is when I try to display it using Views.
Answer: For anyone who ends up in my same situation, I will post the answer.
Author Pane is only prepared to be displayed on full view nodes, but not in View's lists or Display Suite custom view modes. This is because calling the function "menu_get_object()" will not retrieve anything.
What you need to do is to alter Author Pane's function "author_pane_get_block()" or find a way to implement a hook to do the same thing properly.
I quickly edit the first condition removing the numerical condition of arg(1) and after $node = menu_get_object() line, I check if node is not set, and in that case, I assign $node variable the current view node from somewhere in the context. (in my case, I could get it from Display Suite context, but you can get it from anywhere, including (in the worst case) the stacktrace arguments.
Hope this helps someone!


How does Drupal know which Entity View Mode to use?

Question: When Entity View Modes are defined, how does Drupal know which to use? Are they only useful with Views, or can they be used in the node display as well? If so, is that specified in the template, or somewhere else?
Answer: With a tiny bit of glue code you can use specific node template files for different view modes, so they can become pretty useful:
function MYMODULE_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'some_type') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__some_type';
  }
}

That will allow you to use template files with names like node--article--some-type.tpl.php specifically targeted to that view mode.
Other than that MPD's answer has all of the other common cases covered.
Comment: Yeah, template suggestions w/ view modes is an awesome way to leverage their power.  We typically bypass the checks and build up suggestions with `$variables['theme_hook_suggestions'][] = 'node__' . $variables['view_mode'];` and `$variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];`
Answer: On the backend, the view mode is used everywhere node_view($node, $view_mode); is called.  In general, the caller specifies which is needed.  And since the system only knows about "full" and "teaser" by default, those are the ones that are baked into core.  Code does have the option of reading all of the view modes when it wants to get rendered content.
Views are the most obvious place the view modes get used, and also the place I find the most helpful.
If you have a node reference, and set the display to "Rendered Node" you can choose the view mode, and it will pull from the list.
In Panels the view mode shows up in the settings for the "Node Being Viewed" content pane.  This typically gets used in the node override page, and it the only way that I know of to specify the view mode for a node/$nid path.
I suspect there are other places, too, especially with modules that make use of CTools content types.
Comment: Is node_view something that would be used in the php template file, or from a module?
Comment: It's mainly used by the templating system and by the search module (to get the page text).  IIRC, the view mode gets passed around in the render tree as a parameter in normal circumstances.  I have never directly called it before.  Using it in your own template file is not a good idea.
Comment: If it cannot be used in a template file, then how can it be used to affect the template output?
Comment: Whatever is doing the templating (views, panels, etc) should be specifying the view mode.
Comment: So If I'm not using either, just wanting to control the output of /node/xyz directly, is this not the right thing to use?
Comment: Not that I am aware of.  This is why I typically use Panels for everything, even simple node view pages.  It makes changing behaviors of pages a lot easier.


Authentication Failed On SonarQube 6.6 macOS Sierra

Question: Not able to login on Sonarqube local url http://localhost:9000 with default credentials admin/admin. When trying to login always getting this error message Authentication Failed.This only happen for SonarQube 6.6 version not for latest 7.0.On latest version 7.0 am able to login successfully but why am not able to login on 6.6 version.Before 2-3 months ago I was able to login on Sonarqube 6.6 but now what happened I don't know.Please help me.Please find the attached log file
Comment: Please add your web.log file so we can understand what's happening.
Comment: @EricHartmann Web.log file attached.
Comment: We have no permission to access the log file
Comment: @JulienL.-SonarSourceTeam you can access the log file now.
Answer: According to your log files, you are using Java 9 or Java 10.
Using Java 8 will solve your issue.
Comment: thanks I know I installed idk 1.8 but by default jdk9 was default set.Also please mention this into your answer.
Comment: Note that the support of Java 9 has been fixed in SonarQube 6.7, which is the Long-Term Support version at the time of writing.


Button stays disabled after enabling it from thread until I focus

Question: I have got a button that will start a background task. It is bound to a command that will change a property to disable it until the task is finished. The task will complete and change to property back in the continueWith.
The button will stay disabled until I click anywhere in the window.
Here is the code:
<Button Command="{Binding StartCommand}"
        Content="Run"/>

public bool IsRunning
{
      get => _IsRunning;
      set
      {
            if (_IsRunning == value)
            {
                  return;
            }

            _IsRunning = value;
            NotifyPropertyChanged();
      }
}

private ICommand _StartCommand;
public ICommand StartCommand => _StartCommand ??
(_StartCommand = new RelayCommand(x =>
{
       IsRunning = true;

       var task = Task.Run(() => Thread.Sleep(1000));

       task.ContinueWith(t => { IsRunning = false; });

 }, x => !IsRunning));

public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Adding Application.Current.Dispatcher.Invoke() did not help as well.
I would like to understand what goes wrong and have a solution without code behind.
Thanks!
Comment: Also, does adding `CommandManager.InvalidateRequerySuggested();` help?
Comment: How does `IsRunning` is declared?
Answer: You can try to use CommandManager.InvalidateRequerySuggested(); to invalidate to command bindings.
Another option is setup Binding for IsEnabled property of Button to inversed IsRunning value and get rid of CanExecute predicate in RelayCommand
private ICommand _StartCommand;

public ICommand StartCommand => _StartCommand ??
                    (_StartCommand = new DelegateCommand(x =>
                    {
                        IsRunning = true;
                        var task = Task.Run(() => Thread.Sleep(1000));
                        task.ContinueWith(t =>
                        {
                            IsRunning = false;
                        });
                    }));

private bool _isRunning;

public bool IsRunning
{
    get => _isRunning;
    set
    {
        _isRunning = value;
        OnPropertyChanged(nameof(IsRunning));
    }
}

The xaml declaration
<local:InverseBooleanConverter x:Key="InverseBooleanConverter"/>
...
<Button Command="{Binding StartCommand}" Content="Run"
        IsEnabled="{Binding IsRunning, Converter={StaticResource InverseBooleanConverter}}"/>

InverseBooleanConverter declaration
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value is bool boolValue ? !boolValue : Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }

    #endregion
}

Answer: the idea here is that we setup our command's CanExecute to return whether or not the command can execute (the example here is !IsRunning).
we know when the command's ability to execute has changed right (when we are literally setting IsRunning to a new value), so when this happens, we should raise ICommand.CanExecuteChanged, because that's exactly what just happened, the command's ability to execute has just changed.
lo and behold, part of databinding Button.Commands is WPF hooking up not only the Execute method we provide but also the CanExecute method, and WPF will re-evaluate CanExecute when CanExecuteChanged is raised.
everywhere right after IsRunning is set we'd want to raise _StartCommand.CanExecuteChanged by calling Invoke on it, which can only be done within RelayCommand itself because of the time-old rule in C# of The event can only appear on left hand side of += or -=, so i'd suggest adding a protected void RaiseCanExecuteChanged in the RelayCommand to do just that: CanExecuteChanged?.Invoke(this, EventArgs.Empty).


Python script not executed from Cron

Question: I am trying to run a Python script from Cron but it does not work. I have already tried everything I have seen in multiple Stackoverflow questions.The machine is a Raspberry running Raspbian. The following piece of code is the edition of crontab:
PATH=/usr/sbin:/usr/bin:/sbin/bin:/sbin:/bin:/home/pi/miniconda/bin:/usr/local/bin:/usr/local/sbin

*/5 * * * * rsync -az --timeout=10 --progress email@example.com:Upload/*.csv /home/pi/PAD-S100/PAD-S100-Bloque_Motor/from_repo/ | /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/adddate_to_logs.sh >> /home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log 2>&1
*/5 * * * * /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/from_repo/launcher.sh | /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/adddate_to_logs.sh >> /home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log 2>&1
*/30 * * * * rm /home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log
* * * * * /usr/bin/python /home/pi/PAD-S100/PAD-S100-Bloque_Motor/from_repo/event_management.py | /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/adddate_to_logs.sh >> home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log 2>&1
0 0 * * * rm /home/pi/PAD-S100/PAD-S100-Bloque_Motor/from_repo/*.csv | /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/adddate_to_logs.sh >> /home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log 2>&1

Crontab Observations:

The Path obtained from echo $PATH is included.
launcher.sh, addddate_to_logs.sh and
event_management are executables using the command sudo chmod a+x <file_name>.

The log.log file does not show anything strange.
The system log file /var/log/syslog has the following logs:
Feb 27 15:11:08 raspberrypi cron[21814]: sendmail: Cannot open :25
Feb 27 15:12:01 raspberrypi rsyslogd-2007: action 'action 17' suspended, next retry is Mon Feb 27 15:13:31 2017 [try http://www.rsyslog.com/e/2007 ]
Feb 27 15:12:01 raspberrypi CRON[22209]: (pi) CMD (/usr/bin/python /home/pi/PAD-S100/PAD-S100-Bloque_Motor/from_repo/event_management.py | /bin/sh /home/pi/PAD-S100/PAD-S100-Bloque_Motor/adddate_to_logs.sh >> home/pi/PAD-S100/PAD-S100-Bloque_Motor/log.log 2>&1)
Feb 27 15:12:09 raspberrypi sSMTP[22212]: Unable to set UsesSTARTTILS=""
Feb 27 15:12:09 raspberrypi sSMTP[22212]: Unable to locate
Feb 27 15:12:09 raspberrypi cron[21814]: sendmail: Cannot open :25
Feb 27 15:12:09 raspberrypi sSMTP[22212]: Cannot open :25
Feb 27 15:12:09 raspberrypi CRON[22205]: (pi) MAIL (mailed 178 bytes of output but got status 0x0001 from MTA#012)

We can observe that it is probable that the failing crontab line is the one of the python script. As I am not an expert in Linux I believe it may be something related to the sSMTP. The same kind of error log appears after every call of the cron python script. But I have no idea of how to fix it or configure the local email.
Here is the piece of code of event_management.py file :
#!/usr/bin/python
# -*- coding: utf-8 -*-
import imaplib
import email
import csv
import datetime

EMAIL = <email_user>
FROM_PWD = <password>
SMTP_SERVER = 'mail.o365.alstom.com'
datum = dict()
translate = {'#09': 1, '#0A': 2, '#0B': 3, '#0C': 4}

def connect_imap():
    mail = imaplib.IMAP4_SSL(SMTP_SERVER)
    mail.login(EMAIL, FROM_PWD)
    return mail

def read_email_from_gmail(writer, mail):
    mail.select('BRMS')

    kind, data = mail.search(None, 'ALL')
    mail_ids = data[0]
    id_list = mail_ids.split()
    first_email_id = int(id_list[0])
    latest_email_id = int(id_list[-1])

    for i in range(latest_email_id, first_email_id, -1):
        typ, data = mail.fetch(i, '(RFC822)')

        for response_part in data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                for part in msg.walk():
                    if part.get_content_type() == 'text/html':
                        content = part.get_payload()
                        manage_email_content(content, writer)

    return 0

def manage_email_content(content, writer):
    content = content.split('\n')
    for i, line in enumerate(content):
        if 'Alert description' in line:
            line = line.split()
            datum['Event code'] = line[-1][4:]
            if line[-1][:3] in translate:
                datum['Motor block num'] = translate[line[-1][:3]]
            else:
                datum['Motor block num'] = 'Defecto ajeno al bloque motor'
        elif 'Alert condition' in line:
            line = line.split()
            datum['Code description'] = ' '.join(line[4:])
        elif 'Unit id' in line:
            line = line.split()
            datum['Train num'] = line[3][3:]
        elif 'Alert raised' in line:
            line = line.split()
            datum['Date'] = line[4][:10]
            datum['Time'] = line[4][11:]
    writer.writerow(datum)
    print datum
    return 0

def move_to_trash_before_date(mail, folder, days_before):
    # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
    no_of_msgs = int(mail.select(folder)[1][0])
    print("- Found a total of {1} messages in '{0}'.".format(folder, no_of_msgs))

    before_date = (datetime.date.today() - datetime.timedelta(days_before)).strftime("%d-%b-%Y")
    typ, data = mail.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

    if data != ['']:  # if not empty list means messages exist
        no_msgs_del = data[0].split()[-1]  # last msg id in the list
        print("- Marked {0} messages for removal with dates before {1} in '{2}'.".format(no_msgs_del, before_date, folder))
        mail.store("1:{0}".format(no_msgs_del), '+X-GM-LABELS', '\\Trash')  # move to trash
        empty_folder(mail, 'Elementos eliminados', do_expunge=True)  # can send do_expunge=False, default True
    else:
        print("- Nothing to remove.")

    return 0

def empty_folder(mail, folder, do_expunge=True):
    mail.select(folder)  # select all trash
    mail.store("1:*", '+FLAGS', '\\Deleted')  # Flag all Trash as Deleted
    if do_expunge:  # See Gmail Settings -> Forwarding and POP/IMAP -> Auto-Expunge
        mail.expunge()  # not need if auto-expunge enabled
    else:
        print("Expunge was skipped.")
    return 0

def disconnect_imap(mail):
    mail.close()
    mail.logout()
    return 0

def main():
    with open('email_data.csv', 'w') as f:
        writer = csv.DictWriter(f, fieldnames=['Time', 'Date', 'Train num', 'Motor block num',
                                               'Event code', 'Code description'], delimiter=';')
        try:
            m = connect_imap()
            writer.writeheader()
            read_email_from_gmail(writer, m)
            move_to_trash_before_date(m, 'BRMS', 15)  # inbox cleanup, before 15 days
            disconnect_imap(m)

        except Exception, e:
            print str(e)

if __name__ == "__main__":
    main()

event_management file connects to an Outlook email folder, reads the emails and builds a CSV file with data extracted from the the emails' contents. This file works properly, it is already tested; and it works fine when executed manually (not using Cron). So I not sure it is related to the sSMTP issue appearing in the system log.
I will apreciate every kind of help or suggestions!
Comment: Does your python script tries to send email ? Maybe you can post the content of event_management.py
Comment: @CCH I have edited the question adding the ```event_management``` code. This script goes into an email account and retrieves data from the emails there. But as I have alredy stated in the question, the script works well when manually executed so I am not sure if the system log ```sSMTP``` is related.
Comment: Is the $PATH you defined in crontab the same as you have when you type `echo $PATH` with your user ? I don't have enough expertise with python on this case but it looks a lot like a $PATH definition problem within cron.
Comment: Yes, it is exactly the same...
Answer: After some test and reading other users' answers, I have found the problem. It is a combination of two different issues that are not directly related, but together made this problem a pain in the ass to debug.

First Problem:
log.log file contains logs and errors from three different executables, hence I did not notice that evet_management file did not have the correct permissions. I did not apply chmod command well, and I have not notice it as it contained a lot of data.
Conclussion 1: One cronjob, one log file.
Conclussion 2: /var/log/syslog contains a lot of data, from various resources, hence it may confuse you when trying to debug. Better to produce log files apart.

Second Problem:
I have two Python distributions installed in my machine. When I execute manually the script, one is used. When Cron executes the script the other one is used. Furthermore I noticed it when first problem was fixed. I got an error of module not found when running the Python script by Cron in the log file, but perfectly worked when manually executed. Hence I have seen that when using pip install <module-name>, it is just for one distro. To check wich version of Python I was using:
which Python

Conclussion: Be smart, don't be like me, don't mess with multiple Python distributions.

Bonus: Always use full paths to be clear. Cron has different env than yours.

Python script not executed from Cron


Linear regression with slope constraint

Question: I want to perform a very simple linear regression in R. The formula is as simple as $y = ax + b$. However I would like the slope ($a$) to be inside an interval, let's say, between 1.4 and 1.6.
How can this be done?
Answer:
I want to perform ... linear regression in R. ... I would like the slope to be inside an interval, let's say, between 1.4 and 1.6. How can this be done?

(i) Simple way:

fit the regression. If it's in the bounds, you're done.

If it's not in the bounds, set the slope to the nearest bound, and

estimate the intercept as the average of $(y - ax)$ over all observations.

(ii) More complex way: do least squares with box constraints on the slope; many optimizaton routines implement box constraints, e.g. nlminb (which comes with R) does.
Edit: actually (as mentioned in the example below), in vanilla R, nls can do box constraints; as shown in the example, that's really very easy to do.
You can use constrained regression more directly; I think the pcls function from the package "mgcv" and the nnls function from the package "nnls" both do.
--
Edit to answer followup question -
I was going to show you how to use it with nlminb since that comes with R, but I realized that nls already uses the same routines (the PORT routines) to implement constrained least squares, so my example below does that case.
NB: in my example below, $a$ is the intercept and $b$ is the slope (the more common convention in stats). I realized after I put it in here that you started the other way around; I'm going to leave the example 'backward' relative to your question, though.
First, set up some data with the 'true' slope inside the range:
 set.seed(seed=439812L)
 x=runif(35,10,30)
 y = 5.8 + 1.53*x + rnorm(35,s=5)  # population slope is in range
 plot(x,y)
 lm(y~x)

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x
     12.681        1.217

... but LS estimate is well outside it, just caused by random variation. So lets use the constrained regression in nls:
 nls(y~a+b*x,algorithm="port",
   start=c(a=0,b=1.5),lower=c(a=-Inf,b=1.4),upper=c(a=Inf,b=1.6))

Nonlinear regression model
  model: y ~ a + b * x
   data: parent.frame()
    a     b
9.019 1.400
 residual sum-of-squares: 706.2

Algorithm "port", convergence message: both X-convergence and relative convergence (5)

As you see, you get a slope right on the boundary. If you pass the fitted model to summary it will even produce standard errors and t-values but I am not sure how meaningful/interpretable these are.
So how does my suggestion (1) compare? (i.e. since the unconstrained solution violates the bound, set the slope to the nearest bound and average the residuals $y-bx$ to estimate the intercept)
 b=1.4
 c(a=mean(y-x*b),b=b)
       a        b
9.019376 1.400000

It's the same estimate ...
In the plot below, the blue line is least squares and the red line is the constrained least squares:
Comment: +1 Finding confidence intervals on the parameter estimates is going to be a challenge in any event.
Comment: Thank you for this answer but... could you give an example using any of these functions?
Comment: @IñigoHernáezCorres see the update to my answer, where I illustrate using `nls` to do it.
Comment: +1 great answer with connections on two ways of doing it!
Answer: Glen_b's second method, using least squares with a box constraint can be more easily implemented via ridge regression.  The solution to ridge regression can be viewed as the Lagrangian for a regression with a bound on the magnitude of the norm of the weight vector (and hence its slope).  So following whuber's suggestion below, the approach would be to subtract a trend of (1.6+1.4)/2 = 1.5 and then apply ridge regression and gradually increase the ridge parameter until the magnitude of the slope is less than or equal to 0.1.
The benefit of this approach is that no fancy optimisation tools are required, just ridge regresson, which is already available in R (and many other packages).
However Glen_b's simple solution (i) seems sensible to me (+1)
Comment: This is clever, but are you sure it will work as described? It seems to me the appropriate approach would be to remove a trend of (1.6+1.4)/2 = 1.5 and then control the ridge parameter until the *absolute value* of the slope is less than or equal to 0.1.
Comment: yes, that is indeed a better suggestion.  The ridge regression approach is really more appropriate if the restriction is on the magnitude of the slope, it sounds like a pretty odd problem!  My answer was originally inspired by Glen_b's comment on box constraints, ridge regression is basically just an easier way to implement the box constraints.
Comment: Although I appreciate your acknowledgment of my comments, imho it distracts from the content of your answer.  We're all in this together to improve our work wherever we can, so it's enough acknowledgment that you acted on my suggestions.  For that *you* deserve the increment in reputation.  If you are moved to make additional edits, please consider streamlining the text by removing that superfluous material.
Comment: Superfluous material edited, however I enjoy collaborations and always seek to give collaborators the credit they deserve, and still think morally you deserve half the up-votes. ;o)
Answer: Another approach would be to use Bayesian methods to fit the regression and choose a prior distribution on $a$ that only has support in the region you want, e.g. a uniform from 1.4 to 1.6, or a beta distribution shifted and scaled to that domain.
There are many examples on the web and in software of using Bayesian methods for regression, you can just follow one of those examples and change the prior on $a$.
This result will still give credible intervals of the parameters of interest (of course the meaningfulness of these intervals will be based on the reasonableness of your prior information about the slope).
Comment: +1, this was my first thought as well. I like the other suggestions, but this seems the best to me.
Answer: Another approach might be to reformulate your regression as an optimization problem and use an optimizer. I'm not sure if it can be reformulated this way, but I thought of this question when I read this blog posting on R optimizers:
http://zoonek.free.fr/blosxom/R/2012-06-01_Optimization.html

Linear regression with slope constraint


What should replace deprecated Facebook adView setAdListener to get callbacks?

Question: As of v5.6.0 the adView.setAdListener is deprecated. How can we receive onAdLoaded and onError callbacks now?
Answer: Solution: Since 5.6, you should use loadAd(AdView.AdViewLoadConfig loadAdConfig)

public void loadAd(AdView.AdViewLoadConfig loadAdConfig)

Loads an ad.
This method always returns immediately. The ad is loaded
  asynchronously. The control's ad listener will be called when loading
  finishes or fails.

Java
AdView adView = new AdView(this, "placementId", new AdSize(width, height));

AdListener adListener = new AdListener() {
    @Override
    public void onError(Ad ad, AdError adError) {

    }

    @Override
    public void onAdLoaded(Ad ad) {

    }

    @Override
    public void onAdClicked(Ad ad) {

    }

    @Override
    public void onLoggingImpression(Ad ad) {

    }
};

AdView.AdViewLoadConfig loadAdConfig = adView.buildLoadAdConfig()
        .withAdListener(adListener)
        .build();

adView.loadAd(loadAdConfig);

Kotlin
val adView = AdView(this, "placementId", AdSize(width, height))

val adListener = object : AdListener {
    override fun onError(ad: Ad, adError: AdError) {

    }

    override fun onAdLoaded(ad: Ad) {

    }

    override fun onAdClicked(ad: Ad) {

    }

    override fun onLoggingImpression(ad: Ad) {

    }
}

val loadAdConfig = adView.buildLoadAdConfig()
    .withAdListener(adListener)
    .build()

adView.loadAd(loadAdConfig)

Find more information here.
Answer: Banner Ad Code: To resolve Issue of setAdListener Method deprecated
Replace your setAdlistener() method For Banner Ad Using below code:
 AdView adView = new AdView(context, context.getString(R.string.str_facebook_banner), AdSize.BANNER_HEIGHT_90);

    AdListener adListener = new AdListener() {
        @Override
        public void onError(Ad ad, AdError adError) {
            Log.e(TAG, "Fb failed :: " + adError.toString());
        }

        @Override
        public void onAdLoaded(Ad ad) {
            Log.e(TAG, "onAdLoaded: ");

        }

        @Override
        public void onAdClicked(Ad ad) {

        }

        @Override
        public void onLoggingImpression(Ad ad) {

        }
    };

    AdView.AdViewLoadConfig loadAdConfig = adView.buildLoadAdConfig()
            .withAdListener(adListener)
            .build();
    adView.loadAd(loadAdConfig);

Interstitial Ad Code: To resolve Issue of setAdListener Method deprecated
You can use below code to replace setAdListener() method for Interstitial Ad:
    InterstitialAd  interstitialAd = new InterstitialAd(context, context.getString(R.string.str_facebook_interstitial));

    InterstitialAdListener interstitialAdListener = new InterstitialAdListener() {
        @Override
        public void onInterstitialDisplayed(Ad ad) {

        }

        @Override
        public void onInterstitialDismissed(Ad ad) {

        }

        @Override
        public void onError(Ad ad, AdError adError) {
            Log.e(TAG, "Fb failed :: " + adError.toString());
        }

        @Override
        public void onAdLoaded(Ad ad) {
            Log.e(TAG, "onAdLoaded: ");
            interstitialAd.show();
        }

        @Override
        public void onAdClicked(Ad ad) {

        }

        @Override
        public void onLoggingImpression(Ad ad) {

        }
    };

    interstitialAd.loadAd(interstitialAd.buildLoadAdConfig()
            .withAdListener(interstitialAdListener)
            .withCacheFlags(ALL)
            .build());
}

Official Reference Link: https://developers.facebook.com/docs/audience-network/changelog-android#5_6_0
Answer: Your class should implement AdListener.
Refer this link for delailed explanation.
https://developers.facebook.com/docs/audience-network/reference/android/com/facebook/ads/adlistener.html/
Answer: val interstitialAdFb = com.facebook.ads.InterstitialAd(this, resources.getString(R.string.fb_interstitial_id))
    val adListener = object : com.facebook.ads.InterstitialAdListener {
        override fun onLoggingImpression(p0: Ad?) {
            TODO("Not yet implemented")
        }
        override fun onInterstitialDisplayed(p0: Ad?) {
            TODO("Not yet implemented")
        }
        override fun onAdClicked(p0: Ad?) {
            TODO("Not yet implemented")
        }
        override fun onInterstitialDismissed(p0: Ad?) {

        }

        override fun onError(p0: Ad?, p1: AdError?) {

        }

        override fun onAdLoaded(p0: Ad?) {

        }
    }

    val loadAdConfig = interstitialAdFb.buildLoadAdConfig()
            .withAdListener(adListener)
            .build()

    interstitialAdFb.loadAd(loadAdConfig)

    //and when you want to show ad
    if (interstitialAdFb.isAdLoaded)
        interstitialAdFb.show()

Answer: Follow the latest guide updated from here:
https://developers.facebook.com/docs/audience-network/support/troubleshoot/integration
For eg:
NativeAdListener nativeAdListener = new NativeAdListener() {
        @Override
        public void onMediaDownloaded(Ad ad) {
            // Native ad finished downloading all assets
            Log.e(TAG, "Native ad finished downloading all assets.");
        }

        @Override
        public void onError(Ad ad, AdError adError) {
        // Native ad failed to load
            Log.e(TAG, "Native ad failed to load: " + adError.getErrorMessage());
        }

        @Override
        public void onAdLoaded(Ad ad) {
            // Native ad is loaded and ready to be displayed
            Log.d(TAG, "Native ad is loaded and ready to be displayed!");
        }

        @Override
        public void onAdClicked(Ad ad) {
            // Native ad clicked
            Log.d(TAG, "Native ad clicked!");
        }

        @Override
        public void onLoggingImpression(Ad ad) {
            // Native ad impression
            Log.d(TAG, "Native ad impression logged!");
        }
    };

    // Request an ad
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withAdListener(nativeAdListener)
                    .build());


22762 rows in my session table. What does this mean for the site, and what should I do about it?

Question: Ok so the title is pretty self explanatory. There's thousands of rows in the session table. I see that the Persistent Login module is enabled. I don't know if this affects how the sessions are stored. Also, I note that 100+ users are quoted as being visitors at any one time, which seems very excessive for the user base and niche content of this site.
Please can someone advise the best course of action here? I assume I can truncate this table locally, but what's the long term action plan look like?
Comment: Do you have cron running?
Comment: Cron was not running, because of a code problem in a contrib module. Very annoying. Fixed. Ran cron, but the sessions table was still very large. Can only assume the session time is enormous and needs changing in the settings.php.
Comment: Persistent login module requests that session lifetime be set to 0, but it is of course 200000. What I don't know is whether to alter this or remove the module completely, or indeed how this module affects site speed or stored sessions - would it work in parallel with the http://drupal.org/project/no_anon module to additionally speed things up a bit for anon?
Comment: Have you profiled things and identified that you have a problem, or do you just think you have a problem because of your row count?  Databases store lots of data; that's their job.  Only start worrying about things when you have to.  If you have a high volume site, then optimize the web server (httpd and mysqld if that is what you are running) for normal behavior, then start worrying about things like sessions.
Comment: I was initially concerned about the sessions mostly because a) the site was running very slowly (this is almost certainly associated with a poorly spec'ed server, with only 1GB of RAM) and b) because admin_menu was reporting 100-150 guests online at one time, which is either incorrect (possibly due to persistent_login, I don't know) or causing a performance problem that could have been potentially associated with sessions - I'm reasonably ignorant on the effect of sessions in this regard, hence the initial question.
Comment: I am not disagreeing that sessions could be a contributing factor, and you have identified a potential problem, but unless you actually profile a system, any changes you make are guesses and just treat symptoms and not cure the problem.  Disable unneeded modules, then optimize php and httpd settings to match the traffic you see and reduce the memory footprint.  Optimize your mysqld for your traffic.  Then profile your system, and see where the weak points are.
Comment: Regarding the number of users that admin menu shows.  This is also something you can measure.  Look at the logs, see how the traffic matches up with these numbers, then try to match this up with the sessions table.  That will indicate whether you have a problem or now.
Answer: The long term action is to limit session lifetime.
Look for the following line in your settings.php:
ini_set('session.gc_maxlifetime',   200000);

This parameter sets session life time, after which session is marked as garbage and will be deleted by garbage collector.
Average session life time (not on drupal sites) is much less than 200000 seconds  - something between 15 minutes and half an hour (900-1800).
So, if you don't need long sessions, you can reduce ini_set value and thus get less sessions stored in the sessions table
Answer: Likely, the thousands of rows are caused by anonymous sessions.  Look at the sessions table, and see how many rows have uid==0 vs uid!=0
SELECT COUNT(sid)
FROM sessions
WHERE uid = 0

SELECT COUNT(sid)
FROM sessions
WHERE uid != 0

Drupal 6 creates sessions for anonymous users during bootstrap.
Pressflow 6 and Drupal 7 only create sessions when you actually save something to $_SESSION.
There is a module, No Anonymous Sessions, that does what the its name says, but it can break some features and non-core modules.
That said, I would only worry if you are seeing (and measuring) actual performance impacts.
As long as your cron is running, the table should not grow without bounds.  It you look at the table sizes, it is probably much smaller than the cache tables, search index, and watchdog tables.


Upload picture - Element is not currently visible

Question: I am trying to upload a picture to a site.
I am using Selenium 2.45.0 for this. The following code should upload a photo:
public void uploadPhoto(String filePath) {
    filePath = filePath.replace("\\", "/");
    WebElement fileInput = driver.findElement(By.xpath("//div[@class='qq-upload-button']/input[@type='file']"));
    fileInput.sendKeys(filePath);
}

I am using the following browser:
public WebDriver driver = new FirefoxDriver();
public JavascriptExecutor jse = (JavascriptExecutor)driver;

However, I get the following exception:
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Command duration or timeout: 66 milliseconds
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'PC', ip: '197.368.536.12', os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=38.0.1, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: fdfdf84b-4a99-4c47-bf88-b12518172011
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:89)
    at quotePictureCreator.util.SeleniumUtility.uploadPhoto(SeleniumUtility.java:62)
    at quotePictureCreator.main.RunApp.main(RunApp.java:50)
Caused by: org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'PC', ip: '192.168.56.1', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: driver.version: unknown
    at <anonymous class>.fxdriver.preconditions.visible(file:///C:/firstname.lastname@example.com/components/command-processor.js:9587)
    at <anonymous class>.DelayedCommand.prototype.checkPreconditions_(file:///C:/firstname.lastname@example.com/components/command-processor.js:12257)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///C:/firstname.lastname@example.com/components/command-processor.js:12274)
    at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///C:/firstname.lastname@example.com/components/command-processor.js:12279)
    at <anonymous class>.DelayedCommand.prototype.execute/<(file:///C:/firstname.lastname@example.com/components/command-processor.js:12221)

Any suggestion what I am doing wrong?
I appreciate your replies!
Comment: I am using ff 38.0.1. Could you post an example using my linked site? Thx in advance!
Comment: Which google chrome version are you recommending?
Answer: Downgrading firefox would help probably. Until now I used that with firefox 34 and chrome 43 works as expected. However, hidden file tag will not work with IE. See this and this


Laravel Mysql DB join 2 polymorphic parents

Question: I am trying to create a query that can handle joining multiple polymorphic parents.
$this->query->join('time_records AS time', function($join) use($taskTable, $projectTable) {
    $join->on('time.parent_id', '=', $taskTable . '.id', 'and')
        ->on('time.parent_type', '=', Task::class, 'and')
        ->on('time.parent_id', '=', $projectTable . '.id', 'or')
        ->on('time.parent_type', '=', Project::class, 'and');
});

This fails due to it not liking strings instead of column names. But I do feel this does not seem right anyway.
This is just one part of the overall report class. In this case there is 2 tables that the polymorphic table time_records needs to join to. but it needs to be 1 join basically. So all the time records that are joined are under the time name, so that the columns that are used all fall in line with the structure of the overall query.
I join many tables here, to create a kind of fake hierarchy.
categories.name as lev1, projects.name AS lev2, tasks.name AS lev3, time.time AS time
That is somewhat how I structure the select so a collection can then group the name and then groups the projects under it and down, ending up with a collection hierarchy that my application can read / understand.
All I am looking for is an end result where I can have a reference to the time_records table that contains data for the row based on if its the project or the task (so if its a project then lev3 would just be null/blank). I don't mind if its not a join, or if it is even just a raw SQL query. I just cannot wrap my head around the proper way to end up with the result I am looking for while keeping it to 1 query (since the collection is taxing enough).
Answer: I figured out a way and its more a change of mindset.
Rather then basing the query on the order you want, just adjust the select. So if you want data from a table, add select arguments for them, if not "hide" the table in the results, but always have it joined.
This part I did not show in my question and I do see now it was fairly important in isolating why this was a difficult one to figure out.
Reverse the order, rather then going from the top level down, go from the bottom up, so start with time_records as the main table for the query and join all the rest, that way both tables that relate to it can be joined simpler.
So in the end the answer was that I was totally looking at this the wrong way. it helped to write out the raw SQL output to find this out and manually query.


amazon ecs Container for Configuration files

Question: at the moment I try to figure out a good setup for my application in amazon ecs.
My application needs a config file. Now I want to have a container to hold my config file so when I want to change something I don't need to redeploy my application.
I can't find any best practice method for this. What I found out is that the ecs tasks just make a docker run and you can't make a docker create.
Does anyone have an idea how I can manage my config files for my applications?
Answer: Most likely using Docker for this is overkill. How complex is the data? If it's simple key-value pairs I would use DynamoDB and get rid of the file completely. Another option would be using EFS for the file, or attaching/detaching an EBS volume.
Answer: You should not do that, it makes it fragile and you're not guaranteed to be able to access it from all containers across a cluster (or you end up having that on all instances which wastes resources). Why not package it up with the container as-is or package it as much as possible and provide environment variables to fill in the gap? If you really want to go this route I highly suggest something like S3


performance comparison in day wise group by in MySQL

Question: Let's consider the following table.
Table:
ID
epoch_time_in_millis
counter

Query #1:
SELECT
DATE_FORMAT(FROM_UNIXTIME(epoch_time_in_millis/1000),"%Y-%m-%d") date,
SUM(counter) totalCount
FROM my_table
GROUP BY date

Query #2:
SELECT
(epoch_time_in_millis DIV 86400000 ) * 86400000 ms,
SUM(counter) totalCount
FROM my_table
GROUP BY (epoch_time_in_millis DIV 86400000) * 86400000;

My question is:
Will the above two queries show any performance difference?
If yes please let me understand why.
If no let me understand why. :p
Thanks in advance.
Answer: The best way to check performance is on your hardware using your data.
But, MySQL implements group by using a file sort algorithm.  This algorithm does not generally take advantage of indexes, and especially not in your case.  Hence, the work for the two queries is going to be in processing the aggregation.
The other operations are trivial.  So, whether the engine does the calculation once or twice really isn't going to be relevant for the overall computation -- unless you have just a handful of rows.  And, in that case, performance isn't really an issue.
Comment: Thanks for the answer. Let's consider there are millions of rows in the table. Still the above two queries won't differ in performance? Since the second query involves multiplication and division operation I guessed that the two actually differ in the long run. Would you please clarify that? @GordonLinoff
Comment: @AnonymousOne . . . In general, the overhead for fetching and managing records in tertiary storage is much larger than a few arithmetic operations per query.  There are definitely cases where this is not the case (say, for user-defined functions or for functions on very long strings), but something of this nature is generally an over-optimization.
Comment: I've run these two queries separately on the same data set (~100K rows). The query #2 always outperforms query #1 on 10000 consecutive runs. The run time the query #1 takes is always > 2.5 times greater than the query #2 takes.
Comment: @AnonymousOne . . . In your environment, the date functions seem to be quite expensive.
Comment: [**Here**](http://pastebin.ubuntu.com/16503371/) you will find my server configuration. This is the server where I've run the experiment.


One Click Browse the Web For Windows Server

Question: What is the shortest possible path to make IE 8 in Windows Server 2008 let me browse web sites without asking me confirmation for every other thing I do (Other then installing a different browser)?
Answer: Select the root of the Service Manager navigation pane, and under the Server Summary click Configure IE ESC, which is part of the Security Information section. A dialog box appears, letting Internet Explorer Enhanced Security Configuration be enabled/disable separately for normal users and administrators.
Disabling the Enhanced Security Configuration will allow you to browse without being prompted.


How to call write() on a class?

Question: I have a set of python classes that represent network data structures (and are also used for disk storage). I'd like to be able to call write() on the class and get its standard binary representation.
The classes can struct.pack themselves into a binary representation via a pack() method. I can overwrite the __bytes__ method to call self.pack() so that write(bytes(myobject)) will work, but not write (myobject):
TypeError: a bytes-like object is required, not 'MyClassName'

Is there something I can override to make write() work without the explicit bytes() cast? Possibly my class would have to be a subclass of Bytes but ... I presume I'd still have to hook up the pack() method call somehow?
Comment: What's so bad about calling `bytes`? This seems like the best solution. Explicit is better than implicit. Now, what `write` is really expecting is an object that supports the buffer protocol. Unfortunately, I believe you have to write a C-extension to support this in your custom class.
Comment: Maybe you could wrap the stream and adapt it to call bytes first.
Comment: Are you just trying to save classes/objects to disk? Would pickle (https://docs.python.org/3/library/pickle.html) work for you?
Comment: Consider: https://jakevdp.github.io/blog/2014/05/05/introduction-to-the-python-buffer-protocol/
Comment: Can't use pickle - it needs to match a predefined on disk format.
I looked at the buffer code, seems staggeringly complex for a very simple problem - I just have an OrderedDict of (name, typename) pairs that match a C struct. Adding new ones as a derived class of my base PackedStruct type this way is trivial, just write out the struct as an OrderedDict.
Answer: You can make the class a subclass of bytearray and make any methods that can alter the object's value update the bytearray's value via the __setitem__ method (that is, using square brackets):
class MyClassName(bytearray):
    def update(self):
        ''' a method that makes certain alterations to the object's value '''
        self[:] = self.pack()

Comment: yes, I skipped over the `self[:] = self.pack()`, but I still think that the major downside here is that `MyClass` shouldn't subclass `bytearray` unless it *is* a bytearray of sorts.
Comment: You *could* do this, but that's probably not a good idea. Unless it makes sense for `MyClass` to *be* a bytearray. I'm not sure that this would work anyway, because what the `write` method is expecting is an object that supports the buffer protocol
Comment: By subclassing `bytearray` this class will certainly support the buffer protocol so it would work as the OP intends it to. The main downside to this approach is that it may be wasteful/inefficient to have potentially multiple calls to methods that update the `bytearray` value for several times before a `write` is actually called on this object. Ideally the `pack` method should be called only when a `write` is actually called.
Comment: Thanks, I'll try this and update when I find out. It is a bytearray of sorts, it's a fixed data format structure that matches a packed C struct either on disk or network to allow Python to store data efficiently and intercommunicate with the main C code.

How to call write() on a class?


How is the cha-cha counted?

Question: I'm trying to understand the cha-cha, specifically to play and write music with that rhythm. In my research, I've come across two ways "the cha-cha" is taught: as a dance and as a musical rhythm.
I'm confused because it seems like the dancers count/say "one two cha-cha-cha - one two cha-cha-cha", etc. But it seems like the percussionists are counting and playing more like "one two three four-and-one two three four-and-one", etc.
I haven't found anything online yet that tries to match up the dancing and music to show how it lines up, so I'm hoping someone here has experience with the cha-cha along with dancers. I've tried watching dance videos with music but things tend to go by really fast.
The two possibilities I've thought of are either the dancers and musicians put the "one" in a different place (i.e., when dancers say "one", musicians are saying "two"), or the dance goes "cha-cha-cha" and the music goes "dum-dum-dum" at different times (i.e., the last "cha" is at the same time as the first "dum"), or I'm totally wrong and the counting actually lines up and I've misunderstood something basic.
So how does the dancer style of counting the cha-cha line up with the musician style of counting it?
Answer: The short: The count/the placement of the 1 should be exactly the same for dancers and musicians. Having been both a competitive dancer and a musician, it saddens me to see people saying otherwise.
The long: I danced competitively for years, and also made a living by teaching Ballroom for a little while. I think the things you're seeing online are a result of teaching techniques that are used for introductory dancers. Often this is also an introduction to counting music.
I'd like to address some items mentioned in other answers:

The final danced cha is not always on the first beat of a bar. This leads to...
Not all steps are counted 2, 3, cha cha cha. Some figures will also have dancers stepping with cha cha cha on 2 & 3.
I imagine the mention of a prep step to the side was with the Closed Basic Movement in mind. A dancer does not need to begin with this step, and there are many cases in which the side prep step won't be used.
The dancing does not need to begin on a 1. A dancer taking their first step does not mean they are counting it with a 1. In fact, if you watch a collegiate competition at the Ohio Star Ball, you'll see many couples begin with a chasse on 4.

We used to introduce students to Cha Cha by counting chasse steps cha cha cha because people tend to pick up on it a little faster that way. When you start dancing more advanced figures, you'll end up with multiple chasse steps in a row. That's why in advanced dancing, you will almost never hear someone count with cha cha cha. It's too easy to lose your place in the music that way.
You can use the book Latin American Cha Cha Cha, written by the Imperial Society of Teachers of Dancing (I'm holding a 2003 copy), to reference any figures I have mentioned. On page 101 you will see part of the count for Cuban Breaks spelled out as 2&3, 4&1 et cetera. I won't even get into Guapacha variation of timing. My point is that as a musician, you have no way to know what timing a dancer is going to use over your music. Cha Cha music does not need to have a 4&1 or 2&3 emphasis*. In fact, I would argue that comfortable Cha Cha dancers almost never dance over musical syncopation that coincides with their chasse (or other alternate timing) steps. They will count the same beat as you, but their syncopation may be different. The Dance Examinations Board does specify Cha Cha music should have a musical accent on the first beat, and a percussive accent on the fourth beat of each bar.
Disclaimer: I have a stronger background in the International style, but have taught both International and American styles of Cha Cha. I am under the impression that the American style evolved from the International style. The method of counting the styles is the same, although the tempo for the American style has historically been a little slower. As always, be careful what you learn from the Internet. That goes for this site as well (my posts included).
Edit: That's not to say that a good/popular Cha Cha won't have emphasis on the & between 4 and 1. You'll likely hear dancers say that they prefer not only the emphasis that ISTD dictates (4, 1) but also between (&). Again, this doesn't mean you should be predicting their competitive routines - they will syncopate as they see fit and you don't need to dictate when they step. If you're writing music for night club Cha Cha, however, I'll have to defer to DanceLifeLaw. Just keep in mind that many of the videos you find online will be for competitive or formal (Arthur Murray/Fred Astaire) Cha Cha in the International Latin or American Rhythm styles.
Answer: For ballroom dancers (either Rhythm in the US or Latin in International styles) the steps are counted: two, three, cha-cha-CHA where the last CHA is on the downbeat. Much of the rhythm is sounded by the guiro. The guiro plays either
4-4-4-88 (where 4 means quarter note and 8 means eighth note, I can't quickly figure out how to post an image or pdf) or 4-88-4-88. The last 88 in a measure is cha-cha, the first quarter is an accented CHA, the second and third quarter notes are two, three.
Also, there is a first step to the side on beat one (called a preparatory step) counted ONE, then the cycle of (two, three, cha, cha, CHA) continues.
The same pattern exists in International Rhumba (or did until last year; I don't know if the slow down from 112 beats/minute to 90/beats/minute calls for different counts) and in US competition mambo (but here the 2-3 are quick and the cha-cha-cha are collapsed to subsume beats 4 and 1 of two successive measures.) Salsa is often counted started on one as the tempo is quite fast (144 or more beats/minute) and the beats are not as strongly marked as in cha-cha-cha.
I think that some Country Cha Cha styles start on beat one which makes the main step com on four.
It has been popular over the last few years to put a bass drum one-two-three-four behind everything. A cha-cha-cha being danced to one of these (Boom-Boom-Cha-Cha for example) still goes two, three, cha-cha, CHA.
Comment: Ok weird. I know when I looked into this a few months ago I found all kinds of dance related sources saying "one two cha-cha-cha", but now I can't find any. Either I'm insane or the whole internet has pranked me.
Answer: first time poster here, so apologies if I mess up any formalities.
As a former competitive latin dancer, I will try to explain this in dancer terms, then put my pianist hat on and try to get the musician's perspective.
There are 3 versions of cha cha that I have danced: international latin, rhythm, and night club. Latin and rhythm have been thoroughly addressed by aeroNotAuto, and I agree with him 100%: the base beat is 4&1, 2, 3. Musically that comes out to something along the lines of half note, half note, whole note x3.  The 4&1 are often counted as cha cha cha only because it is easier to say at speed than 4&1.
In nightclubs, an alternate beat is often used: 1, 2, 3&4. This is not the beat used for competitive dancing, but is often enjoyed in latin clubs along with salsa, merengue, bachata. As before the beat is counted 1, 2, cha cha cha. and the musical notes are converted accordingly.
The reason your research is varied is likely due to the different uses for a cha cha beat. Neither is wrong or right, and you should use the appropriate format based on your ideal audience and purpose. Furthermore, all of this is for the base beat, often the music will have its own natural synchopations and changes based on the song itself.
tldr;
latin and rhythm competition dancing: 4&1, 2, 3. 1 is the first beat of the measure.
Nightclubs: 1, 2, 3&4 is the count, music and measures will change based on song. As is often the case, nightclubs are less picky about beat and more interested in the feel of the song... competitions the exact opposite.
Cheers!
Answer: "one two cha-cha-cha" used by dancers is indeed musically misleading as the "one" for dancers is not the one in terms of musical measures. The 3rd "cha" is actually the first beat of the following bar:
1---------2---------3---------4--------|1---------2----...
      ...one-------two-------cha--cha--cha-------

Try to clap your hand on the 1 (beat of the measure) as you say "one two cha-cha-cha":
1---------2---------3---------4--------|1---------2----...
      ...one-------two-------cha--cha--cha-------
CLAP                                   CLAP

I think you'll immediatly feel the flow of the ryhtm in a much more intuitive way (as you say, musically you can count it "one two three four-and-one", "four-and-one" com on top of "cha-cha-cha").
Comment: Yep, that's it. It's rather difficult to find an example where both music and dance steps are perceptible in the most clear way, this one here https://youtu.be/QisK7N-75lU?t=546 is the best I could find. If you look and hear attemptively I think you can perceive that the down beat comes at the third of the three quick steps, in fact that's where the musical excerpt and dance end (clearly in a down beat).
Comment: This was my thought after looking at several different sources but when I discussed it with a friend who has a dance background she thought I was wrong. Just so I'm 100% clear, the numerical "1 2..." on the top row is the actual beat numbers that musicians would count, and the spelled out "one two..." on the bottom row is how the dancers are counting it, right?
Answer: If you look at sheet music published by a reputable source, it is clear the final "cha" is on the first beat of the bar.
For example, in the Trinity College London piano exam syllabus:

There are also published examples in the ABRSM (London Royal Schools of Music) examimations.
I have no idea why dancers count it they way the OP claims they do - but from (bitter) practical experience I wouldn't give much weight to their evidence about anything to do with rhythm.
Answer: I'm a dance Instructor and musician they don't understand each other... Lol it all starts on one ... Chacha breaks on 23 done properly but dancing isn't a science it's an art it was built upon mistakes and each town has its own flavor... You can 2 step 2 different ways in the same town on the same night ... It's subjective but 4 and 1 is the proper...
Answer: This just about sums it up. ___
Comment: And yet somehow doesn't give me any greater understanding. Are you saying I'm wrong about how musicians seem to be counting the cha-cha?
Comment: You just asked me my actual question in your last comment.
Comment: Well, the dance instructers on this video actually do it (musically) correctly, they say, very clearly, "cha-cha-one () two () three", not "one () two () cha-cha-cha". Their "one" is really the downbeat/1st beat of the bar.
Comment: I think so, yes.  I can't see any other way to count it.  It's a pretty solid 4-on-the-floor sort of groove.
Comment: And you totally disagree with joseem's answer then? Perhaps not all musicians count the cha-cha the same way? Have I opened a huge can of worms? Also, I thought "four on the floor" meant each quarter note (crotchet) has a kick drum hit on it, which doesn't seem to be the case for any of the cha-cha rhythms I've seen online.
Comment: Here's a demonstration (skip to the end when they finally turn the music on) that uses "One two three cha-cha".  But dance "one" is still in the same place as musical "one".
https://www.youtube.com/watch?v=PWiLi22Cq8w
Comment: That is exactly one of the videos that I saw that started off my confusion. All dancers seem to count it the same way. All **musicians** seem to count it a different way. If you look on YouTube for videos posted by drummers on how to play a cha-cha rhythm, you'll probably understand why I'm asking the question pretty quickly.
Comment: But "one" is in the same place though?
Comment: Maybe I saw a different video by those same people or I missed that when watching it. I definitely recognize those people. I can't easily re-watch the video now because I'm at work.

How is the cha-cha counted?


How do I create a .txt file from a pandas dataframe?

Question: I have a dataframe in my jupyter notebook, which follows the below format for ~1500 rows:
BUSINESS    CUSTOMER_ID     RISK_RATING
PVB          1000033280         HR
SLA          1000064680         LR

I want to output this df as a .txt file, similar to how I have used df.to_csv.
I have tried this code:
np.savetxt(r'Y:\FILEPATH\df.txt', df.values, fmt='%d', delimiter='\t')
But I am currently getting this error message:
TypeError: Mismatch between array dtype ('object') and format specifier ('%d   %d  %d  %d  %d  %d  %d  %d')
I also want to make sure the column headers ("BUSINESS", "CUSTOMER_ID" & "RISK_RATING") are included in the .txt file.
Any help would be much appreciated thank you.
Answer: You can use df.to_csv and just give a .txt name to your file. See below:
df.to_csv('filename.txt')


How to handle or impute large number of missing values?

Question: I am trying to use this dataset to build a predictive model.
The hubway.db file contains 3 tables. One of which is is bike_trips which has ~1 million entries. Some of my variables have high number of missing values:
zip_code:  340,438
birth_date:  697,931
gender:  340,372
Moreover these variables are fundamentally different. Gender can take 1 of 2 values but birthdate cannot, same with zip codes.
The 2 other tables contain bike_station and weather data. The end goal is to find underlying patterns and ultimately build a model to predict trip duration and final destination (from a given starting station). However I first need to clean the data, hence my issue.
How am I supposed to either impute or generally deal with this?
Comment: It depends on what you're trying to do with the dataset.  "Working" is too vague to justify any answer at all.  It also depends on why those variables are missing and what their pattern of missingness is.  Could you edit your post to supply this additional information?
Comment: to echo @whuber, depends on your project. A first step would be a check if the data is missing at random (MAR), if this is the case then you can use any of the popular data imputation algorithms (AMELIA and missforest are my personal favorites)
Answer: It depends on the data set.
Imputation using K-NN, Multivariate imputation by Chained equation, Stochastic regression, hot deck imputation, Extrapolation and Interpolation, Mean mode imputation, Probability likelyhood, many other techniques and based on our problem we need to choose.


Abri um Form dentro de um Panel

Question: Vendo uma Pergunta aqui no Stackoverflw onde uma das resposta era para abrir o Form dentro de um Tpanel.
É possível abr um Form dentro de um Tpanel? E se positivo como se faz para abri um Form Dentro de um Tpanel?
Answer: Sim podes. Basta indicares que o parent do teu Form é o painel que desejas. Algo como
//Criar nova instancia do form e mostrar num painel
f:=TFrmMeuForm.Create();
f.BorderStyle:=bsNone;
f.Align:=alClient;
f.Parent:=MeuPainel;
f.Visible:=true;

Comment: TFrmMeuForm.Create(); não vai gerar um erro de criação?
Comment: Que bacana, vou fazer testes com isso.
É bem simples...
Comment: Era um exemplo de um form meu que tem um construtor assim.. tipicamente leva o Owner como parametro de entrada, é isso que se refere?
Comment: Na verdade ele obrigatoriamente precisa de um Owner, seja existe (criado) ou não. Isso vem da Classe `TForm`.
Answer: Também pode utilizar este formato:
var
  vForm : TForm;
begin
  vForm        := TForm.Create(MeuPainel);
  vForm.Parent := MeuPainel;
  vForm.Left   := 0;
  vForm.Top    := 0;
  vForm.Height := MeuPainel.Height;
  vForm.Width  := MeuPainel.Width;
  vForm.Show;

Um diferencial é que existira a possibilidade de movimentar o Formulário (carregar ele na tela);
Ainda vale lembrar que precisa de um controle de Memória para isto.

Abri um Form dentro de um Panel


Proving $\lim_{n\to\infty} \frac{1}{n(n+1)}=0$

Question: I claim that the sequence $\{a_n\}_{n = 1}^{\infty}$ with $a_n = \dfrac{1}{n(n+1)}$ converges to $0$. Now using this definition of convergence of a sequence

A sequence $\{a_n\}$ converges to a limit $L$
  $$\lim_{n\to \infty} = L$$
  if, for any $\epsilon > 0$, there exists an $N$ such that $\mid a_n - L \mid < \epsilon$ for $n > N$

$$ \left\lvert \frac{1}{n(n+1)} \right\lvert < \epsilon $$
$$\frac{1}{n(n+1)} < \epsilon$$
$$n(n+1) > \frac{1}{\epsilon}$$
$$n^2 + n > \frac{1}{\epsilon}$$
I am not able to proceed further. How can I find an $N$ not in terms of $n$ that satisfies the definition? I tried dividing it into two cases: $\epsilon \ge 1$ and $\epsilon < 1$ but still couldn't solve it. Is my claim wrong (I don't think so) or am I not able to manipulate the inequality as needed?
Comment: You don't need the "smallest possible $N$". Just let $N > \frac{1}{\epsilon}$. Then $n^2 + n > n > N > \frac{1}{\epsilon}$.
Comment: @SteamyRoot is correct. The following might also be useful for you
in the future. If you know that $x_{n}\rightarrow x$ and $y_{n}\rightarrow y$, then $x_{n}y_{n}\rightarrow xy$. In this case, you could take $x_{n}=1/n$ and $y_{n}=1/(n+1)$, both of which you already know go to zero.
Answer: You are doing great!
You need to find an $N$ such $n^2+n>\frac{1}{\epsilon}$ for all $n>N$.
Just take $N>\frac{1}{\epsilon}$ (this is possible by the archimidean property.
Now, if $n>N$ we have:
$n^2+n>n>N>\frac{1}{\epsilon}$ as desired.
Answer: It would have been enough to say the following. Given $\epsilon > 0$, choose an integer $N > \frac{1}{\epsilon}$. For all $n > N$,
$$\left\lvert \frac{1}{n(n+1)} - 0\right\rvert = \frac{1}{n(n+1)} < \frac{1}{n} < \frac{1}{N} < \epsilon.$$


amp-img tag, replace to simple img

Question: I need to change this tag  to <amp-img>, I've been researching about this and I have this function for change the img tag.
function amptheme_image($variables) {
  // Remove RDF properties incompatible with AMP specification.
  if (isset($variables['attributes']['typeof'])) {
    unset($variables['attributes']['typeof']);
  }

  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      if (empty($attributes[$key])) {
        $attributes[$key] = $variables[$key];
      }
    }
  }

  return '<amp-img' . drupal_attributes($attributes) . '></amp-img>';
}

This function should change  to <amp-img> but it's not working.

I think it's maybe for the name of the function.
My theme's name is bartik, but the function example it's amptheme_image.
I just did tried like this bartiktheme_image, also bartik_theme_image, but it's the same error.
I also tried like this, theme_image, but boom error cause there's another function with the same name.
Thanks for the answers and suggestions.
Answer:
I think it's maybe for the name of the function. My theme's name is bartik, but the function example it's amptheme_image.

Without more info it's hard to be sure, but it sounds like you're adding this code to the core bartik.theme file? If so then yes, that's why it's not working. You need to create a subtheme, add your code to its .theme file, and then enable that theme on the front end.
The function must be named <themename>_image, so to use your existing code exactly as-is, you should make sure the machine name of your subtheme is amptheme.
Once you've done that and rebuilt the cache, your image elements should start using the override you've setup.
Comment: Yes, I'm adding the code to the core bartik.theme file.
I don't know if it's necessary a subtheme because this is only for a node (Machine name: ir_news).
Or there's a way to apply the Google AMP just for a content type using a sub theme without change the theme style. That's why I'm doing this with this code.
**Please, any help will be appreciated.**

amp-img tag, replace to simple img


Classes no JavaScript em uma aplicação com o Cordova

Question: Quando tento declarar uma classe no JavaScript, usando, por exemplo:
<code>class musica{
    contructor(){
      this.variavel = 3;
    }
    funcao(){
      console.log('essa é a minha variável: '+ this.variavel);
    }
}
</code>
Na minha aplicação tenho o seguinte erro:

Uncaught SyntaxError: unknown message reserved_word

Não é possível criar classes no JS usando o Cordova?
Answer: Cordova não suporta ES6, classes, da forma que você fez, só estão disponíveis a partir dele. Entenda que muitas tecnologias ainda são experimentais e não formam implementadas totalmente.
O Ionic com cordova usa classes, mas, na verdade, não é JavaScript e sim TypeScript que, no build é "compilado" (recodificado) para JavaScript.
Talvez você encontre alguns artigos por ai que falem que é possível usar ES6 no Cordova, mas, na verdade, estes artigos estão falando do projeto Babel:

http://babeljs.io

Que é um 'compilador' que transforma o seu script like ES6 em "ES5", ou seja, lhe permite usar ES6 antes de estar disponível.