C# winform - Raise a personal event in Timer_tick event

Question: I have create a small class CountDown , that contains a timer.
Class is very simple : receive time target, and start a CountDown with a timer.
When target is reached, my personal event fire:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CountDownWithEvent
{
    public delegate void countDownFinishEventHandler(Object sender, EventArgs e);
    class CountDown
    {
        private DateTime _target;
        private System.Windows.Forms.Timer _timer;
        System.TimeSpan _timeMissing;

        public event countDownFinishEventHandler CountDownFinish;

        public CountDown(DateTime targetTime)
        {
            this._target = targetTime;
            this._timer = new System.Windows.Forms.Timer();
            this._timeMissing = new TimeSpan();
        }

        public DateTime TargetTime
        {
            get;
        }

        public TimeSpan timeMissing
        {
            get;
        }

        public void CountDownStart()
        {
            _timer.Interval = 1000;
            _timer.Tick += new EventHandler(timer_tick);
            _timer.Start();
        }

        protected virtual void timer_tick(Object sender, EventArgs e)
        {
            //if (_timer.Tick != null)
            //{
            //}
            System.DateTime now = System.DateTime.Now;
            _timeMissing = _target.Subtract(now);
            if (!(timeMissing.TotalSeconds > 0))
            {
                _timer.Stop();
                if(CountDownFinish != null)
                {
                    EventArgs b = new EventArgs();
                    CountDownFinish(this, b);
                }
            }
        }

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CountDownWithEvent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CountDown CountDown = new CountDown(new DateTime(2016, 05, 27, 14, 48, 00));
            CountDown.CountDownFinish += new countDownFinishEventHandler(onCountDown);
            CountDown.CountDownStart();
        }

        private void onCountDown(Object sender, EventArgs e)
        {
            MessageBox.Show("time expired! ");
        }
    }
}

I use EventArgs, rather than write a derived class , because I don't need any special information of the event ( to understand, parameter e)
now I'm in a situation a bit unusual :
protected virtual void timer_tick(Object sender, EventArgs e)
    {
        //if (_timer.Tick != null)
        //{
        //}
        System.DateTime now = System.DateTime.Now;
        _timeMissing = _target.Subtract(now);
        if (!(timeMissing.TotalSeconds > 0))
        {
            _timer.Stop();
            if(CountDownFinish != null)
            {
                EventArgs b = new EventArgs();
                CountDownFinish(this, b);
            }
        }
    }

When i call CountdownFinish(this,e);  the e parameter refer an timer_tick
It isn t consistent pass EventArgs timer
so I don t know how to behave ???
In fact I have instantiated new EventArgs b
            EventArgs b = new EventArgs();
            CountDownFinish(this, b);

but I don't know if this is the right path
Now i'm another problem :
I want to see in label the time left to goal. And refresh it to any timer_tick.
whereas I want to keep separated the timer logic of the program graphic..
how I can do it?
Many thanks in advance for the understanding and the help!
(sorry for bad english, isn't my language :) )
Comment: **1-** To provides a value to use with events that do not have event data use [`EventArgs.Empty`](https://msdn.microsoft.com/en-us/library/system.eventargs.empty(v=vs.110).aspx).
 **2-** Create `TimeLeft` property which shows remaining time to finish and decrease it in the timer tick event. Also create `TimeLeftChanged` event which fires when `TimeLeft` changes.
Comment: In the form, subscribe `TimeLeftChanged` event of your component and in the method which handles the event set the text of label to value of `TimeLeft` property of the component.
Comment: If you solved your problem don't add another question to the same post, ask new one instead.
Comment: thank for ask.. but  i haven't solved...
the first is a doubt .. the second is the problem
Comment: @RezaAghaei thanks.
If i create a property that decrease ... how to refresh label ?! This is the passage that I miss ( I hope to have past my difficulty) .. Whereas `CountDown` and `Form` is a separate class...`Also create TimeLeftChanged event which fires when TimeLeft changes`  with this solution how to pass data to label ? create a member class in `CountDown` type label ?
Comment: thanks @RezaAghaei . Below , write _solution_ ...
if you mean other ways or other to improve this solution I'll listen gladly :)
Comment: @RezaAghaei if u have a possibility , read my solution and question that
followed in bottom..
Comment: @rul3z Sure, I checked it. Sorry, I couldn't remember why I missed your comment at Jun 1. Probably I was in middle of answering another question and I saw other notifications but didn't see it. Sorry for late reply :)
Answer: @Reza Aghaei
ok, this is my solution ..
What do you think ?!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventsTry
{
    public delegate void countDownFinishEventHandler(Object sender, EventArgs e);
    public delegate void TimeLeftChangedEventHandler(Object sender, TimeLeftDateEventArgs e);
    class CountDown
    {
        private DateTime _target;
        private System.Windows.Forms.Timer _timer;
        System.TimeSpan _timeMissing;

        public event countDownFinishEventHandler CountDownFinish;
        public event TimeLeftChangedEventHandler TimeLeftChanged;

        public CountDown(DateTime targetTime)
        {
            this._target = targetTime;
            this._timer = new System.Windows.Forms.Timer();
            this._timeMissing = new TimeSpan();
        }

        public DateTime TargetTime
        {
            get { return this._target; }
        }

        public TimeSpan timeMissing
        {
            get { return this._timeMissing; }
        }

        public void CountDownStart()
        {
            _timer.Interval = 1000;
            _timer.Tick += new EventHandler(timer_tick);
            _timer.Start();
        }

        protected virtual void timer_tick(Object sender, EventArgs e)
        {
            System.DateTime now = System.DateTime.Now;
            _timeMissing = _target.Subtract(now);

            if (!(timeMissing.TotalSeconds > 0))
            {
                _timer.Stop();

                if (CountDownFinish != null)
                {
                    CountDownFinish(this, EventArgs.Empty);
                }
            }
            else
            {
                if (TimeLeftChanged != null)
                {
                    TimeLeftChanged(this, new TimeLeftDateEventArgs(timeMissing));
                }
            }
        }

    }

    public class TimeLeftDateEventArgs : EventArgs
    {
        private int _hours;
        private int _minutes;
        private int _seconds;

        public TimeLeftDateEventArgs(TimeSpan timespan)
        {
            _hours = timespan.Hours;
            _minutes = timespan.Minutes;
            _seconds = timespan.Seconds;

        }

        public int Hours
        { get { return this._hours; } }

        public int Minutes
        { get { return this._minutes; } }

        public int Seconds
        { get { return this._seconds; } }

    }

}

form class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EventsTry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CountDown CountDown = new CountDown(new DateTime(2016,06,01,11,35,00));
            CountDown.CountDownFinish += new countDownFinishEventHandler(onCountDown);
            CountDown.TimeLeftChanged += new TimeLeftChangedEventHandler(onTimeLeft);
            CountDown.CountDownStart();
        }

        private void onCountDown(Object sender, EventArgs e)
        {
            MessageBox.Show("time expired! ");
        }

        private void onTimeLeft(Object sender, TimeLeftDateEventArgs e)
        {
            label1.Text = e.Hours + ":" + e.Minutes + ":" + e.Seconds;
        }
    }
}

I know that delegate countDownFinishEventHandler it's equal to EventHandler.
I haven t changed out of laziness.
I wanted to use an inner class to TimeLeftDateEventArgs but public delegate is extern to class CountDown then TimeLeftDateEventArgs isn't not accessible to delegate.

2- Create TimeLeft property which shows remaining time to finish and decrease it in the timer tick event.

you meant this solution ? or other way !?
Comment: You are almost there. To create a custom event use [such solution](http://stackoverflow.com/a/36130796/3110834). But instead of `EventHandler` use `public event EventHandler TimeLeftChanged;`. Also if your `TimeLeftChangedEventArgs` contains enough information, you don't need any other properties for the class. The property which I mentioned in comments was for gaining information which you currently have in your event arg and you can use theme to show on label.
Comment: So to make the answer more useful, edit the answer and add event in the right way.


Node template engine that can include other templates?

Question: Starting to get into node but struggling to pick a template engine..
Is there an engine out there that can include other templates in the same twig can?
EG:
<code>{% include 'template.html' with {'foo': 'bar'} %}
</code>
Comment: EJS is what I use now, exactly because of Jade's funkiness (and lack of good docs - at least when I was trying it out). Plus, coming from a Java/C# asp.net background, the conventions were immediately familiar.
Comment: If you're looking to set a general common page format (headers/footers, etc.) with each page having custom content, Jade will do that (I've used it on a project and liked it Ok...). If you're looking for page fragments a la java server pages that can be inserted anywhere in another page... jQuery has some options - (haven't used any on a project, so can't comment..)
Comment: Ok cool i will take a look.. I did look at jade but the syntax was a little funky. Would you recommend ejs?
Comment: I think ejs it is then. Thanks,  John
Answer: I went with this in the end:
http://paularmstrong.github.io/swig/
I is a port of twig to js.. absolutely awesome and does exactly what you would expect from a twig.
UPDATE: It swig ha since been deprecated in favor of:
https://mozilla.github.io/nunjucks/
Answer: I recommend a new template engine: Saker, it enables fluid coding workflow, unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML.
Saker is my personal open source project.
Github: https://github.com/eshengsky/saker
Comment: @MartijnPieters got it!


Navigation animated underline from right to left

Question: I need to make a navigation where on hover line appears from left to right and then on hover out it goes back to left.
I have got that far that I have it but it moves from left to right and then dissapears to the right, but I need it to go back to the left

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}

.underline:after {
  content: "";
  position: absolute;
  right: 0;
  width: 0;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}

.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  left: 0;
  right: auto;
  width: 100%;
}
underline

So my desired result is that the underline goes back to the left on hover out.
Thanks!
Comment: what you want is easier than what you have: simply change the width on hover for 0 to 100%
Answer:
So my desired result is that the underline goes back to the left on hover out.

That only needs one single change in the stylesheet - position it from the left, instead of the right, to begin with.

.underline {
  display: inline;
  position: relative;
  overflow: hidden;
}

.underline:after {
  content: "";
  position: absolute;
  left: 0; /* was: right: 0 */
  width: 0;
  bottom: -5px;
  background: #000;
  height: 4px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}

.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  /* left: 0; */ /* redundant now */
  /* right: auto; */ /* redundant now */
  width: 100%;
}
underline
Answer: Just change transform-origin:100% 0 for hover element,So the underline comes from right to left. If you apply transform-origin:0 100%  the undeline moves from left to right

.expand{
  position:relative;
  text-decoration:none;
  display:inline-block;
}
.expand:after {
  display:block;
  content: '';
  border-bottom: solid 3px #000;
  transform: scaleX(0);
  transition: transform 250ms ease-in-out;
  transform-origin:100% 50%
}
.expand:hover:after {
  transform: scaleX(1);
  transform-origin:100% 0;
}
 Underline
Answer: As the CSS god @TemaniAfif pointed out, simply get rid of all right definitions in both states, instead use left: 0; in the default state, and you're there:

.underline {
  overflow: hidden;
  position: relative;
}

.underline:after {
  background: #000;
  bottom: -5px;
  content: "";
  height: 4px;
  left: 0;
  position: absolute;
  transition: width .3s ease-out;
  width: 0;
}

.underline:hover:after,
.underline:focus:after,
.underline:active:after {
  width: 100%;
}
underline


Error: The apk has permissions that require a privacy policy set for the app, e.g: android.permission.CAMERA

Question: Estou tentando publicar um APP na minha lojas de testes, o build funciona normal, mas quando tento publicar na loja aparece o erro descrito acima.
Pelo que tenho visto é necessário informar no Google Play Console uma politica de privacidade porque no meu caso estou tentando utilizar o recurso da câmera, segundo esse artigo: How to fix Google Play Developer policy violation: Action Required Policy issue

O Google Play exige que os desenvolvedores forneçam uma política de
  privacidade válida quando o aplicativo solicitar ou manipular
  informações confidenciais de usuários ou dispositivos. Seu aplicativo
  solicita permissões confidenciais (por exemplo, câmera, microfone,
  contas, contatos ou telefone ) ou dados do usuário , mas não inclui
  uma política de privacidade válida.

No artigo diz para seguir os seguintes passos:

Vá para o seu Console do desenvolvedor do Google Play.
Selecione um aplicativo.
Selecione a listagem de lojas.
Em Política de Privacidade, insira o URL no qual você tem a
política de privacidade hospedada on-line.
Selecione Salvar rascunho (novos aplicativos) ou Enviar atualização
(aplicativos existentes). "

Eu não encontrei dentro do console a parte que diz: Selecione a listagem de lojas, onde eu poderia encontra-lá?
Answer: Após realizar a seleção do aplicativo:

Abra o menu lateral tem uma opção chamada Presença na Loja.
Clique em Detalhes do App.
No final da página de Detalhes do App você encontrará o local para
inserir a URL da sua politica de privacidade.
Comment: Muito obrigado, funcionou. Pqp tava na minha cara e não via rs!
Comment: Essa interface de manuteção dos apps é bem complicada msm. Valeu


How many solutions are possible to this equation?

Question: Given
$$A+2B+3C=N
$$
where $N$ is a given positive integer.
$A ,B,C\in\mathbb{N}$ vary from $0$ to $\infty$.
How many solutions will be there to this equation?
Comment: Please try and format your questions using $\LaTeX$ notation, and avoid non-standard abbreviations.
Comment: $N+3-1\choose{3-1}$ , it isn't possible I suppose?
Comment: Are $A,B,C$ also *integers*?
Comment: Yes A,B,C are intergers
Comment: @Berci ,ABC are integrs
Comment: @Inceptio: Answer for N=8 is 10
Comment: Take $2B=x_1, 3B=x_2$. Then you get $x_1=(0,1,..N)$, Now choose every 2 out of it, since $x_1$ is even. And similarly for $x_2$.
Comment: @Inceptio:    Any formula you could find?
Comment: I'm trying to deduce one!
Comment: @Inceptio: I think we can multiply multinomial here
Comment: @I think the answer is (n+3)*(n+3)/12
Comment: @user1907531 I don't think that's right. For $n = 1$ that would give $4/3$, which doesn't make sense.
Comment: Seems to be related to http://math.stackexchange.com/questions/334972/ ...
Answer: It appears to be sequence A001399 at the Online Encyclopedia of Integer Sequences, where the simple formula $${\rm round}{(n+3)^2\over12}$$ is given, along with lots of interpretations, links, references, and so on.
Answer: Let $X=C, Y=B+C, Z=A+B+C$, then this is equivalent to finding the number of non-negative integer solutions to $X+Y+Z=N$ s.t. $X \leq Y \leq Z$.
First ignore the restriction on $X, Y, Z$. In total we have $\binom{N+2}{2}$ solutions.
The number of solutions with $Y=Z$ is just the number of non-negative integer solutions to $2Y \leq N$, giving $\lfloor \frac{N}{2} \rfloor+1$. By symmetry we get the same number of solutions for $X=Y, X=Z$.
The number of solutions for $X=Y=Z$ is 1 if $3 \mid N$ and 0 otherwise. We can represent this as $1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil$.
The number of solutions with exactly 2 variables equal is thus $3[(\lfloor \frac{N}{2} \rfloor+1)-(1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil)]$.
Now going back to the problem, each solution where $X<Y<Z$ corresponds to 6 solutions where $X, Y, Z$ are distinct. Each solution with $X \leq Y \leq Z$ and exactly 2 of them equal corresponds to 3 solutions where exactly 2 of them equal but without the condition $X \leq Y \leq Z$.
We thus get:
\begin{align}
& \frac{\binom{N+2}{2}-3(\lfloor \frac{N}{2} \rfloor+1)+2(1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil)}{6} \\
& +\frac{3(\lfloor \frac{N}{2} \rfloor+1)-3(1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil)}{3} +(1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil) \\
& =\frac{\binom{N+2}{2}+3(\lfloor \frac{N}{2} \rfloor+1)+2(1-\lceil \frac{N}{3}-\lfloor \frac{N}{3} \rfloor \rceil)}{6}
\end{align}
Comment: This is what I was tryna do(Use greatest int func).:). +1 Great solution.
Answer: The result will be equal to the coeeficient of $x^{n}$ in $(x+x^{2}+x^{3}+\dots)(x^{2}+x^{4}+\dots)(x^{3}+x^{6}+\dots)$


LinkedIn Signin script won't work on PHP page - only HTML pages

Question: Part of the login script for the linkedIn API reads as follows:

Unfortunately, when I save the page as a .php file, the <?js piece of the code is throwing an error. However, if I save the file as .html, there is no error and the login with linkedIn button shows up just fine.
Am I missing something obvious here? Is there a way to put this button on a php page?
For reference, the error that I'm seeing reads:

Parse error: syntax error, unexpected '='
Answer: try:

Comment: Works perfectly - why wouldn't they make a php friendly demo though?
Comment: The php interpreter interprets the file, and "), so you have to escape it somehow.
Comment: Or disable php short tags and use <?php tags instead of just <?


get error on click on last checkbox in list view

Question: I have a strange problem..I have a list view that contains checkboxes..I want user select them and then I get selected items neme and add them to a loop..I used ArrayAdapter to do that every think is good but when I check last item for the first time I get error but If I check other checkboxes for the first time I didnot get error..Here Is on clicklistener
    package co.tosca.persianpoem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class InteractiveArrayAdapter extends ArrayAdapter<String> {

      private final List<String> list;
      private final Activity context;
      public ArrayList<String> items = new ArrayList<String>();
      public ArrayList<String> main_db_id = new ArrayList<String>();
      public List<String> database_ids = new ArrayList<String>();

      public InteractiveArrayAdapter(Activity context, List<String> list) {
        super(context, R.layout.database_list_item, list);
        this.context = context;
        this.list = list;
        persian_poem_class main=new persian_poem_class(context);
        String mySQL = "SELECT DISTINCT id as _id "+","+ClubCP.COLUMN_POET_ID+","+ClubCP.COLUMN_PARENT_ID
                + " from cat"
                + " where " + ClubCP.COLUMN_PARENT_ID+"= 0 "
                + " order by " + ClubCP.COLUMN_POET_ID;
        Cursor c= main.getData(mySQL);

        c.moveToFirst();
        while(!c.isAfterLast()) {
            main_db_id.add(c.getString(c.getColumnIndex(ClubCP.COLUMN_POET_ID))); //add the item
             c.moveToNext();
        }
        Log.i("main_db_id", main_db_id.toString());
        File path=new File(ClubCP.SDcardPath+"/temp/database/");
       database_ids =   main.directoryPath(path,true);
        Log.i("database_ids", database_ids.toString());
      }

      public ArrayList<String> getSelectedItems(){
      return items;
      }

      @Override
      public View getView (int position, View convertView, ViewGroup parent) {
          View itemView = convertView ;
          final int pos =position;
            if (itemView == null) {

            LayoutInflater inflator = context.getLayoutInflater();
            itemView = inflator.inflate(R.layout.database_list_item, null);

            CheckBox cb = (CheckBox)itemView.findViewById(R.id.chk_database_list_item);
            TextView tv =(TextView)itemView.findViewById(R.id.txt_database_status);
            Log.i("aray adapter","set caption");
            cb.setText(list.get(position));

            for(int i=0;i<database_ids.size();i++){
                boolean found = false;
                for(int j=0;j<main_db_id.size();j++){
                        if((database_ids.get(position).equals(main_db_id.get(j)))){
                                found = true;
                                break;
                        }
                }
                if(found) {
                        tv.setText(context.getString(R.string.is_in_db));
                        tv.setTextColor(Color.parseColor(context.getString(R.color.red)));
                } else {
                    tv.setText(context.getString(R.string.is_not_in_database));
                    tv.setTextColor(Color.parseColor(context.getString(R.color.green)));
                }
        }

            cb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckBox myCb = (CheckBox)v;

                    if (myCb.isChecked()) {
                        items.add(pos, list.get(pos));
                        Toast.makeText(context, items.toString(), 1).show();
                    } else {
                        items.remove(pos);
                    }
                }
            });
            }
            return itemView;
        }
    }

and here Is error
04-10 10:24:51.722: E/AndroidRuntime(1938): FATAL EXCEPTION: main
04-10 10:24:51.722: E/AndroidRuntime(1938): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
04-10 10:24:51.722: E/AndroidRuntime(1938):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at java.util.ArrayList.add(ArrayList.java:143)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at co.tosca.persianpoem.InteractiveArrayAdapter$1.onClick(InteractiveArrayAdapter.java:97)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.view.View.performClick(View.java:3534)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.widget.CompoundButton.performClick(CompoundButton.java:104)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.view.View$PerformClick.run(View.java:14263)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.os.Handler.handleCallback(Handler.java:605)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.os.Looper.loop(Looper.java:137)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at android.app.ActivityThread.main(ActivityThread.java:4441)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at java.lang.reflect.Method.invokeNative(Native Method)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at java.lang.reflect.Method.invoke(Method.java:511)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-10 10:24:51.722: E/AndroidRuntime(1938):     at dalvik.system.NativeStart.main(Native Method)

It says out of bundry so I think problem Is with add items in listview but dont know why :(
and here is a new logcat
04-10 20:23:14.947: D/dalvikvm(7732): GC_FOR_ALLOC freed 45K, 3% free 7646K/7875K, paused 23ms
04-10 20:23:14.947: I/dalvikvm-heap(7732): Grow heap (frag case) to 8.968MB for 1536016-byte allocation
04-10 20:23:14.977: D/dalvikvm(7732): GC_CONCURRENT freed <1K, 3% free 9145K/9415K, paused 1ms+1ms
04-10 20:23:15.097: D/libEGL(7732): loaded /system/lib/egl/libGLES_android.so
04-10 20:23:15.117: D/libEGL(7732): loaded /system/lib/egl/libEGL_adreno200.so
04-10 20:23:15.137: D/libEGL(7732): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
04-10 20:23:15.147: D/libEGL(7732): loaded /system/lib/egl/libGLESv2_adreno200.so
04-10 20:23:15.227: I/Adreno200-EGLSUB(7732): <ConfigWindowMatch:2078>: Format RGBA_8888.
04-10 20:23:15.247: D/OpenGLRenderer(7732): Enabling debug mode 0
04-10 20:23:17.087: D/dalvikvm(7732): GC_FOR_ALLOC freed 13K, 3% free 9167K/9415K, paused 12ms
04-10 20:23:17.097: I/dalvikvm-heap(7732): Grow heap (frag case) to 10.454MB for 1536016-byte allocation
04-10 20:23:17.127: D/dalvikvm(7732): GC_CONCURRENT freed <1K, 3% free 10667K/10951K, paused 2ms+5ms
04-10 20:23:17.177: D/TextLayoutCache(7732): Using debug level: 0 - Debug Enabled: 0
04-10 20:23:17.197: I/Adreno200-EGLSUB(7732): <ConfigWindowMatch:2078>: Format RGBA_8888.
04-10 20:23:17.338: D/OpenGLRenderer(7732): Flushing caches (mode 0)
04-10 20:23:19.057: I/file_list(7732): [khiam.db, prvin-aEtsami.db]
04-10 20:23:19.057: I/main_db_id(7732): [3]
04-10 20:23:19.077: I/database_ids(7732): [3, 8]
04-10 20:23:19.087: I/aray adapter(7732): set caption
04-10 20:23:19.107: I/Adreno200-EGLSUB(7732): <ConfigWindowMatch:2078>: Format RGBA_8888.
04-10 20:23:19.117: I/aray adapter(7732): set caption
04-10 20:23:19.137: I/aray adapter(7732): set caption
04-10 20:23:19.297: D/OpenGLRenderer(7732): Flushing caches (mode 0)
04-10 20:23:20.387: I/getSelectedItems_befor(7732): []
04-10 20:23:20.387: I/list(7732): [khiam.db, prvin-aEtsami.db]
04-10 20:23:20.387: D/AndroidRuntime(7732): Shutting down VM
04-10 20:23:20.387: W/dalvikvm(7732): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
04-10 20:23:20.397: E/AndroidRuntime(7732): FATAL EXCEPTION: main
04-10 20:23:20.397: E/AndroidRuntime(7732): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
04-10 20:23:20.397: E/AndroidRuntime(7732):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at java.util.ArrayList.add(ArrayList.java:143)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at co.tosca.persianpoem.InteractiveArrayAdapter$1.onClick(InteractiveArrayAdapter.java:102)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.view.View.performClick(View.java:3534)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.widget.CompoundButton.performClick(CompoundButton.java:104)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.view.View$PerformClick.run(View.java:14263)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.os.Handler.handleCallback(Handler.java:605)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.os.Looper.loop(Looper.java:137)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at android.app.ActivityThread.main(ActivityThread.java:4441)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at java.lang.reflect.Method.invokeNative(Native Method)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at java.lang.reflect.Method.invoke(Method.java:511)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-10 20:23:20.397: E/AndroidRuntime(7732):     at dalvik.system.NativeStart.main(Native Method)

Comment: What's the structure of `main_db_id`?
Answer: items = ( items == null ) ? new ArrayList<Object>(list.size) : items;

Do this while initializing the item. Hope this will help. You are trying to add an Item to an ArrayList that doesn't have the position that you are mentioning in the add Command. Try to add the above line as the first statement in your getView method. And also Instead of add use items.set(pos, list.get(pos));
Comment: I tried this but I get "The blank final field list may not have been initialized"
Comment: It should be inside getView method
Comment: I added your code but still get error..what If I use an if statement ?
Comment: Thanks for your help I must change your code to use it ..I changed it to `items = ( items == null ) ? new ArrayList(list.size()) : items;` but I still get same error..
Comment: Thanks my friend..I added it to my question


Erro - JSF e PrimeFaces

Question: Erro ao tentar cadastrar usuário, aparece a seguinte mensagem:
accordion:dtNasc: '22-02-1990' could not be understood as a date.

XHTML:

<f:convertDateTime pattern="dd/MM/yyyy" />

Classe Funcionario
@NotEmpty(message = "O campo data de nascimento é obrigatório.")
@Column(name = "fun_dt_nasc", nullable = false)
private String dt_nasc;

public String getDt_nasc() {
    return new SimpleDateFormat("dd/MM/yyyy").parse(getDt_nasc());
}
public void setDt_nasc(String dt_nasc) {
    setDt_nasc(new SimpleDateFormat("dd/MM/yyyy").format(dt_nasc));
}

No meu get ele dá um erro:
Type mismatch: cannot convert from Date to String
Comment: Qual é o tipo do atributo dt_nasc na classe funcionario?
Comment: Ele é String...
private String dt_nasc;
Comment: Calendar precisa que o atributo seja do tipo Date
Answer: Como vc disse, seu atributo dt_nasc é do tipo String e o Calendar precisa que seja do tipo Date.
Ou você troca isso ou cria um método para converter, por exemplo:
public Date getDtNasc(){
    return new SimpleDateFormat("dd/MM/yyyy").parse(getDt_nasc());
}
public void setDtNasc(Date data){
    setDt_nasc(new SimpleDateFormat("dd/MM/yyyy").format(data));
}

E no seu xhtml:

    <f:convertDateTime pattern="dd/MM/yyyy" />

Comment: Nilson, não conseguir cadastrar mudando o atribuito para Date, e quando coloco igual vc fez no get e set dá erro... Vou postar no código acima....

Erro - JSF e PrimeFaces


Aplicando o scroll em tabela mantendo o cabeçalho fixo

Question: Estava procurando uma forma de aplicar o scroll vertical e horizontal mantendo o cabeçalho fixo para minha tabela.
Encontrei nesse fiddle uma possível solução para este caso.

$('table').on('scroll', function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});
html {
    font-family: verdana;
    font-size: 10pt;
    line-height: 25px;
}
table {
    border-collapse: collapse;
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead {
    background-color: #EFEFEF;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
    height: 25px;
    border: dashed 1px lightblue;
}

            Column 1
            Column 2
            Column 3
            Column 4
            Column 5

            Row 1
            Row 1
            Row 1
            Row 1
            Row 1

            Row 2
            Row 2
            Row 2
            Row 2
            Row 2

            Row 3
            Row 3
            Row 3
            Row 3
            Row 3

            Row 4
            Row 4
            Row 4
            Row 4
            Row 4

            Row 5
            Row 5
            Row 5
            Row 5
            Row 5

            Row 6
            Row 6
            Row 6
            Row 6
            Row 6

            Row 7
            Row 7
            Row 7
            Row 7
            Row 7

            Row 8
            Row 8
            Row 8
            Row 8
            Row 8

            Row 9
            Row 9
            Row 9
            Row 9
            Row 9

            Row 10
            Row 10
            Row 10
            Row 10
            Row 10

Quando tento passar o trecho de código acima para meu arquivo.html ele não exibe corretamente o scroll horizontal.
Não entendo por que no fiddle funcionou e no meu arquivo não funciona.
Answer: Seu script jquery está rodando antes da pagina, é só colocar o script no final que resolve o problema.
Answer:

$('table').on('scroll', function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});
html {
    font-family: verdana;
    font-size: 10pt;
    line-height: 25px;
}
table {
    border-collapse: collapse;
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead {
    background-color: #EFEFEF;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
    height: 25px;
    border: dashed 1px lightblue;
}

            Column 1
            Column 2
            Column 3
            Column 4
            Column 5

            Row 1
            Row 1
            Row 1
            Row 1
            Row 1

            Row 2
            Row 2
            Row 2
            Row 2
            Row 2

            Row 3
            Row 3
            Row 3
            Row 3
            Row 3

            Row 4
            Row 4
            Row 4
            Row 4
            Row 4

            Row 5
            Row 5
            Row 5
            Row 5
            Row 5

            Row 6
            Row 6
            Row 6
            Row 6
            Row 6

            Row 7
            Row 7
            Row 7
            Row 7
            Row 7

            Row 8
            Row 8
            Row 8
            Row 8
            Row 8

            Row 9
            Row 9
            Row 9
            Row 9
            Row 9

            Row 10
            Row 10
            Row 10
            Row 10
            Row 10

Embora possa parecer que a ordem seja conforme mostrado acima dentro da sua pagina, clica em executar e dentro dessa area clica com o direito do mouse e selecione exibir código fonte e repare onde está localizado o trecho de código

 $('table').on('scroll', function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});

dentro do html

Considerações ##  Fonte
Se você tentar acessar algum elemento do DOM ainda no head da página, ele não existirá e um erro acontecerá. Por isso a recomendação de se colocar o script antes de fechar a tag body.
CONTUDO, quem usa jQuery pode usar um recurso da biblioteca (que podemos fazer com JS puro se assim quisermos) que permite carregar o script no head, mas sua execução é feita apenas quando o DOM é montado (exceto o carregamento de imagens, que o jQuery não espera). Essa sintaxe pode ser:
$(document).ready(function() {
// seu código aqui
});

Answer: Sei que é antigo este assunto, mas fiz uma busca e achei este e acabei que fazendo uns ajustes para quem usa bootstrap5.
Nada melhor que retribuir postando as melhorias, é somente incluir os scripts abaixo no HEAD!
Espero que ajude!
-JAVA-SCRIPT/Jquery-
        $('table').on('scroll', function () {

            $("table > *")

               .width(

                    $("table")
                   .width() + $("table")
                   .scrollLeft()

                );
        });

-/JAVA-SCRIPT/Jquery-
-STYLE/CSS-
        table_head_fix {
            border-collapse: collapse;
            width: 100vw;
            max-width: 100vw;
            overflow-x: scroll;
            display: block;
        }
        thead {
        }
        thead, tbody {
            display: block;
        }
        tbody {
            overflow-y: scroll;
            overflow-x: hidden;
            height: 30vh;
        }
        td, th {
            min-width: 5vw;
            width: 50vw;
            max-width: 100vw;
            height: 5vh;
        }

-/STYLE/CSS-


Why is Python's scikit-learn LDA not working correctly and how does it compute LDA via SVD?

Question: I was using the Linear Discriminant Analysis (LDA) from the scikit-learn machine learning library (Python) for dimensionality reduction and was a little bit curious about the results. I am wondering now what the LDA in scikit-learn is doing so that the results look different from, e.g., a manual approach or an LDA done in R. It would be great if someone could give me some insights here.
What's basically most concerning is that the scikit-plot shows a correlation between the two variables where there should be a correlation 0.
For a test, I used the Iris dataset and the first 2 linear discriminants looked like this:
IMG-1. LDA via scikit-learn

This is basically consistent with the results I found in the scikit-learn documentation here.
Now, I went through the LDA step by step and got a different projection.
I tried different approaches in order to find out what was going on:
IMG-2. LDA on raw data (no centering, no standardization)

And here would be the step-by-step approach if I standardized (z-score normalization; unit variance) the data first. I did the same thing with mean-centering only, which should lead to the same relative projection image (and which it indeed did).
IMG-3. Step-by-step LDA after mean-centering, or standardization

IMG-4. LDA in R (default settings)
LDA in IMG-3 where I centered the data (which would be the preferred approach) looks also exactly the same as the one that I found in a Post by someone who did the LDA in R

Code for reference
I did not want to paste all the code here, but I have uploaded it as an IPython notebook here broken down into the several steps I used (see below) for the LDA projection.

Step 1: Computing the d-dimensional mean vectors $$\mathbf m_i = \frac{1}{n_i} \sum\limits_{\mathbf x \in D_i}^n \; \mathbf x_k$$
Step 2: Computing the Scatter Matrices
2.1 The within-class scatter matrix $S_W$ is computed by the following equation:
$$S_W = \sum\limits_{i=1}^{c} S_i = \sum\limits_{i=1}^{c}  \sum\limits_{\mathbf x \in D_i}^n (\mathbf x - \mathbf m_i)\;(\mathbf x - \mathbf m_i)^T$$
2.2 The between-class scatter matrix $S_B$ is computed by the following equation:
$$S_B = \sum\limits_{i=1}^{c} n_i (\mathbf m_i - \mathbf m) (\mathbf m_i - \mathbf m)^T$$
where $\mathbf m$ is the overall mean.
Step 3. Solving the generalized eigenvalue problem for the matrix $S_{W}^{-1}S_B$
3.1. Sorting the eigenvectors by decreasing eigenvalues
3.2. Choosing k eigenvectors with the largest eigenvalues. Combining the two eigenvectors with the highest eigenvalues to construct our $d \times k$-dimensional eigenvector matrix $\mathbf W$
Step 5: Transforming the samples onto the new subspace $$\mathbf y = \mathbf W^T \times \mathbf x.$$
Comment: I haven't gone through to look for the differences, but you can see exactly what scikit-learn is doing [in the source](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/lda.py).
Comment: It looks like they are also standardizing (centering and then scaling via division by the standard deviation). This, I would expect a result similar to the one in my 3rd plot (and the R) plot...hmm
Comment: Weird: the plot you obtained with scikit (and the one they show in their documentation) does not make sense. LDA always yields projections that have correlation zero, but obviously there is a *very strong* correlation between scikit's projections on discriminant axes 1 and 2. Something is clearly wrong there.
Comment: @ameoba Yes, I think so too. What's also weird is that the same plot I am showing for scikit is in the example documentation: http://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_vs_lda.html That makes me think that my usage of scikit it correct, but that there is something odd about the LDA function
Comment: @SebastianRaschka: Yes, I noticed. It is weird indeed. However, notice that the first of your own (non-scikit) LDA plots also shows non-zero correlation and hence something must be wrong with it as well. Did you centre the data? Projection on the second axis does not seem to have zero mean.
Comment: I believe it is the effect of the scaling of the axes on the first pic. If you pull the pic up/down to add it much more height, you'll see the same as on the other pics. I expect. It is probable that scikit makes some (unnecessary) scaling of discriminant scores to the eigenvalues (which are very different for the two discriminants in your case).
Comment: I'm not R user, but I think the only original, correct R output among the two is the second one (Pic No.3). Variables centered or standardized, no matter, the pic should be the same. Discriminants as variables are centered and uncorrelated. Pic No.2 looks like Pic No.3 to which constants (levels) were added, different for different groups.
Comment: @ttnphns: But surely no amount of scaling can turn zero correlation into strong correlation!
Comment: @amoeba, Discriminant scores are uncorrelated only when they are displayed properly, i.e. with data cloud centered. Pic No.2 is strange. Was there different shifts applied to the classes by by Y axis, or was there some sort of rotation? I don't know (and wouldn't care much).
Comment: @amoeba, it really can be rotation (plus constand addition). Results are sometimes rotated in LDA. I just did the analysis in SPSS with varimax rotation of the coefficients; and the plot of the scores look quite similar to the OP's.
Comment: Thanks for all your comments. I thought that it would be easiest to add descriptive headings to the images where everyone can see it. This should also answer the question about standardization and centering :). @ameoba It would be great if you could add the SPSS results as 5th image to as edit to my question or as a separate answer. I think that would be very helpful for this discussion
Comment: @SebastianRaschka, I had shown LDA of iris data results, obtained in SPSS, here: http://stats.stackexchange.com/a/83114/3277
Comment: @SebastianRaschka, regarding your second figure: I don't think it makes any sense to project the data without centring it first. The LDA axes are found via covariance matrices, and the means are subtracted to compute them. So you should also subtract the means before projecting the data (standardizing is optional though, that is another issue). I would replace your Figure 2, if I were you. Regarding the scikit analysis, we should contact the developers and ask them (or look in the code). I might do it later. I am sure it is *not* about varimax rotation, btw.
Comment: @SebastianRaschka: Also, I found your question on StackOverflow. Cross-posting is [very much discouraged](http://meta.stackexchange.com/questions/64068) on the StackExchange network. Please consider either removing one of your questions, or modifying one of them so that they are not almost identical anymore. Maybe you can leave this question as is (i.e. about which analysis is correct) and phrase the one on StackOverflow as a short bug report (consisting of the first paragraphs, Figure 1, and a link here)? Just an idea.
Comment: Note that there is also a visualization issue in this figure! So, within-class correlation in linear discriminants should be minimal! And this property is satisfied although it may look that LD1 & LD2 are correlated for each class, but they are not! It's just that LD1 has 5 times higher range than LD2 so class distributions don't look spherical!
Comment: @VahidMir: I am not sure I understand what you mean. If a distribution is spherical then after scaling it might look elliptic, but *not diagonally stretched*! There certainly *is* a correlation between LD1 and LD2 within each class on Figure 1.
Comment: @ameoba: I changed the post on StackOverflow entirely now. I   cross-posted it initially because I thought that the audience might be a largely different one: statisticians, machine learning people here, and more programmers on StackOverflow: I didn't know that it was discouraged and I will definitely refrain from cross posting in future.
Comment: For convenience: here is [the StackOverlow discussion](http://stackoverflow.com/questions/25003427).
Comment: As an update in 2018 - there is still an open bug with the Sklearn implementation in the case of more than 2 classes. https://github.com/scikit-learn/scikit-learn/issues/6848 And I am not getting the right results for 3 classes on the IRIS dataset.
Answer: Update: Thanks to this discussion, scikit-learn was updated and works correctly now. Its LDA source code can be found here. The original issue  was due to a minor bug (see this github discussion) and my answer was actually not pointing at it correctly (apologies for any confusion caused). As all of that does not matter anymore (bug is fixed), I edited my answer to focus on how LDA can be solved via SVD, which is the default algorithm in scikit-learn.

After defining within- and between-class scatter matrices $\boldsymbol \Sigma_W$ and $\boldsymbol \Sigma_B$, the standard LDA calculation, as pointed out in your question, is to take eigenvectors of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B$ as discriminant axes (see e.g. here). The same axes, however, can be computed in a slightly different way, exploiting a whitening matrix:

Compute $\boldsymbol \Sigma_W^{-1/2}$. This is a whitening transformation with respect to the pooled within-class covariance (see my linked answer for details).
Note that if you have eigen-decomposition $\boldsymbol \Sigma_W = \mathbf{U}\mathbf{S}\mathbf{U}^\top$, then $\boldsymbol \Sigma_W^{-1/2}=\mathbf{U}\mathbf{S}^{-1/2}\mathbf{U}^\top$. Note also that one compute the same by doing SVD of pooled within-class data: $\mathbf{X}_W = \mathbf{U} \mathbf{L} \mathbf{V}^\top \Rightarrow \boldsymbol\Sigma_W^{-1/2}=\mathbf{U}\mathbf{L}^{-1}\mathbf{U}^\top$.
Find eigenvectors of $\boldsymbol \Sigma_W^{-1/2} \boldsymbol \Sigma_B \boldsymbol \Sigma_W^{-1/2}$, let us call them $\mathbf{A}^*$.
Again, note that one can compute it by doing SVD of between-class data $\mathbf{X}_B$, transformed with $\boldsymbol \Sigma_W^{-1/2}$, i.e. between-class data whitened with respect to the within-class covariance.
The discriminant axes $\mathbf A$ will be given by $\boldsymbol \Sigma_W^{-1/2} \mathbf{A}^*$, i.e. by the principal axes of transformed data, transformed again.
Indeed, if $\mathbf a^*$ is an eigenvector of the above matrix, then $$\boldsymbol \Sigma_W^{-1/2} \boldsymbol \Sigma_B \boldsymbol \Sigma_W^{-1/2}\mathbf a^* = \lambda \mathbf a^*,$$ and multiplying from the left by $\boldsymbol \Sigma_W^{-1/2}$ and defining $\mathbf a = \boldsymbol \Sigma_W^{-1/2}\mathbf a^*$, we immediately obtain: $$\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B \mathbf a = \lambda \mathbf a.$$

In summary, LDA is equivalent to whitening the matrix of class means with respect to within-class covariance, doing PCA on the class means, and back-transforming the resulting principal axes into the original (unwhitened) space.
This is pointed out e.g. in The Elements of Statistical Learning, section 4.3.3. In scikit-learn this is the default way to compute LDA  because SVD of a data matrix is numerically more stable than eigen-decomposition of its covariance matrix.
Note that one can use any whitening transformation instead of $\boldsymbol \Sigma_W^{-1/2}$ and everything will still work exactly the same. In scikit-learn $\mathbf{L}^{-1}\mathbf{U}^\top$ is used (instead of $\mathbf{U}\mathbf{L}^{-1}\mathbf{U}^\top$), and it works just fine (contrary to what was originally written in my answer).
Comment: @kazemakase: Well, of course if there are only two classes, then $\boldsymbol \Sigma_B$ has rank 1, and everything simplifies a lot, as the only eigenvector of $\boldsymbol \Sigma_W^{-1}\boldsymbol \Sigma_B$ is given by $\boldsymbol \Sigma_W^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_2)$, where $\boldsymbol\mu_i$ are class means. I guess that is what you meant before? This is nicely covered e.g. in Bishop's ML textbook, section 4.1.4. But the generalization to more classes requires eigen-analysis (Ibid., 4.1.6). Also, scikit's code (that we are discussing here!) *does* use svd, twice actually.
Comment: Thanks for this nice answer. I appreciate it that you took the time to write it up that nicely. Maybe you could mention it in the discussion on GitHub; I am sure that would be of help to fix the LDA in the next version of sci-kit
Comment: @SebastianRaschka: I don't have an account on GitHub. But if you want, you can give there a link to this thread.
Comment: @amoeba: Textbooks usually describe the LDA as you did - an eigenvalue decomposition of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B$. Curiously, a number of LDA implementations I know take a different approach. Their axes are the vectors to the class means transformed with $\boldsymbol \Sigma_W^{-1}$. Your LDA solution is an orthonormal basis of these vectors. Scikit-learn's LDA gives the same results as these implementations, so I don't think there is actually an error.
Comment: For reference, here are the implementations I was talking about:

http://sourceforge.net/p/mlpy/code/ci/default/tree/mlpy/da.py#l24

https://github.com/sccn/BCILAB/blob/master/code/machine_learning/ml_trainlda.m

http://www.mathworks.com/matlabcentral/fileexchange/29673-lda--linear-discriminant-analysis
Comment: @kazemakase: Can you point me to any authoritative treatment of LDA explaining such an approach (textbook, paper, slides, whatever)? I have seen dozens of LDA treatments and they were all equivalent to the standard approach. If there are any advantages in doing LDA differently, I would love to know them. Code examples are not convincing, as they are (a) not authoritative, and (b) fail to explain any rationale. [Also: class means transformed with $\boldsymbol\Sigma_W^{-1}$ is yet another approach, different from scikit's? Does not involve svd/eig at all? Probably works for two classes only.]
Comment: @amoeba: May I refer you to Fisher's 1938 paper [here](http://digital.library.adelaide.edu.au/dspace/bitstream/2440/15227/1/138.pdf)? Although only the two-class case is discussed, generalization to more classes is straight forward. SVD/EIG is not used at all, and the advantage is that you don't need an estimate of $\boldsymbol \Sigma_B$, which is often underdetermined.
Answer: Just to close this question, the discussed issue with the LDA has been fixed in scikit-learn 0.15.2.


PCA loadings interpretation

Question: Regarding the final output of PCA:

Using rotation, I'll get a loading for my 50 components, so the equation would be $pc_1=0.05*a_1+0.02*a_2+\dots+0.04*a_{50}$. Now, can I derive the value of $pc_1$ by using my last observed return for $a_1,a_2,\dots,a_{50}$?
As I looked at my data, I have found at least 10 principal components are required to explain 80% of the variance, so using same logic as above, I'll get $pc_1,pc_2,\dots,pc_{10}$. Now the regression would be $y=w_1*pc_1+w_2*pc_2+...+w_{10}*pc_{10}+e $. In each of them $w_1,w_2,\dots,w_{10}$ can be their respective eigenvalue and the remaining term is an error term?
Comment: How does this differ from [your previous question](http://stats.stackexchange.com/questions/28996/principal-component-analysis-in-r)?
Answer: Everything sounds pretty OK except the ending of Q2. When you do regress y on the first ten PCs, w1,...,w10 are unknown weights to be estimated from your data using Ordinary Least Squares for example.
Comment: To add firstname.lastname@example.com's answer:  the eigenvalues describe the variance accounted for among the 50 variables used in PCA, but this is before the dependent variable (Y) was ever entered into the analysis.  The eigenvalues and loadings have nothing to do with relationships with Y.

PCA loadings interpretation


How can I integrate both Java and Python in a Visual Studio project?

Question: I'm developing a software which involves database creation, manipulation and extension in a proprietary format, which is partly inspired from SQL but is more extensive.
Some part of my software is coded in Python, most in Java, and just a bit front-end in Visual Basic. How can I integrate the back-end code that is written in Python and Java, with VB (2012) and call functions among them, in a single solution?
Answer: I would approach it by picking one of three languages as your database back-end, then develop an API for interacting between them using HTTP or some other protocol.
For instance, you could use Python Django's great ORM to develop your database models, and then use the Django Tastypie library to expose API resources for your database models at endpoints like http://localhost/api/v2/foo/ (a list of foo objects) and http://localhost/api/v2/foo/24/ (a detailed foo object with foo.id = 24).
Then, write a class in your VB.NET App_Code folder called localhostRESTfulApi which consumes your django-tastypie API. This could be a simple or as complex as you want.
The simple case would include invoking API calls verbosely using something like localhostRESTfulApi.POST([endpoint URL], [new object data]). You have to be knowledgeable about how the POST/GET/PATCH requests work in all circumstances and it's not very OOP-y.
The complex solution would be to re-write wrappers for your objects in the django database back-end as classes in VB (and again in Java) which have a constructor that either takes null for a new object or id for an object which it would then retrieve via the API upon instantiation (e.g. by consuming the localhostRESTfulApi.GET method.  This way you save yourself some clunkiness by only having to write the API GET/POST logic in the private methods of the object class, instead of littered throughout your application.
You would also write a save() method which does the appropriate API PATCH/PUT request behind the scenes to sync with the database back-end -- or perhaps override your get/set attribute methods on the class to retrieve and save changes on-the-fly (without invoking an asynchronous save() method).

I'm curious to see what solutions other SO users come up with. This is merely one way I have done it previously on a multiple language/platform application (for which I also needed an external RESTful API anyway).


Como deixar um texto centralizado entre duas linhas horizontais?

Question: Preciso utilizar um texto centralizado na página e entre duas linhas horizontais em todas títulos do projeto, conforme abaixo:

O texto do título possui magin: 0 35px, é dinâmico e as linhas horizontais devem aumentar ou diminuir de acordo.
Answer: Existem algumas maneiras de se fazer isso, uma delas seria com fieldset, exemplo

fieldset {
   border-top: 1px solid #333;
    border-bottom: none;
    border-left: none;
    border-right: none;
    display: block;
    text-align: center;
}

fieldset legend {
    padding: 5px 10px;
}
<fieldset class="Produtos">
    <legend>Produtos</legend>
</fieldset>

Outra maneira seria com uma div e span

div.titulo {
  height: 1px;
  background-color: #333;
  text-align: center;
}
div.titulo span {
  background-color: white;
  position: relative;
  top: -0.5em;
  padding: 0 10px;
}

    Produtos

Answer: Quase tudo sobre texto entre linhas:

/**
 * Horizontal Type Line Behind Text
 * Inspired by this discussion @ CSS-Tricks: http://css-tricks.com/forums/topic/css-trick-for-a-horizontal-type-line-behind-text/#post-151970
 * Available on jsFiddle: http://jsfiddle.net/ericrasch/jAXXA/
 * Available on Dabblet: http://dabblet.com/gist/2045198
 * Available on GitHub Gist: https://gist.github.com/2045198
 */
h2 {
  font: 33px sans-serif;
  margin-top: 30px;
  text-align: center;
  text-transform: uppercase;
}
h2.background {
  position: relative;
  z-index: 1;
}
h2.background:before {
  border-top: 2px solid #dfdfdf;
  content: "";
  margin: 0 auto;
  /* this centers the line to the full width specified */

  position: absolute;
  /* positioning must be absolute here, and relative positioning must be applied to the parent */

  top: 50%;
  left: 0;
  right: 0;
  bottom: 0;
  width: 95%;
  z-index: -1;
}
h2.background span {
  /* to hide the lines from behind the text, you have to set the background color the same as the container */
  background: #fff;
  padding: 0 15px;
}
h2.double:before {
  /* this is just to undo the :before styling from above */

  border-top: none;
}
h2.double:after {
  border-bottom: 1px solid blue;
  -webkit-box-shadow: 0 1px 0 0 red;
  -moz-box-shadow: 0 1px 0 0 red;
  box-shadow: 0 1px 0 0 red;
  content: "";
  margin: 0 auto;
  /* this centers the line to the full width specified */

  position: absolute;
  top: 45%;
  left: 0;
  right: 0;
  width: 95%;
  z-index: -1;
}
h2.no-background {
  position: relative;
  overflow: hidden;
}
h2.no-background span {
  display: inline-block;
  vertical-align: baseline;
  zoom: 1;
  *display: inline;
  *vertical-align: auto;
  position: relative;
  padding: 0 20px;
}
h2.no-background span:before,
h2.no-background span:after {
  content: '';
  display: block;
  width: 1000px;
  position: absolute;
  top: 0.73em;
  border-top: 1px solid red;
}
h2.no-background span:before {
  right: 100%;
}
h2.no-background span:after {
  left: 100%;
}
h2.no-span {
  display: table;
  white-space: nowrap;
}
h2.no-span:before,
h2.no-span:after {
  border-top: 1px solid green;
  content: '';
  display: table-cell;
  position: relative;
  top: 0.5em;
  width: 45%;
}
h2.no-span:before {
  right: 1.5%;
}
h2.no-span:after {
  left: 1.5%;
}

Strikethrough title

Line-behind title

Double-lined title

Line-behind title (no bg)

Line-behind title (no span/no bg)

FONTE
Answer: Uma forma que encontrei a solução.
Com certeza há várias formas de se fazer.

  or

Criação da div com class="content".
Tag
 para criar a linha.
O título
Tag
 para criar a linha.

.content {
  width: 400px;

  display: flex;
  align-items: center;
  gap: 5px;
}
hr {
  width: 100%;
}

Limitei a div content com (largura)width: 400px;
Defini o div com `display: flex;
Alinhei todos os itens ao centro
Defini o espaçamento entre eles com gap: 5px;
Defini o valor de largura das linhas conforme o tamanho da div pai.


Why does sql-sync fail?

Question: I'm managing Drupal 7 and Drupal 8 sites, so I'm running Drush 8 as that's the only version that can manage both. The Drupal 8 sites are installed using Composer and my local setup runs on MAMP 5.5.1.
It works fine for the Drupal 7 sites, and rsync works for the Drupal 8 sites as well. However, sql-sync fails. When I run drush sql-sync @local.dup @prod.dup, I get the following messages.

Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/localvendor/bin/drush on line 4
  Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include_path='.:') in /Users/username/path/to/local/vendor/bin/drush on line 4
  The command could not be executed successfully (returned:                                                                                [error] Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/local/vendor/bin/drush on line 4
  Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include_path='.:') in  /Users/username/path/to/local/vendor/bin/drush on line 4, code: 255)
  The Drush sql-dump command did not report the path to the dump file produced. Try upgrading the version of Drush you are using on the source machine.

I get similar errors when checking drush @local status and drush @remote status as well as when I try to use the Drush 9 included in each site ( cd path/to/docroot > vendor/bin/drush @self @remote).
I've tried removing all Drush instances and installing only the same version that my host (cloudways) uses on the remote server (Drush 8.0.5) with no luck. I've installed Drush using CGR as instructed on Install (alternatives).
I've also checked my alias' file in the global Drush folder multiple times and can't find any issues.
What can I do from here to debug and resolve the issue?
Comment: `some D7 and D8-sites so I'm running Drush 8 as that's the only version that can manage both.` – That's somewhat wrong. See https://docs.drush.org/en/master/install/#drupal-compatibility
Comment: Not true. That chart specifically shows drupal 8 support, though partial, for drush 8. I don't think we should assume that "manage both" means full support.
Comment: Thanks guys. I basically only use Drush for rsync, sql-sync and clearing the cache, so I thing Drush 8 should be fine, right?
Comment: If it works for you. But it's not recommended. And especially when handling app critical things like the database you should better be using a version that fully supports your Drupal 8.4+.
Comment: OK, but as I'm still getting the same error when using the site-specific Drush 9 commands as described in the question, I guess the errors aren't due to the global Drush 8 installation, right?
Answer: I ended up running two global drush installs as explained here.
I needed to make to use same versions of Drush 9 both globally and on the site-specific installs to not get any errors. Now both Drush 8 and Drush 9 seem to run smoothly alongside each-other.

Why does sql-sync fail?


Skipping bad JSON data in Jackson

Question: Using Jackson data binding, what's the neatest way to skip a bad chunk of data, without rejecting the whole parse?
Take these classes (I'm using public fields just to keep the code short):
 public class ClassWhichCouldFailConstruction {
     public ClassWhichCouldFailConstruction(String s) {
         if(s.charAt(0) > 'L') {
            throw new BadParameterException();
         }
         // else init code here.
     }
 }

 public class User {
     public String name;
     public ClassWhichCouldFailConstruction failable;
 }

 public class AppInfo {
     public List<User> users;
 }

... and this code to parse it:
 AppInfo appinfo = (List<User>) objectMapper.readValues(jsonStream, AppInfo.class);

... and this JSON:
 { "users": [
     { "name": "John", "failable": "Example" },
     { "name": "Jane", "failable": "No good" }
   ]
 }

By default ClassWhichCouldFailConstruction("No good") will throw an exception which will bubble up to the caller of objectMapper.readValues().

How can I make it return a AppInfo object containing a users list that is one item long (the valid item)?
And can I run a routine to deal with (e.g. to log) the skipped entry?

I know I can achieve this with a custom deserializer:
 public class User {
     public String name;
     @JsonDeserialize (using = MyCustomDeserializer.class)
     public ClassWhichCouldFailConstruction failable;
 }

... in which MyCustomDeserializer consumes the content in incremental mode. I'm looking for an option which takes advantage of data binding. Consider that ClassWhichCouldFailConstruction might be something a whole lot more complicated, so writing a custom parser would be laborious.
Comment: Your custom deserializer could internally use its own `ObjectMapper`, and return `null` if that mapper threw an exception.
Comment: if you need to validate the JSON message you might have a look at [json-schema](http://json-schema.org/), though it is still in draft and has its limits (no object-orientated like inheritance but a kind of by using `allOf` a referenced schema, though you can't override those reference values - so the JSON message is validated against both schemas - a bit tricky but other than that it works)
Answer: Use Bean Validation API instead of throwing exception from constructor -- aspects of JSON parsing and data-binding (that Jackson does) can be separated from validation logic. This is where Bean Validator helps: you can declaratively define rules and constraints.
Comment: Can you explain how that would be used to achieve the goal described? That is, to skip the invalid part of a JSON parse, letting the rest of it through.
Comment: You would not do that, but rather you would not embed validation deep within your objects but use Bean Validation annotations for declarative approach (or, for more complex cases, implement validators that are associated using annotations).

If you do want to skip values that throw exception, you better create custom `JsonDeserializer` to do it. That is doable too.

Skipping bad JSON data in Jackson


SQL State : 90057, Message : Constraint "PRIMARY KEY | UNIQUE (USERNAME)" not found; SQL statement:

Question: I am using h2 in memory DB, I have small spring boot application.
When trying to run test I am getting error:
java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException: Migration V1.0.1__create_authorities_table.sql failed
-----------------------------------------------------
SQL State  : 90057
Error Code : 90057
Message    : Constraint "PRIMARY KEY | UNIQUE (USERNAME)" not found; SQL statement:

So it says that Flyway can't build it.
I have only two sql files:
V1.0.0__create_user_table.sql
CREATE TABLE users
(
    id IDENTITY PRIMARY KEY,
    username            VARCHAR(50) NOT NULL,
    password        VARCHAR(68) NOT NULL,
    enabled BOOLEAN NOT NULL
);

and V1.0.1__create_authorities_table.sql:
CREATE TABLE authorities (
                             username VARCHAR(50) NOT NULL,
                             authority VARCHAR(50) NOT NULL,
                             FOREIGN KEY (username) REFERENCES users(username)
);

CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority);

I see that Flyway doesn't like FOREIGN KEY (username) REFERENCES users(username) so I also tried with ALTER TABLE authorities ADD FOREIGN KEY (username) REFERENCES users(username) but still doesn't work. I checked that when I just remove adding FOREIGN KEY then tests are green - no errors.
Seems like both ways from this: https://stackoverflow.com/a/41515905/4952262 are failing for me - what am I doing wrong here?
Answer: Referential constraints may reference only unique sets of columns, a primary key or unique constraint on them is required, so you need to create a unique constraint on users(username) to allow references to this column from referential constraints.
You can simply add an inline constraint to definition of this column:
CREATE TABLE users
(
    …
    username            VARCHAR(50) NOT NULL UNIQUE,
    …

It will be better to remove username column from authorities table and add something like user_id BIGINT REFERENCES users(id) instead of it, however, duplication of long values between tables isn't a good practice.


both test lab Domain controllers need initial synchronisation

Question: Im trying to setup a test lab for our 2008R2 AD environment but am having trouble getting the domain controllers to start.
If I just start the PDC with all FSMO roles (DC01) it gives an error saying it needs to do an initial synchronisation with atleast 1 other domain controller before it will start.
I understand this means turn on another DC and it should be good to go.
but When I start DC03, it starts but has an error in dcdiag saying it cannot connect to the PDC. I can open sites and service and right click dc01 to manually 'replicate now'. It says its 'Active Diretory Domain sevices has repllicated the connections'.
On DC01 and DC03 I have tried to force replication with 'repadmin /replicate dc01 dc03 DC=domain,DC=com', it says
Experienced the following operational errors trying to retrieve replication information:
       58 - dc03'.
Pretty much google says that they cant communicate with each other, but I dont know why.
I can ping and RDP between them. They are both on an isolated vswitch. Firewalls are off.
They are on different subnets so I added windows routes.
Their subnets are in sites and services.
Any advice on getting a copy of production as a Lab up and running?
update:
I have tried the registry setting:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters]
"Repl Perform Initial Synchronizations"=dword:00000000
When I use it, it starts but I cant create any new objects in AD such as users - it says 'The Directory Service is unable to allocate a relative identifier.'
Does anyone else have this issue if they use this reg key?
repadmin /showreps - says:
Last Attempt at  failed, result 8524 (0x214c): The DSA operation is unable to proceed because of a DNS lookup failure.
PortQuery: General network connectivity is ok. Domains and trusts says there are issues with the services that are not started. eg. ldap query fails because the directory services has not started.
update 2:
Solution: Turns out this was just a rookie mistake. My isolated network was only on one Host. I boot my VM I placed it on this host, but after a short amount of time, DRS would eventually migrate one of these VMS, so network connectivity would be lost. I would usually have enough time to do initial tests such as network connection, ping etc.
Comment: Could someone offer some advice on how to improve my question so it doesn't get voted down and so it is more useful to others?
Answer: If it's just a test environment, you can enable the following registry setting:
<code>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters]
"Repl Perform Initial Synchronizations"=dword:00000000
</code>
http://blogs.technet.com/b/ad/archive/2007/04/29/adroitly-sidestepping-initial-synchronization-requirements.aspx
If you want to find out why it is not communicating, run repadmin /showreps to get the replication status and PortQueryUI to confirm network connectivity.
Comment: Updated my question with results from these suggestions.


How to remove arrows from views Select list field

Question: I have a content type which has a select list field.
I created a view where select list field was added under "filter criteria".

How can I remove the arrows and slider?
Comment: Hello - that's just the default styling of a multi-value html select widget. It's not a special Drupal thing. You could install a theme that styles select widgets differently or create a new (or modify your existing) custom theme to style it differently.
Answer: The appearance of the Select widget on a Content type can be changed on the Manage form display page for that Content type (for example for Article CT it's under Structure > Content types > Article > Manage form display (/admin/structure/types/manage/article/form-display)).
For a List field you can change it from the Select list to Check boxes/radio buttons.
There are also modules that provide different widgets for these types of fields, for example Select 2.

In Views you can change how each of the Exposed form elements is rendered under Advanced (third column area) > Exposed form style settings.
The module Better Exposed Filters is commonly used to adjust the Views Exposed forms.