How can I change the OverScroll color in Android 2.3.1?

Question: Since Android 2.3.1 there is a new feature for ScrollViews and Lists called OverScroll. With
android:overScrollMode="never"

I can turn it off, but if i don't wan't to turn it off how can I change the Color of it?
Comment: The graphics for this are overscroll_glow.png and overscroll_edge.png. If you find a way to manually specify different version's of these files you will be able to change the color and style of the overscroll. Unfortunately I haven't happened upon *how* to do this yet. Let me know if you do.
Answer: Afaik there is no way to do this. So I created one; presenting:
Graeme's Amazing Custom List View v2
I've created a custom view which performs overscroll for ListViews and for GridViews (XML example is for slightly more involved GridView but view works for both):
<CustomGlowListView     android:id="@+id/searches"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:background="@android:color/black"
                        android:layout_margin="10dp"
                        android:tag="GridView"
                        android:numColumns="3"
                        android:horizontalSpacing="8dp"
                        android:verticalSpacing="8dp">
</CustomGlowListView>

The CustomGlowListView looks like this:
public class CustomGlowListView extends RelativeLayout{

private ImageView underscrollEdge;
private ImageView underscrollGlow;
private ImageView overscrollGlow;
private ImageView overscrollEdge;
private AbsListView listView;

private final   static float    MAX_EDGE_SIZE   = 11f;
private final   static float    MAX_GLOW_SIZE   = 93f;
private         float   scrollDistanceSinceBoundary     = 0;

private Rect paddingRectangle = new Rect();

GestureDetector listViewGestureDetector;

// Gives the option of short circuiting the overscroll glow fade (Such as by scrolling away from the overscrolled edge)
boolean interruptFade = false;

public CustomGlowListView(Context context, AttributeSet attrs)
{
    super(context, attrs);

    listViewGestureDetector = new GestureDetector(new ListViewGestureDetector());

    if( getTag() == null ||
        getTag().toString().equalsIgnoreCase("ListView"))       {   listView = new ListView(context);   }
    else if(getTag().toString().equalsIgnoreCase("GridView"))
    {
        listView = new GridView(context, attrs);
        ((GridView)listView).getSelector().getPadding(paddingRectangle);
    }
    listView.setId(android.R.id.list);
    listView.setOverScrollMode(OVER_SCROLL_NEVER);
    addView(listView, new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    underscrollEdge = new ImageView(context);
    underscrollEdge.setImageResource(R.drawable.underscroll_edge);
    underscrollEdge.setScaleType(ScaleType.FIT_XY);
    underscrollGlow = new ImageView(context);
    underscrollGlow.setImageResource(R.drawable.underscroll_glow);
    underscrollGlow.setScaleType(ScaleType.FIT_XY);
    overscrollGlow = new ImageView(context);
    overscrollGlow.setImageResource(R.drawable.overscroll_glow);
    overscrollGlow.setScaleType(ScaleType.FIT_XY);
    overscrollEdge = new ImageView(context);
    overscrollEdge.setImageResource(R.drawable.overscroll_edge);
    overscrollEdge.setScaleType(ScaleType.FIT_XY);

    addView(underscrollGlow, getWideLayout(ALIGN_PARENT_TOP));
    addView(underscrollEdge, getWideLayout(ALIGN_PARENT_TOP));

    addView(overscrollGlow, getWideLayout(ALIGN_PARENT_BOTTOM));
    addView(overscrollEdge, getWideLayout(ALIGN_PARENT_BOTTOM));
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if(ev.getAction() == MotionEvent.ACTION_DOWN) interruptFade = true;
    listViewGestureDetector.onTouchEvent(ev);

    if(ev.getAction() == MotionEvent.ACTION_UP) reset();
    return super.dispatchTouchEvent(ev);
}

private RelativeLayout.LayoutParams getWideLayout(int alignment)
{
    RelativeLayout.LayoutParams returnLayout = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);
    returnLayout.addRule(alignment);
    return returnLayout;
}

public void reset()
{
    interruptFade = false;
    new GlowShrinker().execute(scrollDistanceSinceBoundary);
    scrollDistanceSinceBoundary = 0;
}

private class ListViewGestureDetector extends SimpleOnGestureListener
{
    @Override
    public boolean onScroll(MotionEvent downMotionEvent, MotionEvent currentMotionEvent, float distanceX, float distanceY)
    {
        float distanceTraveled = downMotionEvent.getY() - currentMotionEvent.getY();
        if(listIsAtTop() && distanceTraveled < 0) // At top and finger moving down
        {
            scrollDistanceSinceBoundary -= distanceY;
            scaleEdges(underscrollEdge, underscrollGlow, scrollDistanceSinceBoundary);
        }
        else if(listIsAtTop() && distanceTraveled > 0 && scrollDistanceSinceBoundary > 0) // At top and finger moving up while in overscroll
        {
            scrollDistanceSinceBoundary -= distanceY;
            scaleEdges(underscrollEdge, underscrollGlow, scrollDistanceSinceBoundary);
        }
        else if(listIsAtBottom() && distanceTraveled > 0) // At bottom and finger moving up
        {
            scrollDistanceSinceBoundary += distanceY;
            scaleEdges(overscrollEdge, overscrollGlow, scrollDistanceSinceBoundary);
        }
        else if(listIsAtBottom() && distanceTraveled < 0 && scrollDistanceSinceBoundary > 0) // At bottom and finger moving up while in overscroll
        {
            scrollDistanceSinceBoundary += distanceY;
            scaleEdges(overscrollEdge, overscrollGlow, scrollDistanceSinceBoundary);
        }
        else if(scrollDistanceSinceBoundary != 0) // Neither over scrolling or under scrolling but was at last check. Reset both graphics.
        {
            reset();
        }

        Log.v(CustomGlowListView.class.getSimpleName(), "boundaryDistance = " + scrollDistanceSinceBoundary);

        return false;
    }

    private boolean listIsAtTop()   {   return listView.getChildAt(0).getTop() - paddingRectangle.top == 0;     }
    private boolean listIsAtBottom(){ return listView.getChildAt(listView.getChildCount()-1).getBottom() + paddingRectangle.bottom == listView.getHeight(); }
}

private class GlowShrinker extends AsyncTask<Float, Integer, Void>
{
    ImageView glow;
    ImageView edge;

    private final int SHRINK_SPEED = 4;
    private final int SHRINK_INCREMENT = 50;

    @Override
    protected void onPreExecute() {
        if(underscrollGlow.getHeight() > 0)
        {
            glow = underscrollGlow;
            edge = underscrollEdge;
        }
        else if (overscrollGlow.getHeight() > 0)
        {
            glow = overscrollGlow;
            edge = overscrollEdge;
        }
        else
        {
            return;
        }
    }

    @Override
    protected Void doInBackground(Float... scrollDistanceSinceBoundary) {
        if(glow != null && edge != null)
        {
            int currentSize = (int) scrollDistanceSinceBoundary[0].floatValue();
            int shrinkRate  = (int) currentSize / SHRINK_INCREMENT;

            for(int i=0; i < SHRINK_INCREMENT; i++)
            {
                if(interruptFade)
                {
                    publishProgress(0);
                    return null;
                }
                currentSize -= shrinkRate;
                publishProgress(currentSize);

                try {       Thread.sleep(SHRINK_SPEED);     } catch (InterruptedException e) {  }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if(glow != null && edge != null)
            CustomGlowListView.scaleEdges(edge, glow, 0);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        CustomGlowListView.scaleEdges(edge, glow, values[0]);
    }
}

private static void scaleEdges(ImageView scrollEdge, ImageView scrollGlow, float scrollBy)
{
    float edgeSize = scrollBy / 20;
    float glowSize = scrollBy / 2;
    if(edgeSize > MAX_EDGE_SIZE) edgeSize = MAX_EDGE_SIZE;
    if(glowSize > MAX_GLOW_SIZE) glowSize = MAX_GLOW_SIZE;
    setHeight(scrollEdge, edgeSize);
    setHeight(scrollGlow, glowSize);
}

private static void setHeight(ImageView viewIn, float height)
{
    ViewGroup.LayoutParams params = viewIn.getLayoutParams();
    params.height = (int) height;
    viewIn.setLayoutParams(params);
}

public AbsListView getListView()
{
    return listView;
}
}

The overscroll images you can grab from platforms\android-10\data\res\drawable-mdpi\ and then change Hue & Saturation to change color.
I hope this can be a useful start for other ListView customisations - Be interesting to hear of any.
Comment: I've expanded on your code to allow for fling events (only from API level 9) and have posted it here: http://pastebin.com/CtauD3sh
Comment: `onFling()` in itself won't do you much good, because it won't tell you when a boundary of a list is "hit". API level 9 introduced the function `onOverScrolled()` for ListViews (line 51 in my pastebin).
Comment: I'm afraid this solution doesn't work very well (at least not on Gingerbread). The effect seemingly randomly displays while scrolling normally, and doesn't appear when hitting a boundary of the list when flung. The effect only appears as expected when attempting to drag beyond a boundary. Perhaps something is wrong with my (simple) implementation?
Comment: Adding an additional check in `listIsAtTop()` for `listView.getFirstVisiblePosition() > 0` (and similarly for the end at `listIsAtBottom()`) resolves the problem of "random overscroll effects." (This is due to Android's recycling of list items, upon which the calculation is performed). I'd still like to see the effect display when the list is flung, but other than that, it looks good!
Comment: I haven't implemented fling over and under scrolling in the above example. I didn't experience "random overscroll effects" but if you've fixed it great.
Answer: Actually, instead of using a customized ListView, you can simply "hack" your way to changing the color, the glow effect is actually a Drawable embedded in the OS's resources, you can apply a ColorFilter on that:
int glowDrawableId = context.getResources().getIdentifier("overscroll_glow", "drawable", "android");
Drawable androidGlow = context.getResources().getDrawable(glowDrawableId);
androidGlow.setColorFilter(brandColor, PorterDuff.Mode.MULTIPLY);

Read more about it here: http://evendanan.net/android/branding/2013/12/09/branding-edge-effect/
Answer: The following method overrides the standard overscroll color including the edge line.
Calling it once in onCreate is enough.
...
ChangeOverScrollGlowColor(getResources(), R.color.red);
...

public static final void ChangeOverScrollGlowColor( Resources res, int colorID ) {

    try {

        final int glowDrawableId = res.getIdentifier("overscroll_glow", "drawable", "android");
        final Drawable overscrollGlow = res.getDrawable(glowDrawableId);
        overscrollGlow.setColorFilter(res.getColor(colorID), android.graphics.PorterDuff.Mode.SRC_ATOP);

        final int edgeDrawableId = res.getIdentifier("overscroll_edge", "drawable", "android");
        final Drawable overscrollEdge = res.getDrawable(edgeDrawableId);
        overscrollEdge.setColorFilter(res.getColor(colorID), android.graphics.PorterDuff.Mode.SRC_ATOP);

    } catch (Exception e) {
    }
}


Statistical description of how two distributions are different

Question: I am have a collection of events recorded in two separate conditions, and I have measured the duration of each one of them. I would like to know two things: 1) are the distributions of durations different between the two conditions, and 2) if so, how are they different? For example, maybe the biggest difference between the two conditions is that there are far more 10 ms long events in condition #1 than in condition #2.
I feel confident in using a Kolmogorov-Smirnov test to determine whether the distributions are significantly different, but am stuck on how to describe what the differences actually are using a statistical test or collection of test statistics. I could histogram the data and run some sort of ANOVA, but that seems a little course and inelegant. Or maybe it is fair to plot the distributions on top of each other and simply read off the difference at areas of interest. Any advice on how to tackle this problem?
Below is some example data. Here a Kolmogorov-Smirnov test comparing these two distributions returns a very small p-value (p < 0.000001), so I know that the two distributions come from different populations. Based on how I think the KS test works, this also tells me that where the two distributions are widest apart in the horizontal plane (around 0.9 on the y-axis) the two distributions are significantly different (there are more events with durations around 60 ms in group 1 than in group 2). But what about everywhere else in the distribution? Is there a way for me to know whether the difference in the amount of events that are 10 ms long is also statistically significant?
Comment: There are many ways in which distributions might differ. It depends on the kinds of differences that are important to describe.
Comment: It might be useful to make a QQ-plot of the two distributions!
Comment: You could look into " "Relative Distribution Methods in the Social Sciences" by Mark S. Handcock and Martina Morris, Springer-Verlag, 1999" which has an associated R package,  reldist.
Comment: @ kjetil b halvorsen: Thanks for the suggestions! I've looked into Relative Distributions and QQ-plots, but unless I'm misunderstanding them, I don't think they help me to answer the problem I'm after. In both cases I'm visually interpreting a plot, but don't have a way of testing the difference between the distributions at every position along the curve? Is that correct?
Comment: I've edited the question to include some sample data and potentially clarifying remarks.
Comment: From you graphic, it look like a lot what you want to do is to compare the two groups to see whether their differ in the time before an event occur.
This is classicaly something we deal with with Survival analysis, you should have a look.
Comment: A t-test of the log-scaled duration is simple and might do the trick as well.
Answer: From a descriptive standpoint, a QQ plot is about as good as it gets for something like this, you can really see where in the distributions things are different (heavier tails, skew, location shift, outliers). That might give you insight about what parameter of the distributions you are interested in testing.
The issue with a statistical test is that it demands that you really clearly state what you care about, i.e., your null hypothesis. As an example, if you wanted to compare whether or not the mean of two distributions was different, you might not care that their standard deviations are different:
<code>a = rnorm(100, sd = 3); b = rnorm(100, sd = 1))
> t.test(a,b)$p.val
[1] 0.2825168

> ks.test(a,b)$p.val
[1] 7.14257e-05
</code>
If our null hypothesis is that the means are different, it wouldn't be correct to test with the KS-test and we see we'd incorrectly reject the null. In your case, you have to state, what aspect of the distribution you care about and then test accordingly.
It would be fine to ask, Is the 10th-percentile different -- that's a good null hypothesis. I'm not aware of well-known statistical test for such a thing, but you could certainly use a bootstrap-based approach.
Comment: Is it fair to do a KS-test first, then follow up with testing differences between specific areas of the distributions? I'm envisioning the protocol might be similar to the way one does an ANOVA first, then follows up with multiple comparisons.
Comment: Can you expand on the "bootstrap-based approach" suggestion, please?
Comment: Sure, I might not have enough characters, but: Your null is that the two distributions have the same 10th percentile. You compute the 10th percentile on each of your two distributions take the absolute difference, call that absolute difference S*. You now sample, with replacement, two datasets of equal size as your originals from the _combined_ dataset (under the null, they have the same distribution), compute the abs 10th percentile difference as before; S_1,..._S_100. Count how many of the times your original S is bigger than the 100 resampled differences (S_1, ..., S_100).


Sql executa no Oracle SQL Developer, mas não executa na aplicação C#

Question: vsql = @"INSERT INTO ALUNOS_ (UF, IDADE, TELEFONE, NOME_PAI, ENDERECO, EMAIL,
                             NOME, CIDADE, NOME_MAE)
        values ('sp', 0,'','','','','','','');";

Esta SQL quando executada no oracle faz a inserção mas na aplicação da o erro

ORA-00933: comando SQL não encerrado adequadamente;

O que pode ser?
Resolvido apenas tirando o ponto e virgula no fim da sql.
Outra duvida que surgiu agora com parametros, Sql executa no Oracle SQL Developer, mas não executa na aplicação C#
Answer: É bem simples na verdade
Seu sql:
vsql = @"INSERT INTO ALUNOS_ (UF, IDADE, TELEFONE, NOME_PAI, ENDERECO, EMAIL,
                             NOME, CIDADE, NOME_MAE)
        values ('sp', 0,'','','','','','','');";

Sql funcional;
vsql = @"INSERT INTO ALUNOS_ (UF, IDADE, TELEFONE, NOME_PAI, ENDERECO, EMAIL,
                             NOME, CIDADE, NOME_MAE)
        values ('sp', 0,'','','','','','','')";

Você pode verificar que removi somente um ponto e virgula da sua string, pois isso ele não consegue interpretar.
Comment: KKK Cara estou a dois dias nisso, valeu mesmo. Mas um outro problema persiste, vou colocar aqui.
Comment: @BrunoVinicius Se for diferente marque essa como resolvida e crie outra pergunta
Comment: Sou novo aqui, como faço para marcar como resolvido?
Comment: Ja marcou é só setar o viès


Inferir tipo da classe a partir de um genérico

Question: Na classe a seguir quero atribuir ao atributo clazz o tipo da classe inferindo-o a partir da lista informada no construtor.
class Foo<T> {
    private Class<T> clazz;

    Foo(List<T> list) {
        //this.clazz = tipo da classe inferido a partir da lista
    }

    ...
}

A minha primeira tentativa foi usar o método list.getClass() o que se mostrou equivocado, pois o valor retornado pelo método foi java.util.ArrayList.
Como inferir o tipo de um bean informado em um ArrayList? É possível fazer esse tipo de inferência a partir do parâmetro, como no exemplo? Se sim, como seria? Se não, quais são as possibilidades existentes, ou seja de que forma ajustar esta classe de modo a atribuir o valor correto ao atributo clazz?
Comment: Olá, @Delfino. Dei uma olhada no link. Parece ser a mesma coisa, mas não é. A pergunta do SOen é mais abrangente. A minha mais específica. Quero recuperar o tipo (T) a partir de um List.
Comment: Sim, realmente, a estrutura de código está tão parecida que a primeira vista parece igual.
Tentei até achar uma solução para você, mas realmente parece não ser possível, tentei de várias formas, e até onde fui não há como.
Comment: Esta pergunta é exatamente a mesma que está no SOen: http://stackoverflow.com/q/3403909/2766598
Comment: O seu código não faz sentido. *T* é um type parameter da classe *Foo* e *clazz* é declarada como sendo do tipo deste type parameter. Daí então você tenta setar para esta variável uma **lista** do tipo do type parameter, mas a variável não é do tipo lista... Está  difícil de entender seu objetivo. De qualquer modo, o generic do Java não oferece recurso para você resgar o tipo do type parameter em tempo de execução.
Comment: @Caffé, talvez você esteja correto, contudo o objetivo do código foi transmitir a minha necessidade. Preciso de alguma forma receber uma lista do type parameter e atribuir valor ao meu atributo clazz. Por suspeitar que isso não seja possível dei a sujestão de adaptar o código da pergunta.
Comment: O problema de o seu código não fazer sentido é que não dá pra entender exatamente o que você precisa; o bjetivo do código não foi alcançado, sua necessidade não foi transmitida. De qualquer modo, como demonstrado na minha resposta e explicado o motivo, inferir o tipo de *T* usando os recursos do Generics não é possível. Se você quer o tipo, precisa informá-lo em outro parâmetro. Por exemplo: `Foo(List list, Class type) { ... }`.
Comment: @Caffé, o exemplo que você forneceu aqui no comentário é justamente o tipo de mudança que sugeri em caso de impossibilidade de uma solução usando o código da forma como está. Seria interessante esta complementação em sua resposta.
Answer: Um truque possível é trocar uma instância da sua classe:
Foo<Integer> x = new Foo<Integer>(new ArrayList<Integer>());

Por uma subclasse dela (no caso uma classe anônima):
Foo<Integer> x = new Foo<Integer>(new ArrayList<Integer>()){};
//                                             Repare no {} ^

Feito isso você pode utilizar a estratégia mencionada nessa resposta do SOen para inferir os tipos genéricos da superclasse:
this.clazz = (Class<T>) ((ParameterizedType) getClass()
            .getGenericSuperclass()).getActualTypeArguments()[0];

No seu caso por definição o tipo da superclasse será o tipo da lista.
Como instanciar a classe diretamente lançará um erro em runtime vale a pena tornar Foo abstrata:
abstract class Foo<T> {
    private final Class<T> clazz;

    public Foo(List<T> list) {
        this.clazz = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }
}

Alternativamente podemos utilizar a mesma estratégia com a lista:
this.clazz = (Class<T>) ((ParameterizedType) list.getClass()
        .getGenericSuperclass()).getActualTypeArguments()[0];
// ...
List<Integer> t = new ArrayList<Integer>(){};
FooII<Integer> x = new FooII<>(t);

Porém isso me parece ainda mais confuso (subclasses anônimas de ArrayList???).

É claro que essa estratégia possui limitações... A principal delas é que <T> tem que ser um tipo real. Se você construir Foo passando outro tipo genérico os casts irão falhar.
Versão funcional no Ideone
Comment: É bastante estranho mesmo, mas você encontra exemplos por aí; o mais famoso que consigo pensar  é [`GenericType`](https://jersey.java.net/apidocs/latest/jersey/javax/ws/rs/core/GenericType.html) do JAX-RS.
Comment: Achei sua resposta bem criativa. Contudo, acho difícil alguém usar este tipo de escrita: Foo x = new Foo(new ArrayList()){}. É um tanto estranho.
Answer: Aparentemente não é possível pegar o type da lista em tempo de execução, o que da pra fazer é verificar se ela possui algum objeto inserido e pegar o tipo dele. Exemplo:
private Class clazz;

Foo(List<T> list) {
    this.clazz = (list != null && !list.isEmpty()) ? list.get(0).getClass() : null;
}

Exemplo 1
public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("1");
    Foo f = new Foo(list); // lista populada
    System.out.println(f.getClazz());
}

class java.lang.String

-
Exemplo 2
public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    Foo f = new Foo(list); // lista vazia
    System.out.println(f.getClazz());
}

null

UPDATE
Outra solução é passar um parâmetro a mais no construtor, exemplo:
Foo(Class<T> typeClass, List<T> list) {
    this.clazz = typeClass;
    // ...
}

E pra chamar:
new Foo(String.class, list);

Comment: Maicon, sua resposta é boa, mas contém um hiato: se a lista for vazia não será possível inferir e atribuir o Type ao atributo `clazz`.
Comment: Sim, por isso avisei na resposta que aparentemente não é possível, mas se ela tiver algum elemento se torna possível.
Comment: Maicon fiz um ajuste na pergunta. Você pode ajustar sua resposta de modo a contemplar as mudanças.
Comment: @GeisonSantos Alterei a resposta, vê se é o que você procura
Answer:
O Java não mantém o tipo do generic após a compilação (ele faz o tal do "type erasure"). Em outras palavras, o tipo do parâmetro generic (ou "type parameter") não pode ser resgatado em tempo de execução.

Existem alguns truques que não funcionam em todas as situações. Então:

A forma usual de ler o tipo de um generic em tempo de execução é não ler o tipo do generic em tempo de execução, mas sim informar este tipo em um parâmetro.

Por exemplo, seria bacana se este código funcionasse:
class AbstractFactory<T> {
    public T Create() {
        return T.newInstance(); // isso não funciona!!
    }
}
class CarroFactory extends AbstractFactory<Carro> {
}
...
CarroFactory carroFactory = new CarroFactory();
Carro carro = carroFactory.Create();

No código acima, minha intenção é usar generic não apenas para manter o factory tipado, com as devidas checagens de tempo de compilação, mas também para aproveitar o tipo informado como type parameter do factory para criar uma instância deste tipo. Isto não funciona pois o tipo do type parameter T será perdido depois da compilação.
Então eu tenho que fazer isso:
class AbstractFactory<T> {
    private Class<T> type;
    public AbstractFactory(Class<T> type) {
        this.type = type; // no constutor eu peço o tipo do type parameter
    }
    public T Create() {
        // com o tipo que eu pedi no construtor eu posso criar uma instância
        return type.newInstance();
    }
}
class CarroFactory extends AbstractFactory<Carro> {
    // para poupar o consumidor desta tarefa,
    // eu informo aqui o tipo do type parameter
    public CarroFactory() {
        super(Carro.class);
    }
}
...
CarroFactory carroFactory = new CarroFactory();
Carro carro = carroFactory.Create();

Agora, com um pouco mais de código e alguma redundância, eu tenho meu factory bem tipado e com a capacidade de criar instâncias não do tipo do type parameter, mas sim do tipo que eu informei no construtor do factory.
Answer:
Acredito que já foi bem coberto por todas as respostas as limitações do type erasure que é implementado pelo javac, ou seja, o tipo generico não tem como ser recuperado diretamente.
A minha intenção então será mostrar uma implementação alternativa para obter esses valores de forma bem objetiva:

A comparação em questão será sempre verdadeira pois em tempo de
  compilação ambos tipos genericos são erased pelo compilador, porém String.class != Integer.class

assert new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass();

Agora olhando para esse estrutura, seria possivel obter o tipo
  generico  a partir da subclasse MyStringSubClass buscando a
  informação que é mantida no bytecode compilado <1.5 ou superior, nas outras
  será ignorado> .

class MyGenericClass<T> { }
class MyStringSubClass extends MyGenericClass<String> { }

Primeiramente nos encontrariamos a superclasse e posteriormente,
  encontramos o tipo generico obtendo o argumento da superclasse.

ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass();
Class<?> genericType = parameterizedType.getActualTypeArguments()[0];
assert genericType == String.class;

Lembrando que essa é uma demonstração simplificada, de um hack elegante para obter o tipo generico. Porem em nivel de API a implementação seria mais complexa entregando a cobertura necessaria a diversos cenarios problematicos.
A recomendação final fica em utilizar uma ótima API para a reflection de tipos genericos:
Generic type reflection library for Java fazendo você economizar um bom tempo.
No mais segue mais um link com uma cobertura do assunto em alto nível, feita por Rafael Winterhalter.


Python, check when file is saved

Question: The goal is to do something every time a file from a list is modified (saved).
I have no idea to proceed. The end goal should be something like this:
<code>files = ['file1.txt', 'file2.txt', 'file3,txt']

if (one of the files in files is modified):
    Print '%s has been modified' % (filename)
</code>
Comment: maybe use `os.path.getmtime(file)` and compare last to current
Comment: I added a simple answer, I doubt for 10 files you have to worry too much about your processor. You could also pickle the result and run a script at a certain time of the day and compare that way, there are basically a lot of different ways to do what you want.
Comment: what do you mean by modified?
Comment: Which operating system?
Comment: I mean that i want to check if someone saves the file. So if someone edits the file and saves it, the program will print out that the file has been modified
Comment: so you mean the file has changed not just saved?
Comment: I would prefer that it worked on the most popular pc operating systems, if that is not possible, then windows
Comment: No, i just want to check when someone saves the file
Comment: Are those changes done by your script?
Comment: They are not done by any script. And i was also wondering, if i have to check the time on every file, won't it use a lot of processing power?
Comment: How many files are there?
Answer: This will check the times using a dict and print any modified files:
<code> import os.path, time
files = ['file1.txt', 'file2.txt', 'file3,txt']
changes =  {"file1.txt":os.path.getmtime("file1.txt"),"file2.txt":os.path.getmtime("file2.txt"),"file3.txt":os.path.getmtime("file3.txt")}
while True:
    for f in files:
        if changes.get(f) < os.path.getmtime(f):
            print "File {} has been modified".format(f)
            changes[f] = os.path.getmtime(f)
        else:
            print "No changes, going to sleep."
    time.sleep(10)
</code>
Comment: When does it update the time in changes?
Comment: @VictorVH, forgot that part! I added the line.
Comment: Thank you, i thought there was something i wasn't seeing
Comment: No worries, you're welcome. I threw it together a bit too quick.

Python, check when file is saved


.NET 6.0 missing when creating a ASP.NET MVC Application in visual basic

Question: I'd like to create a MVC web app using ASP.NET and visual basic.
So, in Visual Studio, i've selected the corresponding template project :

In the next screen, why .NET 6.0 is missing (considering that if I select C# project template, .NET 6.0 is selectable) ?

EDIT:
I used Visual Studio Community 2022 up to date.
Here are the choices that i had when filtered to VB and Web project type:
Answer: Which version are you using? .NET 6 is only supported in VS 2022.
Another thing: You selected (.NET Framework) project. You have to select (Core)
Comment: I edited the question providing these infos
Comment: It seems that you cannot create a MVC template using VB. It accepts only C# and F#. More info: https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new-sdk-templates
Comment: It seems indeed. And it was confirmed here: https://github.com/dotnet/aspnetcore/issues/8674
BUT there is a template: https://marketplace.visualstudio.com/items?itemName=ModernVBNET.Vazor
Comment: Glad to see your problem solved, you can post your conclusion as answer and  click '✔' to mark it as the accepted answer to change its status to Answered. It will also help others to solve the similar issue.


PHPMyAdmin on Ubuntu: Connection for controluser as defined in your configuration failed

Question: As subject, my phpmyadmin installation on ubuntu have that error, did you know what it means and how to solve it?
Comment: Silly question, I should have searched it before asking:D
Found the answer here:
http://ubuntuforums.org/showpost.php?p=7362860&postcount=5
Answer: Open config.inc.php file on phpMyAdmin folder.
Find this line:

$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

Go to phpMyAdmin user privileges.
Then change the "pma" password.
Refresh your phpMyAdmin.
Comment: i didn't find where the config.inc.php file located?
Comment: It depends. If you install manually by download phpmyadmin from their website, you can find `config.inc.php` in root directory of phpmyadmin. But, if you install from package manager, let's say Ubuntu, you can find at `/etc/phpmyadmin/config.inc.php`.


In BIND, forward DNS query for specific domain to specific nameserver

Question: Windows Server 2003 has this feature where you can forward queries for domain "example.com" to specific nameserver (not the default DNS server).
How do i set this up in BIND? For example, i want to set up forwarding for local TLD to specific local nameserver.
Bind version 9.6
Working configuration
As Khaled noted, we can use forwarders statement in zone clause. It worked with the following configuration:
zone "local." IN {
   type forward;
   forward only;
   forwarders { 10.10.1.9; };
};

Answer: Have a look at this page. You can use the forward and forwarders statements inside your zone block.
forward ( only | first )
forwarders { ipv4_addr }


Assign a volume pedal to a DSP on a Psr keyboard?

Question: I have a yamaha Psr-2100, and a volume pedal (yamaha fc7). I was hoping I could assign my pedal to affect a certain parameter of an effect that is applied on a voice, for example distortion or vibrato. This would be very useful for like Organ playing.
I found a way to have a main voice and a layer, and only applying the volume pedal to the layer. The layer would then be a copy of the main voice, only with the added effect (distortion enabled). This does give a bit of what I was hoping for, however since now everytime I 'enable distortion' I get a big volume boost, which isn't really desirable.
Anyone knows how to assign the pedal to an effect/dsp, or otherwise an alternative solution?
Answer: So the pedal is working ok, then.  It's just a matter of you figuring out the sound module part of your keyboard?  Not having that keyboard, I'd say it's time to dig through the manual and pray :)  Sorry, not much of an answer, I know...  google the manufacturer's website for the manual in .pdf form if you lost it.
Answer: The first thing I would say is, you can't.   Unless you mean to ask "how can I turn DSP on and off?".
I that case, hit the shortcut button, then the paddle, then scroll with the wheel and look for an option "dsp on/off".
If you don't see it, then you probably can't do that.
Also, there is a similar trick that may help: in the voice settings of the instrument (which you should be able to access from the voice folder with a up arrow) you should find two options called "amplitude" and "filter" (to be sure, find amplitude. Whatever is right next to it should be the correct one).
Set one to max (127) and the other one to min (0).
You'll know if you do the wrong combination (the are only two!) because it will probably go mute on you.


If $f$ is Riemann integrable on $[a,b]$ , is $|f|$ Riemann integrable on $[a,b]$?

Question: If $f$ is Riemann integrable on $[a,b]$ , is $|f|$ Riemann integrable on $[a,b]$ ?
(The metric is $\mathbb R$ usual)
The other is question is $f$ is Riemann integrable on $[a,b]$ , can I claim $f$ is bounded on $[a,b]$ ? (I think the answer can be either yes or no that depend on considerating generalized function or not)
Update: I think I made a mistake on second question that both definitions of Riemann integral and generalized Riemann integral on [a,b] request the f being bounded on [a,b]. Sorry for my mistake.
Comment: @MrSelberg, that function is not Riemann integrable on $[0,1]$. Do not confuse "improperly Riemann integrable" with "Riemann integrable".
Comment: It is more general than that. Refer to theorem 6.11 of baby rudin.
Comment: Riemann Integration is only considered for bounded functions
Comment: @MrSelberg: I've calculated the integral of $f(x)=1/\sqrt x$ and the result is 2 when I used ε+ to replace 0. Seems the definition of $f(x)$ at 0 has no effect on the integral?
Comment: Correct, it have not effect.
Comment: @learnmore: so if $f$ ∈ $R[a,b]$, will it imply $f$ ∈ $B[a,b]$?
Comment: @SantiagoCanez True. I apologize for the mistake.
Comment: @SantiagoCanez: What's the name of integral of $f(x) = 1/\sqrt x$ on[0,1]?
Answer: Using the reverse triangle inequality we have
$$\begin{align}\sup_{x \in [x_{j-1},x_j]}|f|(x) - \inf_{x \in [x_{j-1},x_j]}|f|(x) \\&=\sup_{x,y \in [x_{j-1},x_j]}| |f(x)|-|f(y)|| \\ &\leqslant \sup_{x,y \in [x_{j-1},x_j]}| f(x)-f(y)| \\ & = \sup_{x \in [x_{j-1},x_j]}f(x) - \inf_{x \in [x_{j-1},x_j]}f(x).\end{align}$$
For a given partition $P = (x_0,x_1, \ldots, x_n)$, the difference of upper and lower sums
is
$$U(P,|f|) - L(P,|f|) = \sum_{j=1}^n \left(\sup_{x \in [x_{j-1},x_j]}|f|(x) - \inf_{x \in [x_{j-1},x_j]}|f|(x)\right)(x_j - x_{j-1})\\ \leqslant  \sum_{j=1}^n \left(\sup_{x \in [x_{j-1},x_j]}f(x) - \inf_{x \in [x_{j-1},x_j]}f(x)\right)(x_j - x_{j-1})\\= U(P,f) - L(P,f)$$
Since $f$ is Riemann integrable, for any $\epsilon > 0$ there exists a partition $P$ such that the difference of upper and lower Darboux sums satisfies
$$U(P, |f|) - L(P, |f|) \leqslant U(P,f)-L(P,f) < \epsilon.$$
Hence, $|f|$ is Riemann integrable.
Comment: what is Darboux sum?
Comment: Just the usual upper and lower (Riemann) sums -- technically the name Darboux is applied.  Also if a function is Riemann integrable, then it is bounded.  See http://math.stackexchange.com/a/1177188/148510
Comment: Thanks. I think your proof is correct.
Comment: Yes. f is Riemann integrable necessarily means f is bounded coz bounded f is a part of the definition of Riemann integrable.
Comment: @Frank_W: You're welcome.
Answer: I will use the fact that $f(x)$ is Riemann integrable on $[a,b]$ if and only if it is bounded and continuous almost everywhere on $[a,b]$.
Let $f(x)$ be Riemann integrable on [a,b]. Then $f$ is bounded and continuous almost everywhere. Define $f_+(x)$ by $f_+(x)=f(x)$ if $f(x)>0$, and $f_+(x)=0$ otherwise. Then $f_+(x)$ will also be bounded and continuous almost everywhere. Thus $f_+(x)$ is Riemann integrable. Similarly, define $f_-(x)$ by $f_-(x)=f(x)$ if $f(x)\leq 0$ and $f_-(x)=0$ otherwise. Then $f_-(x)$ is also Riemann integrable by the same reasoning as above. Riemann integrability of $|f(x)|$ follows since $|f(x)|=f_+(x)-f_-(x)$.
Answer: Let $\epsilon >0$ be arbitrary
Let $P=\{a=x_0<x_1<x_2<....<x_n=b\}$ be a partition of $[a,b]$ with $||P||<\delta$
let $M_i=\sup _{({x_{i-1},x_i})}f$ and $m_i=\inf _{({x_{i-1},x_i})}f$
let $M_i^{'}=\sup _{({x_{i-1},x_i})}|f|$ and $m_i^{'}=\inf _{({x_{i-1},x_i})}|f|$
Then $\sum_{i=1}^n\{|M_i^{'}-m_i^{'}|\}\Delta x_i\leq \sum_{i=1}^n|M_i-m_i|\Delta x_i<\epsilon$
Comment: Why do you say $|M_i|=\sup_{(x_{i-1},x_i)}|f|$? That's not true in general, if $f$ is positive, this is true... but then we have nothing to prove.
Comment: I think MrSelberg's comment is right. Some bugs need to be fixed.
Comment: I don't know. I do not click downvote. Still thanks, learnmore


Avoiding Dependancy Hell in a Restrictive Environment

Question: This may be a canonical question, and it may simply be a function of my inexperience, but I'm curious to know if there are best practices aimed at avoiding dependency hell when you find yourself in an environment with limited access to common, open repositories.
In our specific case, our struggle is working within the context of a large corporation with security policies that severely diminish the ability to access outside repos for packages when installing various software.
How do you balance security with the need for access to public repos?  Is there a way to limit the dependance on external repos without making the installation of Linux software impossible?  What kind of arguments can be made for the security and reliability of yum or apt-get repos?
A broad question I know - I hope it's appropriate here - but I'm very curious to see what other people's experience in this area has been.
Answer: You avoid dependency hell (and a whole raft of other things) better when you limit the number of external repositories you use.  Since you can't guarantee the quality, long-term availablility, and timeliness of the contents of those repositories, it is a very poor move to rely on their contents (and continued existence).
As a concrete example, I've previous seen examples where semi-official third-party repositories of packages for a stable Linux distribution had packages come and go over time.  This caused a great deal of trouble, because we might build up a few machines at one time, which all got the same version of a critical package.  Some time later, when we went to build more machines, the version we had specified was no longer available (superceded by a newer, shinier version) and we had to test everything again to make sure the newer package still worked properly.
This isn't the worst possibility.  What if we didn't test the new package, and it had a critical bug in it?  Bummer.  Of course, the version we choose may turn out to have a security flaw in it, but that's OK, because as responsible packagers we keep an eye on upstream security announcements and ensure that any vulnerabilities are patched appropriately.
The cautious administrator only installs packages onto his/her systems from two places:

The distribution's official repositories (appropriately cryptographically verified for authenticity, of course), where the policies and practices of the manner in which packages are added and removed is known and complies with your own risk management assessment; and
An internally managed package repository or repositories (again, cryptographically verified).

The contents of that internal repository set can be populated by several different means:

Download packages from external, third-part repositories, verify their utility and stability in a testing environment, and then add them to the repo.
If you are moderately paranoid, you rebuild the source packages from the above repos, then test and add.
If you're properly paranoid, you shut yourself in a small room without any computers or electronic equipment whatsoever.
Comment: Whoever's building those systems needs their fingers broken.  For the good of the Internet.
Comment: Yes, it is.  Tough if you've got crap internal repos, at least, there's a better chance of making a case and having the repos improved than you do if you're trying to get some third-party repo to work.  As far as not having direct access to the official repos, well, that's easy: an internal mirror.  If that isn't possible, then it's easy to make a strong case that that is an unworkable situation because of lack of timely security updates.
Comment: @womble the saddest part about it...I am not installing packages by hand. As an example our package for HTTPD that comes installed on our system is version 2.2.3-65.el5_8. If I want to say install httpd-devel I stare at 2.2.3-31.el5 so I am forced to downgrade httpd. Further you then get packages for instance apr, apr-util, db4, etc. all of which are incorrect versions against the repo.
Comment: This is a great perspective womble.  The idea of having too many repositories is a great consideration.  I guess I was curious about situations when you have no access to even official repos, like RedHat's.  In our case, we're limited to what I suppose is the next logical solution - an internally managed repo.  Unfortunately, ours seems to be quite limited and very dated, though I guess that's an issue for the repo managers.
Comment: @JohnK I am in the same boat as you. If you try to do a yum install of something it will fail because the version we are using is newer than what the repo has to offer...for instance "devel" packages.  Its a nightmare, and the fix is install a newer version of RHEL....
Comment: @JMeterX: That's entirely self-inflicted hell.  How can you be using a newer version of a package than what is in the repo?  If you're installing packages by hand, well, you only reap what you sow.
Comment: @womble Haha I couldn't agree more with you. Their solution is literally to install the new image the company is offering.
Comment: Unfortunately, JmeterX, what you're describing is our problem too.  Internal repos are turrible, trying to install new software with any dependency on anything new leads to multilayer dependency hunts.  It hurts... my goal here was to learn how to avoid this in the future if I'm ever placed in a position of responsibility.  Thanks for the replies.


How to change rotation handler icon in mxgraph

Question: i'm facing bit difficulty to change rotation handler icon
below image show you:

Steps to reproduce:

click on the box
Observe rotation handler will appear.

i want to change above rotation handler with some other icon.
below is my code:

 <title>Handles example for mxGraph</title>

Answer: To change rotation handler appearance you have to override createSizerShape function in mxVertexHandler, and change part about rotation handle(if (index == mxEvent.ROTATION_HANDLE)).
It have to return shape, originally it create mxEllipse. If you want to use custom image you can use mxImageShape For example:
let imgSrc = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a';
mxVertexHandler.prototype.createSizerShape = function(bounds, index, fillColor)
{
    if (this.handleImage != null)
    {
        bounds = new mxRectangle(bounds.x, bounds.y, this.handleImage.width, this.handleImage.height);
        var shape = new mxImageShape(bounds, this.handleImage.src);

        // Allows HTML rendering of the images
        shape.preserveImageAspect = false;

        return shape;
    }
    else if (index == mxEvent.ROTATION_HANDLE)
    {
        bounds = new mxRectangle(bounds.x, bounds.y, 20, 20);
        var shape = new mxImageShape(bounds, imgSrc);

        // Allows HTML rendering of the images
        shape.preserveImageAspect = false;

        return shape;
    }
    else
    {
        return new mxRectangleShape(bounds, fillColor || mxConstants.HANDLE_FILLCOLOR, mxConstants.HANDLE_STROKECOLOR);
    }
};

So your code will look like this:

 <title>Handles example for mxGraph</title>

Comment: thank you very much!!, can i use **image** instead of `shape`, please help me with **image**
Comment: I didn't get any response from you,  please produce a snippet with **image icon**.  Please help me.
Comment: Hi **Godric**  i'm struck with your solution, please have a look at this one https://codepen.io/eabangalore/pen/VOxBmB, if you tell i will ask this one as separate question here. but **Please have a look on this**, and reply me. Thank you.
Comment: All you need to do is to change if blocks order, first check and handle rotation handle (`if (index == mxEvent.ROTATION_HANDLE)` and then use default image (`else if (this.handleImage != null)`)
Comment: i din't understood, please show me once, thanks in advance!!


Unit test for httpserverletrequest from Java object

Question: I have written the unit test which was passing without any issues:
private Example ex;
@BeforeEach
    void setUp(){
        ex = new ex();
    }
@Test
    void funcTest(){
        UserDataType p1 = new UserDataType("");
        Response noResponse = ex.func(p1);
        assertNotNull(noResponse);
        assertEquals(noResponse.getStatus(),Status.NOT_FOUND.getStatusCode());
    }

public Response func(@Valid Object Obj) {
        UserDataType p1;
        ObjectMapper MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        try {
            String eventJson =  MAPPER.writeValueAsString(obj);
            p1 = MAPPER.readValue(eventJson, UserDataType.class);
            }
            catch (Exception ex) {
                  return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

        if (!p1.object.equalsIgnoreCase("something")) {
            return Response.status(Status.NOT_FOUND).build(); // p1 in test has object as ""
        }

Now the question is:
Since, I am going to change the func in the codebase as follows:
public Response func(@Context HttpServletRequest req) {
      // do Same thing as above
}

Is it possible to wrap the object as HTTPServerLetRequest so that test cases can pass?

I am using the dropwizard framework.
I know in order to get the JSON, I need to use req.getInputStream(). I am basically asking on how/what to pass as req
Answer: The usual way is to use some framework for mock-object (e.g. Mockito), to "mock" HttpServletRequest interface in your unit-test.
Comment: yes, but how to add the Obj in `httpserverletrequest`?
Comment: I have a fealing, that you not really understand how to work with mocks. You have to learn it.

Let's say, your "func" method is using HttpServeltRequest -> getMethod() inside.
In you unit-test you are doing somethign like that:

HttpServeltRequest request = Mockito.mock(HttpServeltRequest.class);
Mockito.when(request.getMethod()).thenReturn("GET");
Response noResponse = ex.func(request);


Improving space complexity in matrix chain multiplication

Question: I want to know whether there is any way to improve space complexity of Dynamic Programming solution of matrix multiplication problem from O(N^2) to something better?
Comment: you have a similar question in this http://stackoverflow.com/questions/4455645/what-is-the-best-matrix-multiplication-algorithm
Comment: I am mainly concerned about space complexity in the Dynamic programming solution of this problem
Answer: Here is a solution with space compexity O(n)
<code>#include <iostream>

using namespace std;

int min_cost(int a[], int n) {
    int* b = new int(n);

    b[1] = 0;
    b[2] = a[0]*a[1]*a[2];

    for (int j = 3; j < n; j++) {
        b[j] = min( b[j-1] + a[0]*a[j-1]*a[j], b[j-2] + a[j-1]*a[j-2]*a[j] + a[0]*a[j-2]*a[j]);
    }

    return b[n-1];
}

int main() {
    int arr[] = {10, 20, 30};
    int size = sizeof(arr)/sizeof(arr[0]);

    printf("Minimum number of multiplications is %d ", min_cost(arr, size));

   return 0;
}
</code>


Tour of heroes Search component if observable is empty

Question: I create the Tour of Heroes, and it works.
But I try to "upgrade" a part of the code and I'm not able to do it.
In the hero.service.ts code you have this part of code about the search:
* GET heroes whose name contains search term */

searchHeroes(term: string): Observable<Hero[]> {
   if (!term.trim()) {
        // if not search term, return empty hero array.
      return of([]);
   }
   return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
   tap(_ => this.log(`found heroes matching "${term}"`)),
   catchError(this.handleError<Hero[]>('searchHeroes', []))
   );
}

My problem is : if I search for something that doesn't exist like "gol" the message rteurned is : found heroes matching "gol"
WRONG I don't found heroes.
So how Can I validate if my observable is empty or not ?
I try something
 private hero = new Observable<Hero[]>();
    searchHeroes(term: string): Observable<Hero[]> {
this.hero = this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`);
 if (!term.trim()) {
      // if not search term, return empty hero array.
      return of([]); //Seulement si le champ recherche est vide, pas si le retour est vide
    }
    this.hero = this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`);

    console.log(term, this.hero, Hero.length);
    if (this.hero !=0) {
      return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
        tap(_ => this.log(`NO heroes matching "${term}"`)),
        catchError(this.handleError<Hero[]>('searchHeroes', []))
      );
    }else{
      return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
        tap(_ => this.log(`found heroes matching "${term}"`)),
        catchError(this.handleError<Hero[]>('searchHeroes', []))
      );
      }
  }

It doesn't work. So how can I manage the observable to know if it's empty or not ?
Thanks
Answer: The return value of http.get is an observable. A totally valid one. Thus, checking the observable against 0, null, etc. isn't going to work as it's a valid object. What you want to do is adjust the logic in the handler for the emission from the observable.
In this case, if you want to log something different when no results are returned you would adjust your tap handler (tap is "do this as well when the observable emits") although you could also check for this in the subscribe handler. Something like:
if (!term.trim()) {
    // if not search term, return empty hero array.
  return of([]);
}
return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
tap(result => {
   if (result.length > 0) {
       this.log(`found heroes matching "${term}"`)
   } else {
       this.log('no matching heroes found');
   }
}),
catchError(this.handleError<Hero[]>('searchHeroes', []))

Comment: @baronming Yeah, that's what I get for doing this without an IDE :)
Comment: Exactly what I wanted. Thanks. But I made a correction to your code because was not working. line 8, replace by : this.log(`found heroes matching "${term}"`); and line 12: }), and finally line 13: catchError(this.handleError('searchHeroes', [])));


Error SQL syntax on FROM and JOIN

Question: Can anyone point me in the right direction why this sql query got an error?
http://sqlfiddle.com/#!9/40058/2
Expected results is to
get the names of Product on a table,
the count of sales on that product,
The amount (transactionamount)
and the net amount (statementdebit)
Comment: http://sqlfiddle.com/#!9/40058/63
Comment: You missed one closing backet in sum statement and remove the spaces after functions like COUNT()  and SUM().
Comment: `transaction` is a keyword. you should change your table name
Comment: Add all relevant Informationen in SO. Not only in a link to sqlfiddle.
Answer: Couple of things wrong in the query

Closing parentheses missing on SUM(transaction.transactionamount AS
Amount
Extra spaces after aggregate functions on select e.g. COUNT ()

Here's the working SQL
SELECT
DISTINCT transaction.transactionservicetype AS Product,
COUNT(transaction.transactionid) AS Count2,
SUM(transaction.transactionamount) AS Amount,
SUM(statement.statementdebit) AS NetCost
FROM transaction
RIGHT JOIN statement ON transaction.transactionid = statement.transactionid
WHERE transaction.transactiondate = '2018-01-17' AND transaction.transactionservicetype = 'LBread';

Working SQL Fiddle
Answer: a transaction is a keyword please cover it with backtick transaction
you are missing one parenthesis after transaction.transactionamount
another thing COUNT (), SUM () should be like COUNT(),SUM() no extra spaces required in function.
SELECT
DISTINCT `transaction`.transactionservicetype AS Product,
count(`transaction`.transactionid) AS Count,
sum(`transaction`.transactionamount) AS Amount,
sum(statement.statementdebit) AS NetCost
FROM `transaction`
RIGHT JOIN statement ON `transaction`.transactionid =
statement.transactionid
WHERE `transaction`.transactiondate = '2018-01-17' AND
`transaction`.transactionservicetype = 'LBread';

Answer: Missing Closing parentheses on "SUM(transaction.transactionamount AS Amount" and
Extra Spaces between COUNT(),SUM() function like "SUM (transaction.transactionamount):

Updated query as per  below using left outer join and
SQL-Fiddle is "http://sqlfiddle.com/#!9/40058/92" :

SELECT
T.transactionservicetype AS Product,
COUNT(T.transactionid) AS CountTotal,
SUM(T.transactionamount) AS Amount,
SUM(S.statementdebit) AS NetCost
FROM statement S
left outer join transaction T  ON T.transactionid = S.transactionid
WHERE T.transactiondate = '2018-01-17' AND T.transactionservicetype = 'LBread'
group by T.transactionservicetype;

Answer: hope it will help you, i'm bit confuse because your table naming field naming.
this my solution
http://sqlfiddle.com/#!9/40058/83/0
sql query :
    SELECT sum(a.statementdebit) debit,count(a.statementdesc) tot_prod,
sum(b.transactionamount) amount,a.statementdesc
FROM
statement a
JOIN transaction b on a.transactionid=b.transactionid
where b.transactiondate = '2018-01-17'
group by a.statementdesc

Error SQL syntax on FROM and JOIN


error: pathspec 'temp/versionX' did not match any file(s) known to git

Question: In git, I'm trying to check out versions of a specific repository into a version folder inside of a temp folder, but when I do
git checkout master~X C:/file/path/temp/versionX

I get the error
error: pathspec 'temp/versionX' did not match any file(s) known to git.

What's causing the problem and how do I fix it?
Comment: I'm assuming `master~X` is the old revision containing the file(s) you want, and that `C:/file/path/temp/versionX` is where you want to place the old file(s).  Two bits of information are missing:  Which old file(s) (relative to the root of the Git repository) do you want?  What is the path to your Git repository?
Comment: Path to the repo is C:/file/path
Answer: git checkout only operates inside the "working tree".  To do what you want, change Git's idea of what the working tree is.  There are a few different ways to do this:

option 1:  run from the Git repository
cd /path/to/repository
# git automatically locates the .git directory as usual
git --work-tree=C:/file/path/temp/versionX checkout master~X

option 2:  run from the destination directory
cd C:/file/path/temp/versionX
# if --git-dir is specified, Git assumes the working tree is .
git --git-dir=/path/to/repository/.git checkout master~X

option 3:  run from some other directory
cd /some/arbitrary/path
# need to specify both the path to .git and the destination directory
git --git-dir=/path/to/repository/.git \
    --work-tree=C:/file/path/temp/versionX \
    checkout master~X

Comment: The file I'm moving it to is inside the directory I'm working. So say for example I'm working in the file C:/dir/myRepo. The file I'm trying to checkout the files to is C:/dir/myRepo/oldversion/temp/versionX. Do I check out the files the same way you just instructed?
Comment: @SSEMember:  I updated my answer.  Does this answer your question?
Answer: Checkout can't be used like that. What you want is git-archive(1). For example:
ancestor=10
git archive --prefix="version${ancestor}" master~$ancestor |
    tar xvf - -C "C:/file/path/temp"

This will export the named commit to a tarball on standard output, which tar will then unpack in the appropriate place. It seems a little cumbersome at first, but it will grow on you.
Comment: I was hoping to avoid archive because it takes *Forever* to unpack everything I'd need to. This work project I'm currently doing is unpacking a couple hundred versions of repos, and in future versions, several thousand. I was hoping to checkout the versions of the repo to a different file inside the git repo, then use a move command to get them outside hoping it would be faster.
Answer: You can try this:
mkdir /file/path/temp/versionX
cd /file/path/temp/versionX
git --git-dir=/path/to/repo/.git --work-path=. checkout master~X


Real dimension of $\mathbb{Z}^d \otimes \mathbb{R}$

Question: I have following, probably really trivial question.
Lets take $\mathbb{Z}^d \otimes \mathbb{R}$. Consider this as vector space over $R$ by defining
$\mu (v\otimes \lambda) = v \otimes (\lambda \mu)$
Then claim is that dimension of this real vector space is $d$.
Clearly it's not bigger then $d$:
Take set $e_1 \otimes 1,e_2 \otimes 1,.., e_d \otimes 1$, any element of tensor product is linear combination of those ($e_i$ are of course basis of the lattice)
But how to prove that this set is linearly independent? It seems really obvious but what's formal proof?
Comment: For any ring $R$, the tensor product $\mathbb{Z}^d \otimes R$ is the free (right) $R$-module $R^d$ on $d$ generators. This can be proven using the fact that $(-) \otimes R$ preserves finite direct sums (in fact it preserves arbitrary direct sums).
Answer: Define the homomorphism $\psi_k:\mathbb{Z}^d\otimes \mathbb{R}\to\mathbb{R}$ by $\psi_k(\sum n_i e_i\otimes r_i)=n_k r_k$ where the $e_i$ are the basis for $\mathbb{Z}^d$. All you need to do now is to show that this is well defined (using the definition of the tensor product) to conclude that if $x=\sum e_i\otimes r_i=0$ then the $\psi_i(x)=r_i$ are zero, namely the $e_i$ are linearly independent over $\mathbb{R}$.


Find a basis of the eigenspace associated with the eigenvalue 3 of the matrix A

Question:
I'm having some difficulties with this problem. After subtracting 3 from the diagonal, I end up with $$\begin{matrix}1&0&-3&-3\\-1&0&0&0\\0&0&3&3\\0&0&0&0\end{matrix}$$
If I do more reducing, the first row is $$\begin{matrix}1&0&-3&-3\end{matrix}$$
So when I solve for the basis, I get 3,0,1,0 and 3, 0, 0, 1. This isn't correct. What's the correct answer? What am I doing wrong?
Comment: Try again without changing the order of the rows of the matrix. That's caused you to make some simple mistakes.
Answer: When you subtract $3$ from the diagonal, you obtain:
$$
A - 3\,\Bbb I_4 =
\begin{pmatrix}
1&0&-3&-3\\-1&0&0&0\\0&0&3&3\\0&0&0&0
\end{pmatrix}
$$
Now remember that the eigenspace of an eigenvalue is defined as the kernel of $A - 3\,\Bbb I_4$; therefore you're looking for all the linearly independent vectors $\mathbf v$ such that $(A - 3\,\Bbb I_4)\mathbf v = \mathbf 0$.
You can then solve the whole linear system or take a closer look at the matrix.
For example, the second column is the zero vector. Then if $\mathbf v = (0,1,0,0)^T$ then you have $(A - 3\,\Bbb I_4)\mathbf v = \mathbf 0$: note that the $1$ in $\mathbf v$ is on the second entry.
The matrix $A - 3\,\Bbb I_4$ has rank two though, so there must be another vector in the eigenspace; to prove that the rank is two, you don't need to do any calculations. Again, look at the matrix: the first row is a linear combination of the second and the third (($-1$) * second + ($-1$) * third = first ), the fourth row is zero and the second and the third are obviously linearly independent (they are not multiples).
To find the last vector, let's take a last look at the matrix; the fourth and the third column are equal. What happens is we consider $\mathbf v = (0,0,1,-1)^T$? If we calculate $(A - 3\,\Bbb I_4)\mathbf v$, that vector sums the third column with the opposite of the fourth column, and again you obtain $\mathbf 0$. Obviously, $(0,1,0,0)^T$ and $(0,0,1,-1)^T$ are linearly independent (they are not multiples).
Finally, the eigenspace of $3$ for $A$ is $\langle(0\ 1\ 0\ 0)^T,(0\ 0\ 1\ -1)^T\rangle$.
I wrrote down what I'm grateful my teachers taught me about solving linear systems with little calculations. This procedure may seem difficult in the beginning, but once you learn it, linear systems like these are really definitely easier to solve.


About digamma function

Question: Show that $F(z)$ has the series expansion $\displaystyle F(z)=-\gamma + \sum_{n=2}^{\infty }(-1)^n\zeta (n)z^{n-1}$ where $\displaystyle \zeta (n)$ is the Riemann zeta function.
Answer: We start with the identity of the digamma function

$$ \psi(z+1) = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n(n+z)}\quad z\neq 0,-1,-2,-3,\dots$$

which implies that
$$ \psi(z+1) = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n^2}\left(1+\frac{z}{n}\right)^{-1} $$
$$ = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n^2}\sum_{m=0}^{\infty}\frac{(-z)^m}{n^m}= -\gamma + \sum_{m=0}^{\infty}(-1)^m {z^{m+1}}\sum_{n=1}^{\infty}\frac{1}{n^{m+2}}$$
$$ = -\gamma + \sum_{m=0}^{\infty}(-1)^m \zeta(m+2){z^{m+1}}  $$

$$ \implies \psi(z+1) = -\gamma + \sum_{m=2}^{\infty}(-1)^m \zeta(m){z^{m-1}}.  $$

About digamma function


Trigger only if build fails

Question: I'm implementing a deployment/rollback procedure using Jenkins 1.430. I would like to configure the deployment and the rollback steps as 2 separate jobs so as to be triggered independently if needed. However I would also like the rollback to be triggered automatically when the deployment fails.
When I go to the Post-build Actions configuration section of the deployment job, I can choose to Build other projects. If I check that setting I get 3 options:
-Trigger only if build succeeds
-Trigger even if the build is unstable
-Trigger even if the build fails
What I'm missing is the Trigger only if build fails option.
Do you know how this can be achieved?
Answer: The Parameterized Trigger Plugin allows you to run another build of any project based upon the status of the just-completed build.
Comment: I've also found this one: https://wiki.jenkins-ci.org/display/JENKINS/Downstream-Ext+Plugin

Trigger only if build fails


uma função para gerar um caminho por um mapa de pontos e segmentos. ps: complicado, pelo menos para mim

Question: Olá, estou testando umas ideias, fazendo uns programas em python 3, e preciso de ajuda com uma coisa complicada na qual não entendo nada, nem consigo bolar qualquer solução minimamente viável. para resumir, preciso criar uma função que receberá 3 parâmetros (ainda a serem comentados), e me retorne a menor rota possível entre dois terrenos.
para entender melhor o funcionamento que essa função deverá ter, demostrarei com uma imagem. a imagem abaixo.

como podemos ver, a imagem é composta de Bolinhas e segmentos de retas, pense em cada bolinha como um terreno, cada uma possui um código único (ID por assim dizer) para ser identificado, esse código é uma string, pode ser uma letra, nome, seja lá o que for, só devemos observar que não pode conter ponto. ou barra/ e será um código único para cada terreno, não podendo por tanto, ter dois terrenos com o mesmo código.
os terrenos por sua vez, são ligados por segmentos de retas, pensem nelas como estradas, logo podemos pensar em rotas também. e é isso que preciso, preciso de uma função que irei fornecer uma listra como primeiro parâmetro, essa listra será uma espécie de mapa, fornecerei o ponto de saída como segundo parâmetro, e o destino como terceiro parâmetro, ela deve retornar uma string com a rota do ponto de saída, até o ponto de chegada, dai a necessidade do primeiro parâmetro, como o mapa pode se alterar, sempre forneceremos para a função calculadora de rotas, o mapa atualizado para ela poder formar e retornar a menor rota possível.
o primeiro parâmetro que ela receberá será uma listra cheia de string que identificam um segmento de rota, uma string que identifica um segmento de rotas é montada da seguinte maneira "ID1.ID2" o ponto é depois usado para separar o ID1 do ID2 com o método .split(), ambos os ID(s) no caso são identificadores de terrenos, antes mencionados, veja por exemplo na imagem, o terreno W está ligado ao terreno D, uma string que represente isso nesse caso seria "W.D", a tal listra nada mais é do que isso, ela possui varias strings dentro que identificam as rotas e os pontos juntos, uma listra que serviria de parâmetro para essa função, baseada na imagem acima ficaria da seguinte forma:
["O.H", "H.R", "E.Q", "G.A", "A.L", "K.A", "B.C", W.D, "J.I", "J.P", "M.E", etc etc etc...] é um resumo do mapa de maneira geral
ela deve inicialmente entender que existe os terrenos, ela então devera extrai-los da listra que recebera como parametro 1, ou seja, no caso do mapa acima, saber que existe os pontos A, B, C, D, E, F, G, H... as vezes eles aparecem mais de uma vez nas listra, pois por exemplo, na foto acima, é possivel ver que o ponto E se liga a mais de um terreno, então ele aparecerá mais de uma vez na listra ["E.H", "E.Q", "E.M", etc etc etc] quando visto pela primeira vez, a função pode por assim dizer, "registrar ele" e se visto depois, pode ignorar enquanto faz a primeira varredura, isso depende também de como ela procede, pode ser de outra forma, o que queremos de fato é, passar uma listra que será da forma descrita acima, esse parâmetro pode ser chamado de Map, irei depois passar duas strings/parâmetros que serão o ponto de saída e destino. vamos considerar a foto acima, supomos que devemos partir do ponto A e devemos chegar no ponto E pela menor rota possível, passamos o ponto de saída, o destino e o Map para a função, nesse caso deverá retornar a string "A.E" que representa, traduzindo para termos lógicos: iniciamos em A, movemos de A para E, fim. ela retorna a menor rota possível, agora supomos que queiramos sair de A e chegar no ponto S, a função devera nos retornar a string "A.E.Q.S" que significa: iniciamos em A, movemos de A para E, movemos de E para Q, movemos de Q para S, fim. nota, apesar de visualmente ter segmentos maiores que outros, a menor rota possível considera somente o numero de terrenos que tivermos de cruzar, se sairmos de A para D, o menor caminho seria "A.E.H.D", embora também possa existir o caminho "A.E.Q.S.U.D", ele é mais longo, portanto, inútil.
outra observação, é que haverá raras situações em que ele poderá identificar duas ou mais rotas diferentes porem com igual distancia, a função então terá de arbitrar escolhendo uma das rotas para retornar, porem não pode ser uma escolha ao acaso, imaginem um caso em um mapa no qual se sai de um ponto fictício P para um ponto fictício C, a função chega a duas menores rotas possíveis como conclusão, a rota ["P.Q.E.C"] e ["P.Q.F.C"] quando eu realizar o calculo chamando a função N vezes, todas as vezes terá de retornar a mesma rota, senão, hora no mapa será desenhada uma rota, hora será desenhada outra rota entre os terrenos, ficaria estranho, não sei ao certo como ficaria para arbitrar entre ambas as rotas, mais poderia ser feito por algum calculo, ou ordem alfabética. o primeiro e o ultimo ponto em ambas as rotas são iguais, mais os outros não, enfim, enquanto estiver sendo fornecido um mesmo mapa para a função, ela nesses casos deverá retornar a mesma resposta sempre.
gostaria de um exemplo de código, se possível, mas mais do que isso, uma explicação de como funciona esse sistema de calcular a menor rota possível. com uma função desse tipo, consigo até variar outras funções como obter uma distancia em números de segmentos de um ponto A ate B, é muitas coisas mais, se entende-la a fundo, posso fazer o inverso, criar uma função que retorna a maior rota possível ou o número de possíveis rotas distintas de ponto A ate B, interessante.
Não me considero um iniciante mais não sou profissional, consegui até fazer um bom sistema de inventario dinâmico, istanciavel com capacidade de transferência de item de um inventario a outro, mais garrei aqui, se está lendo até aqui, obrigado pela atenção.
Comment: é parecido com isso aqui, https://pt.stackoverflow.com/questions/426570/como-descobrir-todos-os-poss%c3%adveis-caminhos-para-visitar-todos-os-v%c3%a9rtices-de-um?noredirect=1#comment827743_426570
Comment: sim, é praticamente a mesma coisa, obrigado, vou ver isso mais a fundo e ver se consigo bolar uma solução inspirado nisso.
Comment: analisei o código que me mandou e fiz aqui, funciona quase certinho, é só fazer umas correções e funcionará adequadamente. obrigado. vou deixar o código abaixo para caso outras pessoas se interessem.
Answer: <code>mapa = {
     "1":"2345",
     "2":"134",
     "3":"124",
     "4":"123",
     "5":"1697",
     "6":"5g",
     "7":"508",
     "8":"07",
     "9":"5",
     "0":"87",
     "a":"bc",
     "b":"ac",
     "c":"abdg",
     "d":"ecf",
     "e":"d",
     "f":"d",
     "g":"6c",
     "h":"ij",
     "i":"hj",
     "j":"hik",
     "k":"j"}

def procurar(saida, destino, mapa):
    if len(saida) != len(set(saida)): return

    if saida[-1] == destino:
        print(saida)
        return

    for i in mapa[saida[-1]]:
        procurar(saida+i, destino, mapa)

while True:
     print()
     opc1 = input("--> saida: ")
     opc2 = input("--> destino:")
     print()

    if procurar(opc1, opc2, mapa) == None:
        print("erro, caminho não achado")

    else:
        print("SUCESSO")
</code>
não consegui por o código todo bonitinho aqui, alguém no futuro se quiser, pode editar isso a vontade, obrigado a ajuda.


Android ImageView program, how to set imageview according to random function

Question: Suppose I have 200 images with name of image are:

image1
image2
.
.
.
image200

Now I can generate random number form 1 to 200 using random function. And as all images name is identical except last numerical digit. Can I set my imageview to ( concatenate image and random number).
For example, my random number generate 20, so I will concatenate image+20 which will give me image20 and then I want to set my imageView to image20.
Answer: Try the following: (Assuming that your images are stored in the drawables folder).
1) MainActivity1.class:---------
public class MainActivity1 extends AppCompatActivity {

private ImageView iv;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout10);

    iv = (ImageView) findViewById(R.id.iv);

    // initial
    generatePicture();

    // onClick generate a different one.
    iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            generatePicture();
        }
    });

}

private void generatePicture(){

    Random r = new Random();
    int i1 = r.nextInt(200) + 1;// generates a number between 1 and 200 including both ends.

    try {
        iv.setImageDrawable(getResources().getDrawable(getResources().getIdentifier("image" + i1, "drawable", getPackageName())));
    }catch (Exception e){
        e.printStackTrace();
    }
}
}

2) layout10.xml:-------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/iv"/>

</android.support.constraint.ConstraintLayout>


How to find the center of a sphere given the radius and 3 points on the surface?

Question: I need to find the center coordinates of a sphere. I have 3 points on the surface and the radius.
Shall I use the equation of sphere: $(x_1-x)^2+(y_1-y)^2+(z_1-z)^2=r^2$  , plug in 3 points and solve the 3 equations? How can I solve such non linear equations?
Or Shall I follow the geometric approach as described here: sphere center ?
Or something else?
Thanks
Comment: Use the linked solution.
Answer: If you subtract one of the equations that you've derived from the other two, you'll get a system of two linear equations. The solution to that system is a line along which the center of the sphere must lie. You can then find the one or two points on this line that are at a distance $r$ from any of the three given surface points, which involves solving a simple quadratic equation.
However, this is pretty much what the linked solution, in particular the second one that wasn't accepted, does. The two linear equations you get above represent two of the plane bisectors of pairs of the three given points. The line p(t) in that solution is their intersection, and he even serves the solution to the final quadratic equation up on a plate.


Convert A List To Dictionary C#

Question: I've implemented a search option using Linq that works fine as follows:
string[] str = txtSearch.Text.Replace(" ", "").Split(',');

var con = (from c in context.Customer
           join d in context.CustomerType on c.CustType equals d.ID
           where str.Any(t => c.CustName.Contains(t))
           select new { c.CustomerID, c.CustName, c.CustAddress, d.Type }).ToList();

grdDetails.DataSource = con;
grdDetails.DataBind();

But I heard about Dictionary that works very well for lookup rather than List. So I've tried to do the following but doesn't get any data to show:
Edited: I've edited the following for Dictionary but it seems like if I work with EF, I have to loop through the List to get with Dictionary. By the way, there are no relation between the keys in both dictionaries. So I guess, there would be no lookup though tried in another way. It works but want to know if it's a good practice.
var dictionary = new Dictionary<int, Customer>();
dictionary.Add(1, new Customer() { CustomerID = 1, CustName = "AT", CustType = 1 });
dictionary.Add(2, new Customer() { CustomerID = 2, CustName = "AT-2017", CustType = 1 });
dictionary.Add(3, new Customer() { CustomerID = 3, CustName = "Jackson", CustType = 1 });
dictionary.Add(4, new Customer() { CustomerID = 4, CustName = "Anderson", CustType = 1 });

var dictionary2 = new Dictionary<int, CustomerType>();
dictionary2.Add(1, new CustomerType() { ID = 1, Type = "Active" });

//dictionary.Keys.Where(key => key.Contains("AT")).ToList();

var con = (from c in dictionary
           join d in dictionary2 on c.Value.CustType equals d.Value.ID
           where str.Any(t => c.Value.CustName.Contains(t))
           select new { c.Value.CustomerID, c.Value.CustName, d.Value.Type }).ToList();

grdDetails.DataSource = con;
grdDetails.DataBind();

I was trying to follow a tutorial that converts a Dictionary into List at the end. But I am not sure about it why it has done so. So I would like to know if the above way is the perfect one to do the search using Dictionary.
Note: I've used Dictionary in the console application and I understood how it works. But little bit confused to do the joining using Dictionary.
Comment: It seems like you're dealing with EF or some type of Linq to SQL provider, in which case your Linq code is just translated to SQL and the type of container wouldn't really matter.
Comment: In your first code block, why are you joining `CustType` to `ID`?  `on c.CustType equals d.ID` That doesn't seem to make sense.
Comment: First off, joining 2 **empty** dictionaries will always return empty result. Second, once you have a dictionary, there is no benefit of using LINQ join because the dictionary itself is well suited for fast lookup, and LINQ join will not use it, so basically it will be the same if you have used lists, arrays or just LINQ to Objects queries.
Comment: Thanks for the reply @juharr. Yes! I am using EF for it. So what you meant there is no need to use the `Dictionary` or not required for the above case? I was wondering if I could implement the above with `Dictionary`. Just trying to clarify.
Comment: I've edited my answer @Ivan Stoev. See if this is somewhat nearer the way I am looking for. Thanks for the comment. The `Dictionary` worked and getting data with the above edited.
Answer: The output of your query is still a list so I'm surprised the con.Values compiles.
Also, the second code example is running a query on two initialized but not populated dictionaries, so no data is a correct result.
I suspect your first code example is better if it is going against the database. It will use the database's optimization to run the query and return the results. There really wouldn't be any advantage of loading all that into memory first then running a query.
Comment: If you want a dictionary created from your query, there is a ToDictionary method that takes in Expressions that will form the key and the value for each entry. You would replace your ToList() with this.
Comment: Thanks a lot @MikeS. I am doing it for database operation or regarding database. I can understand the query is ok to work with. But curious to know if I could make it with `Dictionary`. By the way, I am using EF.
Comment: I've edited my answer @MikeS. The `Dictionary` worked and getting data but see if this is somewhat nearer the way I am looking for. Thanks again for the comment.

Convert A List To Dictionary C#


Como faço para matar um websocket?

Question: Estou com dificuldades para matar o websocket que roda dentro do meu aplicativo em java, não consigo achar respostas em nenhum lugar.
Preciso disso, pois, estou usando ele com uma extensão do chrome para preencher forms de um site, mas quando atualizo a página ou a fecho e abro novamente o servidor para de enviar novas informações ao form, então quero reinicia-lo quando necessário.
Classe ServidorExt:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servidor;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import view.painelUsuarios;

/**
 *
 * @author Neto
 */
public class ServidorExt extends WebSocketServer {

    public static String msg1;
    public static String msg2;
    public static String msg3;

    public void Verificador() {
        painelUsuarios pu = new painelUsuarios();
        msg1 = pu.getMsg1();
    }

    public void PegaMsg1() {
        msg1 = painelUsuarios.getMsg1();
    }

    public void PegaMsg2() {
        msg2 = painelUsuarios.getMsg2();
    }

    public void PegaMsg3() {
        msg3 = painelUsuarios.getMsg3();
    }

    public ServidorExt(int porta) throws UnknownHostException {
        super(new InetSocketAddress(porta));
        System.out.println("Recebendo conexões da porta: " + porta);
    }

    @Override
    public void onMessage(WebSocket webSocket, String mensagem) {

        String msgAnterior = "";
        String msgNova;

        while (true) {

            Verificador();
            msgNova = msg1;

            while (!msgNova.equals(msgAnterior)) {
                Verificador();
                msgAnterior = msg1;

                PegaMsg1();
                webSocket.send(msg1);
                System.out.println("msg 1 = "+ mensagem);

                PegaMsg2();
                webSocket.send(msg2);
                System.out.println("msg 2 = "+ mensagem);

                PegaMsg3();
                webSocket.send(msg3);
                System.out.println("msg 3 = "+ mensagem);
            }
        }
    }

    @Override
    public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
        System.out.println("A conexão foi encerrada.");
    }

    @Override
    public void onError(WebSocket arg0, Exception e) {
        System.out.println("Erro de conexão." + e);
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake arg1) {
        System.out.println("Foi iniciado uma nova conexão.");
    }

    @Override
    public void onStart() {
        System.out.println("Servidor iniciado com sucesso!");
    }

}

Essa classe é acionada pelo comando new ServidorExt(8080).start(); em outra classe no aplicativo.
Answer: De acordo com o JavaDoc da classe WebSocketServer que me parece que você está usando, basta usar o método stop no seu servidor.
O problema é que, quando você faz new ServidorExt(8080).start();, você está jogando fora a referência ao servidor que você está iniciando. Salve a referência em uma variável pra poder chamar stop() nela depois. Por exemplo:
public class MinhaOutraClasse {

    private ServidorExt servidor;

    // .....

    public void iniciarServidor() {
        this.servidor = new ServidorExt(8080);
        this.servidor.start()
    }

    public void pararServidor() {
        this.servidor.stop()
    }

    // ....

}

Nesse exemplo, você chama iniciarServidor() quando quiser iniciar e pararServidor() quando quiser parar.
Comment: Você não sabe o quanto eu procurei por isso, muito obrigado pela ajuda, outra coisa, sabe me informar o porque do servidor para de enviar novas informações ao cliente em javascript quando fecho o navegador e abro novamente, já que o mesmo encontra-se conectado ao servidor?
Comment: Sinto muito, não entendo muito do lado do Javascript. Mas fique à vontade para abrir outra pergunta aqui no site, colocando o código do lado do JavaScript e explicando a situação.
Comment: Tudo bem, já fiz isso, com toda a explicação do meu problema, mas infelizmente ninguém respondeu, mas você já foi de uma grande ajuda, obrigado!

Como faço para matar um websocket?


Probability, Odds

Question: Assume that a fund manager has no idea of hat he is doing and is essentially flipping a coin in order to make decisions.  Let's say it's a 50/50 proposition that the manager will have a "good" year.  What is the probability that the fund manager will have 6 or more good years out of 10?
Is it (1/2)^6?
Comment: That's the probability that six specified years are good.  Read up on [binomial distributions](https://en.wikipedia.org/wiki/Binomial_distribution).
Comment: Can you provide me with the answer please so I can at least check my work?
Comment: Please provide your work.  As I say, your answer is not at all correct.
Comment: So I could view this problem as, what is the probability of getting at least 6 heads on 10 flips, correct?  That would be ((1/2)^6)*((1/2)^4)?
Comment: @Marley that is the probability of getting **exactly** the first six flips to be heads and the remaining flips to be tails in ten flips., not the probability of getting **at least** six heads and not the probability of getting exactly six heads and four tails **in any order** in ten flips
Comment: Your formula is wrong even for exactly six...it gives the probability that six specified years are good and the other four specified years are bad.  to get the answer for exactly six out of ten you need to multiply by $\binom {10}6$.
Comment: I'm sorry, but what is the notation for (10  6) you have above.  Is that (10!/6!).  Thank you both for the help.
Comment: $\binom{n}{r}$ is the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient) "$n$ *choose* $r$" and counts the number of ways of selecting a subset of $r$ objects out of a set of $n$ distinct objects (*i.e. order doesn't matter*) and can be simplified algebraically as $\binom{n}{r}=\frac{n!}{r!(n-r)!}$.  The information on what the binomial coefficient is should have been included in the link to the binomial distribution which we have provided several times already to you in the past hour which you should have had the opportunity to read already by now.
Comment: What is with all the attitude @Jmoravitz?  Yes I know you have provided the wikipdia link to Binomial Distribution page.  I am currently working a full time 10 hour/day job while trying to complete this homework.  I don't have time to comb through wikipedia pages.  So take it easy on me.
Comment: So I did (10!/4!*6!)(1/2)^6*(1/2)^4.....to get about .2 or 20%.  Is this correct?
Comment: That  is still the probability of exactly six, not at least six.  Read the answer below.  "At least six" corresponds to "exactly six or exactly seven or exactly eight or ..."
Comment: So I have to add to probabilities of exactly 7 and so on?  Is the answer 37.70%?
Comment: Yes $~~~~~~~~~$
Comment: Together we can achieve more @Jmoravitz.  Now, let's go tackle the other one.  I think i can apply some the same principles.
Answer: Hint: The probability you are looking for is $$ \sum_{k=6}^{10} \binom{10}{k} \left(\frac{1}{2}\right)^k \left(\frac{1}{2}\right)^{10-k}. $$
Left for the reader to simplify the above further.

As @lulu said, read on https://en.wikipedia.org/wiki/Binomial_distribution to arrive at the above answer.

Probability, Odds


HttpClient in java

Question: I want to use a simple HttpClient.
However, it appears sun.net.www.http.HttpClient is inaccessible.
Also, com.ibm.ws.http.HTTPConnection - appears to be more supporting of http server and not client. Why? Because when I create an instance of HttpConnection, it has a "getHttpResponse" to which I am supposed to write.
Anyway to use the IBM HttpConnection for HttpClient?
Or, is there any standard httpClient code that I can use?
Comment: https://github.com/square/okhttp is a good and popular one. Very well maintained
Comment: FYI: Java 11+ has a new HTTP client implementation built-in. See [*JEP 321: HTTP Client*](https://openjdk.java.net/jeps/321).
Answer: Many people use Apache's HTTPClient.
Have a look at the first few chapters of its tutorial to see if it's what you're looking for.
If you're after something simple that's already built into Java, you can look at HttpURLConnection, which you can use to build HTTP requests (example). If you need to do anything more than just simple HTTP requests, though, HTTPClient is probably the way to go.
Answer: I highly recommend Unirest:
Unirest.post("http://httpbin.org/post")
  .queryString("name", "Mark")
  .field("last", "Polo")
  .asString()

Comment: Unirest & jcabi-http (as suggested by @yegor256) seem to be the 2 most easy to use library, and the usage are pretty similar. Do you guys know any different between the two?
Comment: Those static methods are a pain when it comes to unit testing. I'm considering replacing Unirest with OkHttp in my project as I could pass in a mocked OkHttpClient object then (instead of using PowerMock as of now). Also, OkHttp comes with a MockWebServer for integration testing.
Comment: I think this is most easy to use client
Answer: There is another option in using google-http-java-client.
This library provides a simple and flexible API together with a pluggable approach to use low-level HTTP libraries like java.net.HttpURLConnection or Apache HTTP Client.
Sample code for posting content to content from an InputStream to a specific URL:
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
InputStream is = ...;
URL url = new URL(...);
String contentType = ...;
HttpRequest httpRequest = requestFactory.buildPostRequest(
  new GenericUrl(url), new InputStreamContent(contentType, is)
);
HttpResponse execute = httpRequest.execute();

Answer: Try Apache's HTTPClient fluent API it's so easy in use!
// Execute a GET with timeout settings and return response content as String.
Request.Get("http://somehost/")
    .connectTimeout(1000)
    .socketTimeout(1000)
    .execute().returnContent().asString();

Answer: You don't need a third party class, just use java's own URL and HttpURLConnection classes.
See an example here.
Comment: Sadly the above link is dead.

HttpClient in java


Is there something called an offensive error in baseball? If not, why not?

Question: Pittsburgh Pirates just made a couple of egregious ones. Frank Cervelli doubled.
John Jaso doubled, and Frank Cervelli stopped at third, instead of scoring.
With one out, on the following play, Jordy Mercer flied out Cervelli came home. But John Jaso was "picked off" running to third, preventing the run from scoring.
Yet I didn't see these miscues scored as error. All the errors I see are defensive errors? Why is that, is that because offensive errors are so rare?
Answer: In baseball, only defensive errors are recorded. I think, in part, this is due to the nature of such errors. If the shortstop lets a ground ball go under his glove, for example, that is clear mistake for which he is at fault.
While plenty of offensive players make boneheaded baserunning mistakes, they are decidedly less common than fielding errors. Furthermore, oftentimes these mistakes are really the result of great plays by the fielders (such as the situation you describe above).
To get a runner who is tagging on a fly ball, the throw has to be in time, perfectly on line, and the tag must be applied before the runner arrives. In that situation, it is less a matter of the runner making a negative play than the fielders making positive ones.
Comment: One of the things the advanced fielding stats brigade have shown is that defensive errors are *not* clear: a shortstop with great range gets really close to a ball in the hole, but it goes under his glove: scored as an error. A shortshop with awful range (Derek Jeter, *cough*, *cough*) gets nowhere near the ball: scored as a hit. For fly balls, we know where the ball is caught and how long it takes to take to home plate, so getting quantitative stats on that should be just as possible.
Answer: These are not recorded mainly because it is hard to define what a base running error would involve. In your given situation, It could be argued that Cervelli "played it safe" by not trying to run home.
One stat you may be interested in however is TOOTBLAN, which stands for Thrown Out On The Basepaths Like A Nincompoop. They account for boneheaded "offensive errors" you are referring to. It is not an official stat, but http://tootblan.tumblr.com/ does an outstanding job recording them.
Comment: And "playing it safe" is equally an error of it stops a run being scored.
Comment: @PhilipKendall  would think any proposed offensive error would generally have to involve a player getting out, as otherwise he's still active and it was just a judgement call, which I don't believe are usually scored as errors.  That'd be the equivalent of a fielder/pitcher/catcher/etc not trying to throw a runner out at third when they quite well could have; not an error as far as I know.  If the runner stumbles and falls, clearly preventing him from scoring, that's one thing that could be an error, but a bad choice usually isn't an error as far as I know.
Comment: From a statistical point of view, no - it's an error of it reduces the team's chance of winning, whether that involves the player getting out or not. From a "trying to explain it to the average punter" point of view, something simpler may be needed though!
Comment: @Jeopardy Tempest. In both cases, one run should have scored, even though neither did. In the first case, Cervelli doubled, meaning that he should have gotten home on the Jaso double. In the second case, the runner on second should have stayed at second to protect the runner going home, because it's much easier to "nail" someone at third than at the plate. In both cases, "someone," (maybe the third base coach) made an error.
Comment: But lapses in judgement aren't errors on the defense why should they be on the offense.  Defense goes to the wrong base, causing them to miss an out (or allow run a to score), it isn't scored as an error.


Blocking ddos string with iptables

Question: I want to ask how do block spefic packet payload?
<code>14:46:35.837759 IP 126.96.36.199.27017 > x.27030: UDP, length 25
        0x0000:  4500 0035 44a4 0000 ee11 53ae 915c 100e  E..5D.....S..\..
        0x0010:  0587 8d74 6987 6996 0021 0000 7a78 4646  ...ti.i..!..zxFF
        0x0020:  ffff ff55 4ba1 d522 0043 6f75 6c64 206e  ...UK..".Could.n
        0x0030:  6f74 206f 70                             ot.op
14:46:35.837775 IP 184.108.40.206.27015 > x.27015: UDP, length 25
        0x0000:  4500 0035 44a1 0000 ee11 911e 784f ebad  E..5D.......xO..
        0x0010:  0587 8d74 6987 6996 0021 0000 7a78 4646  ...ti.i..!..zxFF
        0x0020:  ffff ff55 4ba1 d522 0043 6f75 6c64 206e  ...UK..".Could.n
        0x0030:  6f74 206f 70                             ot.op
</code>
It is Possible to block attack by blocking hex-string?
Comment: Blocking a packet with iptables is not going to magically give you back the link-time already used to send the packet to you. So all you can aim for is to process the packet as fast as possible. Handling a UDP packet targeted at a closed port is already pretty fast, so you are more likely to slow the processing down by using iptables.
Comment: Be careful. If you keep receiving such packets, but they don't harm the machine itself in any way, adding payload inspection might actually increase the load of your machine. As @lain notes, you won't free the line this way. Your command should work, but it can probably be rather easily evaded by the attacker. Adding multiple inspections like this will have even bigger performance attack.
Comment: Thanks for replay, <code> iptables --append INPUT --match string --algo kmp --hex-string '|ff ff ff 55 4b a1 d5 22 00 43 6f 75 6c 64 20 6e|' --jump DROP </code> Will that work?
Answer:
It is Possible to block attack by blocking hex-string?

No, not really. With a DDOS attack, by the time a packet gets to your machine for inspection it has done it's job - viz it has used up a portion of your network resource.
To solve a DDOS problem, you need to elicit some help from upstream.

Blocking ddos string with iptables


BCP exits with code 0

Question: When running BCP from my Java application it exits with status code 0 when 1 is expected.
I run bcp with an invalid combination of data and formatting file and bcp gives the following error:
Starting copy...
SQLState = 22005, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Invalid character value for cast  specification

BCP copy in failed

BCP however exits with exit code 0 and not 1, as i suspect. Now it is extremely difficult to see if something failed while running BCP. Exitting with the right code works once they match to some degree (like same delimiters).
Command
PS C:\Users\feh\Desktop> bcp integrate_test.dbo.AS_LOADER_DELIMITED in .\data.dat -S "10.0.0.161\SQL2K5,1048" -U user -P pass -f .\formatting.ctl -m 1

Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unexpected EOF encountered in BCP data-file

0 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 1
PS C:\Users\feh\Desktop> $lastexitcode
0

How can i validate a formatting file to the data and get a exit code 1 when they do not match?
Answer: If the bcp is "in" the consider using BULK INSERT. This does the same as bcp but can be trapped using SQL Server TRY/CATCH or normal exception handling
Otherwise, are you trapping %ERRORLEVEL% and not some other code?
Comment: I've added the command i call with the result from $lastexitcode.
Answer: In a batch file, need to SETLOCAL ENABLEDELAYEDEXPANSION in order for the errorlevel environment variable will get set.

BCP exits with code 0


Creating Daemons in Linux... how should the file permissions be?

Question: I am setting up a few PHP Gearman Daemons running on PEAR System_Daemon. I need them to be able to write to the following locations...
<code>/var/run/{APPNAME}.pid
/etc/init.d/{APPNAME}
/gearman/log/{APPNAME}.log
</code>
What permissions should I set for them? I don't mind creating a different user or what have you, but I am just not the greatest with File Permissions. I want to do this right, not chmod 777 for ease of use and running as root which is never a good idea.
Help this file permission idiot?
Answer: You can create a user:group for this daemon, and give them the permissions you need.
As root you can always
<code>sudo -u newuser $program
</code>
Comment: yes, if you're writing, you'll need to have rw access, 660 I guess
Comment: What exact chmod should I give them? Obviously init.d will need the most, but I don't want to do a blanket chmod 777...
Comment: I'd say 550 should be ok. and of course `chown $user:$group script.sh`
Comment: chmod 550 = Read + Execute for Group and Owner Right?

...wouldn't the log file need to a write flag?
Comment: Yes, the System_Daemon method writes an init.d script on first or updated startup, updates log file always, and needs to write the PID file. I'll try this later today / tomorrow and let you know if System_Daemon likes the new settings. Much better than blanket permissions :)
Comment: I hope it works, just in case, I would give blanket permissions to the logging part of the script, so that if anything goes wrong, it can be logged.
After everything works, logs can be tightened as well
Comment: Seems to work, marking it as correct, need to use 660 and not 550 for readers that came here from google