问:
getView() not called even when getCount() has results
Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:

I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.

CartFragment Layout:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>
</code>```

In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:

```<code>public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();
</code>```

When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.

The method that populate my public list:

```<code>private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}
</code>```

ListView Adapter:

```<code>public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

@Override
public int getCount() {
    return mDataSource.size();
}

@Override
public Object getItem(int position) {
    return mDataSource.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}
</code>```

My layout of row:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?

EDIT
I inflate listview on onCreate:

```<code>    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);
</code>```

答:
Declare your List sCarrinhoAuxiliar and adapter sAdaptador as global.

Update your OnCreateView() as below:

```<code>// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;

.........................

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ....................
    ........................

    sCarrinhoAuxiliar = new ArrayList<>();
    sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
    fCarrinhoResultado.setAdapter(sAdaptador);

    .......................
    ...............
}
</code>```

Update your onResponse() method as below:

```<code>@Override
public void onResponse(String response) {

    .....................
    ..........................
    try {
        // Clear old data
        sCarrinhoAuxiliar.clear();

        for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
            PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
            sCarrinhoAuxiliar.add(sItem);
        }
        // Update list
        sAdaptador.notifyDataSetChanged();
        .............
        ....................
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Hope this will help~

Body:
Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:

I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.

CartFragment Layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>

In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:

public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();

When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.

The method that populate my public list:

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}

ListView Adapter:

public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

@Override
public int getCount() {
    return mDataSource.size();
}

@Override
public Object getItem(int position) {
    return mDataSource.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}

My layout of row:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?

EDIT
I inflate listview on onCreate:

    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);

Body:
Declare your List sCarrinhoAuxiliar and adapter sAdaptador as global.

Update your OnCreateView() as below:

// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;

.........................

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ....................
    ........................

    sCarrinhoAuxiliar = new ArrayList<>();
    sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
    fCarrinhoResultado.setAdapter(sAdaptador);

    .......................
    ...............
}

Update your onResponse() method as below:

@Override
public void onResponse(String response) {

    .....................
    ..........................
    try {
        // Clear old data
        sCarrinhoAuxiliar.clear();

        for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
            PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
            sCarrinhoAuxiliar.add(sItem);
        }
        // Update list
        sAdaptador.notifyDataSetChanged();
        .............
        ....................
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Hope this will help~


来源: stackexchange

问:
C, HTTP 1.1 and Socket Send troubles
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

```<code>int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}
</code>```

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

```<code>void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}
</code>```

If I were to add

```<code>Send("Oh end of HTML Sending eh?");
</code>```

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

```<code>SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");
</code>```

This should result in the Browser showing:

HAaaaii!!lolwut?

答:
Since you're sending the content-length, the browser won't be accepting no more content after "HAaaaii!!" and therfore will interpret the "lolwut?" as a part of the answer of its next request, which will of course fail.

You could skip sending a content-length, but this would mean that you are not using keep-alive and therefore can't handle more than one request per TCP connection.

Handling more than one Request-Response exchange per TCP connection can greatly speed up browsing speed, since a normal web-page consists of several separate resources, each of which will have to be requested separately. And since establishing a TCP connection is takes at least 3 round trips, this would add an additional, unnecessary delay for each resource.

OwnerDisplayName: Filip Ekberg

ContentLicense: CC BY-SA 2.5

Title: C, HTTP 1.1 and Socket Send troubles

Body:
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}

If I were to add

Send("Oh end of HTML Sending eh?");

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");

This should result in the Browser showing:

HAaaaii!!lolwut?

OwnerDisplayName: saua

LastEditorDisplayName: saua


问:
Ruby on rails - Sort data with SQL/ActiveRecord instead of ruby
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

```<code>@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }
</code>```

Is their a way to do the same thing only with SQL/ActiveRecord?

答:
Yes, using ActiveRecord's #order:

```<code>@video = Video.order(:created_at)
@pictures = Picture.order(:created_at)
@medias = @video.all + @pictures.all # Really bad idea!
</code>```

Also calling all on the models like that will unnecessarily load them to memory. If you don't absolutely need all records at that time, then don't use all.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }

Is their a way to do the same thing only with SQL/ActiveRecord?

Body:
Yes, using ActiveRecord's #order:

@video = Video.order(:created_at)
@pictures = Picture.order(:created_at)
@medias = @video.all + @pictures.all # Really bad idea!

Also calling all on the models like that will unnecessarily load them to memory. If you don't absolutely need all records at that time, then don't use all.


问:
get information from an other entity
I have two entities "OfferStage and Entreprise" with relation ManyToOne and OneToMany, and for the display of the list of "offrestage" I like to display the Logo of each "Entreprise"

Entity/OffreStage

```<code>class OffreStage
{
 /...

/**
 *
 *
 * @ORM\ManyToOne(targetEntity="UserBundle\Entity\Entreprise",      inversedBy="offres", cascade={"persist", "merge"})
 * @ORM\JoinColumn(name="entreprise_id", referencedColumnName="id")
 */

protected $entreprise;
</code>```

Entity/Entreprise

```<code>class Entreprise extends User
{
/..
/**
 * @ORM\OneToMany(targetEntity="Gestion\StageBundle\Entity\OffreStage", mappedBy="entreprise")
 */
protected $offres;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
protected $path;
</code>```

Controller

```<code>class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('FrontBundle:Default:index.html.twig');
    }

    public function listeStagesShowAction()
    {
        $em = $this->getDoctrine()->getManager();

        $offreStages = $em->getRepository('StageBundle:OffreStage')-    >findAll();

        return $this->render('FrontBundle:Stage:listeStage.html.twig',      array(
            'offreStages' => $offreStages,

        ));
}    }
</code>```

答: it just problem from database , it found data with null value </p>

Title: get information from an other entity

Body:
I have two entities "OfferStage and Entreprise" with relation ManyToOne and OneToMany, and for the display of the list of "offrestage" I like to display the Logo of each "Entreprise"

Entity/OffreStage

class OffreStage
{
 /...

/**
 *
 *
 * @ORM\ManyToOne(targetEntity="UserBundle\Entity\Entreprise",      inversedBy="offres", cascade={"persist", "merge"})
 * @ORM\JoinColumn(name="entreprise_id", referencedColumnName="id")
 */

protected $entreprise;

Entity/Entreprise

class Entreprise extends User
{
/..
/**
 * @ORM\OneToMany(targetEntity="Gestion\StageBundle\Entity\OffreStage", mappedBy="entreprise")
 */
protected $offres;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
protected $path;

Controller

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('FrontBundle:Default:index.html.twig');
    }

    public function listeStagesShowAction()
    {
        $em = $this->getDoctrine()->getManager();

        $offreStages = $em->getRepository('StageBundle:OffreStage')-    >findAll();

        return $this->render('FrontBundle:Stage:listeStage.html.twig',      array(
            'offreStages' => $offreStages,

        ));
}    }


问:
Keyboard shortcut to remove empty lines in a C# code file
Is there any keyboard shortcut to remove empty lines in C# code files (.cs)?

Similar to Ctrl + K , D which formats the whole .cs file.

Or is there a workaround?

答: CodeMaid has a setting that automatically removes empty lines (when you save the file, I think) according to some configurable rules. I think it makes the files quite neat.</p>


问:
How do I extend own library?
I am new in codeigniter and want to add a library to my first ci app which extends another library

```<code>class Mylib {}
</code>```

/application/libraries/Mynewlib.php:

```<code>class Mynewlib extends Mylib{}
</code>```

Where do I have to put Mylib.php and how do I load Mylib?

Thanks!

答:
This works for me.

library file Mylib.php

```<code>class Mylib {
   function test()
   {
       return 1;
   }
}
</code>```

library file Mynewlib

```<code>require_once('Mylib.php');
class Mynewlib extends Mylib{}
</code>```

controller

```<code>$this->load->library('Mynewlib');
echo $this->Mynewlib->test();
</code>```

Title: How do I extend own library?

Body:
I am new in codeigniter and want to add a library to my first ci app which extends another library

class Mylib {}

/application/libraries/Mynewlib.php:

class Mynewlib extends Mylib{}

Where do I have to put Mylib.php and how do I load Mylib?

Thanks!

Body:
This works for me.

library file Mylib.php

class Mylib {
   function test()
   {
       return 1;
   }
}

library file Mynewlib

require_once('Mylib.php');
class Mynewlib extends Mylib{}

controller

$this->load->library('Mynewlib');
echo $this->Mynewlib->test();


问:
Is it possible to change behaviour on new tab event in any browser?
When you click on the "new tab" button in a browser, let's say Chrome, new tab appears in the end of the existing tab chain.

I wonder if it is any chance to make a broswer put the tab in the head of the chain?

Maybe plugin? Have to dive in firefox codebase?

Any ideas appreciated!

答:
I did it with Chrome Extention
https://chrome.google.com/webstore/detail/tabtohead/iipdefkdfmbhnelbhlbdamplokbnpkhe</p>


问:
How to pass @formparam in post method of URI via mozilla restclient
I have created a restful webservice in java, while testing it on mozilla restclient I am unable to pass @formparam. Can someone please help me to do the same.
Please find the code of my webservice below:

```<code>@Path("/user/service")
public class UserServices {
    @GET
    public String getFunc(@FormParam("username") String username) {
        System.out.println("getFunc");
        return username;
    }
    @POST
    public String postFunc(@FormParam("username") String username) {
        System.out.println("postFunc");
        System.out.println("username is " + username);
        return username;
    }
}
</code>```

Here is a screenshot how I am passing @formparam to the mozilla restClient:
Screenshot

答:
Can you try changing the POST method to accept a Map (i.e. request body), e.g.:

```<code>@POST
public String postFunc(final MultivaluedMap<String, String> formParams) {
    System.out.println(formParams);
}
</code>```

You can then print the content of the Map and see which parameters are retrieved on the server side.

Body:
I have created a restful webservice in java, while testing it on mozilla restclient I am unable to pass @formparam. Can someone please help me to do the same.
Please find the code of my webservice below:

@Path("/user/service")
public class UserServices {
    @GET
    public String getFunc(@FormParam("username") String username) {
        System.out.println("getFunc");
        return username;
    }
    @POST
    public String postFunc(@FormParam("username") String username) {
        System.out.println("postFunc");
        System.out.println("username is " + username);
        return username;
    }
}

Here is a screenshot how I am passing @formparam to the mozilla restClient:
Screenshot

Body:
Can you try changing the POST method to accept a Map (i.e. request body), e.g.:

@POST
public String postFunc(final MultivaluedMap<String, String> formParams) {
    System.out.println(formParams);
}

You can then print the content of the Map and see which parameters are retrieved on the server side.


问:
Can we fetch the call details of an iPhone?
Can we fetch the call details like dialed numbers, missed calls of an iPhone?

UPDATE

Can we do it in jail broken phones for CYDIA store?

答:
Yes, you can do it for jailbroken device.

The call history is stored in call_history.db.

ContentLicense: CC BY-SA 4.0


问:
R 3.4.0 median methods and roxygen2
I have been asked to update my package Bolstad so that the definition of my S3 median method agrees with the new median generic in R 3.4.0. This means is needs to be able to deal with ... - That is fine, but I also need it to work with roxygen2. Here is my function definition etc.:

```<code>#' Median generic
#'
#' @param x an object.
#' @param na.rm Ideally if \code{TRUE} then missing values will be removed, but not currently used.

#' @param \ldots [>=R3.4.0 only] Not currently used.
#' @details If \code{x} is an object of class \code{Bolstad} then the posterior
#'   median of the parameter of interest will be calculated.
#' @author James Curran
#' @method median Bolstad
#' @export
median.Bolstad =
if(is.na(match("...", names(formals(median))))) {
  function(x, na.rm = FALSE) {
    return(quantile(x, probs = 0.5))
  }
}else{
  function(x, na.rm = FALSE, ...) {
    return(quantile(x, probs = 0.5))
  }
}
</code>```

This conditional definition seems to compile okay, but when I run it through the devel version of R, I get a code mismatch warning because the usage hasn't allowed for the ..., i.e.

```<code>Codoc mismatches from documentation object 'median.Bolstad':
median.Bolstad
  Code: function(x, na.rm = FALSE, ...)
  Docs: function(x, na.rm = FALSE)
  Argument names in code not in docs:
  ...
</code>```

Any help/advice appreciated.

答:
The solution that has gone up on CRAN is given below (based on something Kurt Hornik sent me). However, it too has a downside in that roxygen2 does not generate a help file for the median function.

```<code>#' Median generic
#'
#' @param x an object.
#' @param na.rm Ideally if \code{TRUE} then missing values will be removed, but not currently used.
#' @param ... [>=R3.4.0 only] Not currently used.
#' @details If \code{x} is an object of class \code{Bolstad} then the posterior
#'   median of the parameter of interest will be calculated.
#' @author James Curran
#' @method median Bolstad
if(is.na(match("...", names(formals(median))))) {
  median.Bolstad = function(x, na.rm = FALSE) {
    return(quantile(x, probs = 0.5))
  }
}else{
  median.Bolstad = function(x, na.rm = FALSE, ...) {
    return(quantile(x, probs = 0.5))
  }
}
</code>```

Title: R 3.4.0 median methods and roxygen2

Body:
I have been asked to update my package Bolstad so that the definition of my S3 median method agrees with the new median generic in R 3.4.0. This means is needs to be able to deal with ... - That is fine, but I also need it to work with roxygen2. Here is my function definition etc.:

#' Median generic
#'
#' @param x an object.
#' @param na.rm Ideally if \code{TRUE} then missing values will be removed, but not currently used.

#' @param \ldots [>=R3.4.0 only] Not currently used.
#' @details If \code{x} is an object of class \code{Bolstad} then the posterior
#'   median of the parameter of interest will be calculated.
#' @author James Curran
#' @method median Bolstad
#' @export
median.Bolstad =
if(is.na(match("...", names(formals(median))))) {
  function(x, na.rm = FALSE) {
    return(quantile(x, probs = 0.5))
  }
}else{
  function(x, na.rm = FALSE, ...) {
    return(quantile(x, probs = 0.5))
  }
}

This conditional definition seems to compile okay, but when I run it through the devel version of R, I get a code mismatch warning because the usage hasn't allowed for the ..., i.e.

Codoc mismatches from documentation object 'median.Bolstad':
median.Bolstad
  Code: function(x, na.rm = FALSE, ...)
  Docs: function(x, na.rm = FALSE)
  Argument names in code not in docs:
  ...

Any help/advice appreciated.

Body:
The solution that has gone up on CRAN is given below (based on something Kurt Hornik sent me). However, it too has a downside in that roxygen2 does not generate a help file for the median function.

#' Median generic
#'
#' @param x an object.
#' @param na.rm Ideally if \code{TRUE} then missing values will be removed, but not currently used.
#' @param ... [>=R3.4.0 only] Not currently used.
#' @details If \code{x} is an object of class \code{Bolstad} then the posterior
#'   median of the parameter of interest will be calculated.
#' @author James Curran
#' @method median Bolstad
if(is.na(match("...", names(formals(median))))) {
  median.Bolstad = function(x, na.rm = FALSE) {
    return(quantile(x, probs = 0.5))
  }
}else{
  median.Bolstad = function(x, na.rm = FALSE, ...) {
    return(quantile(x, probs = 0.5))
  }
}


问:
Execute a query for all tables and fill in data in new one
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

```<code>SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates
</code>```

Then I found out how to get all table names
I do it in this way

```<code>SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'
</code>```

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

```<code>DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor
</code>```

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

```<code>CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()
</code>```

答:
right... you might want to try this.

remove this line and run the query again.

```<code>DECLARE @DB_Name varchar(50), @Command varchar(100);
</code>```

i think in mysql you can just use a variable without declaring it and then cast when necessary.

Body:
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates

Then I found out how to get all table names
I do it in this way

SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()

Body:
right... you might want to try this.

remove this line and run the query again.

DECLARE @DB_Name varchar(50), @Command varchar(100);

i think in mysql you can just use a variable without declaring it and then cast when necessary.


问:
Plotting non uint8 images with matplotlib
I was studying about Python Numpy tutorial from link when I came across the fact that matplotlib.pyplot was giving strange results when I tried to display some image.

Here's my sample code which I modified from the tutorial link.

```<code>from scipy.misc import imread, imresize
import matplotlib.pyplot as plt

img = imread('cat.jpg')
img_tinted = img * [1, 1, 1]

print img_tinted
# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 2, 2)

plt.imshow(img_tinted)
plt.show()
</code>```

The output was as follows

```<code>[[[132 128 117]
  [155 151 139]
  [181 175 161]
  ...,
  [ 78  68  43]
  [ 76  65  43]
  [ 64  53  31]]]
</code>```

Even though the data looks to be in the uint8 format the output image was a strange one.

Is there a way to display it similar to the original image?

答:
A simple solution to this could be to explicitly typecast unit8 to the image while plotting it with matplotlib.pyplot

Just replacing this code plt.imshow(img_tinted) with plt.imshow(np.uint8(img_tinted)) resolved the issue.

Here's the sample output

You can even play further with the images

```<code>import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt

img = imread('cat.jpg')
img_tinted = img * [1, 0.5, 0.5]

print np.uint8(img_tinted)

# Show the original image
plt.subplot(1, 3, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 3, 2)
plt.imshow(np.uint8(img_tinted))

# Show the tinted image without using np.uint8
plt.subplot(1, 3, 3)
plt.imshow(img_tinted)

plt.show()
</code>```

The output was as follows

```<code> [[[132 128 117]
  [155 151 139]
  [181 175 161]
  ...,
  [ 78  68  43]
  [ 76  65  43]
  [ 64  53  31]]]
</code>```

Body:
I was studying about Python Numpy tutorial from link when I came across the fact that matplotlib.pyplot was giving strange results when I tried to display some image.

Here's my sample code which I modified from the tutorial link.

from scipy.misc import imread, imresize
import matplotlib.pyplot as plt

img = imread('cat.jpg')
img_tinted = img * [1, 1, 1]

print img_tinted
# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 2, 2)

plt.imshow(img_tinted)
plt.show()

The output was as follows

[[[132 128 117]
  [155 151 139]
  [181 175 161]
  ...,
  [ 78  68  43]
  [ 76  65  43]
  [ 64  53  31]]]

Even though the data looks to be in the uint8 format the output image was a strange one.

Is there a way to display it similar to the original image?

Body:
A simple solution to this could be to explicitly typecast unit8 to the image while plotting it with matplotlib.pyplot

Just replacing this code plt.imshow(img_tinted) with plt.imshow(np.uint8(img_tinted)) resolved the issue.

Here's the sample output

You can even play further with the images

import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt

img = imread('cat.jpg')
img_tinted = img * [1, 0.5, 0.5]

print np.uint8(img_tinted)

# Show the original image
plt.subplot(1, 3, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 3, 2)
plt.imshow(np.uint8(img_tinted))

# Show the tinted image without using np.uint8
plt.subplot(1, 3, 3)
plt.imshow(img_tinted)

plt.show()

The output was as follows

 [[[132 128 117]
  [155 151 139]
  [181 175 161]
  ...,
  [ 78  68  43]
  [ 76  65  43]
  [ 64  53  31]]]


问:
Java Concurrent Modification Error HashMap
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?</p>

```<code>Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}
</code>```

答:
The first example throws an exception because you modify the map while you are iterating over it. That is expected.

In the second example, you create an ArrayList containing all the strings in the map. Here you iterate over that newly created ArrayList, so your second example don't throw an example because you iterate over the ArrayList, not over the map

Body:
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}


问:
UnboundLocalError with keras 2.0
I seem to have problems with the updated keras version. This neural network structure causes this error:

```<code>  print "Data-train-in: " + str(data_train_input[0].shape)
        print "Data-train-out: " + str(data_train_output[0].shape)
        print "Data-test-in: " + str(data_test_input[0].shape)
        #sys.exit()

        model.add(Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu" , input_shape = (3,6,3)))
        model.add(Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu", ))
        model.add(Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu", ))
        model.add(Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = "LeakyRelu", ))
        print model.output_shape
#        model.add(MaxPooling2D(pool_size=(3,1)))
        print model.output_shape
        model.add(Flatten())
        print model.output_shape
#        model.add(Dense(output_dim=300, input_dim=200, init="normal",activation='tanh'))
#        model.add(Dense(output_dim=32, input_dim=200, init="normal",activation='relu'))
#        model.add(Dense(output_dim=1, input_dim=32, init="normal",activation='tanh'))
        model.add(Dense(output_dim=13, input_dim=32, init="normal",activation='LeakyReLU'))
        model.add(Dense(output_dim=1,  init="normal", activation='linear'))
        print model.summary()
        model.compile(loss='mean_squared_error', optimizer="adam")
</code>```

Gives this output:

```<code>Data-train-in: (3, 6, 3)
Data-train-out: (1,)
Data-test-in: (3, 6, 3)
Traceback (most recent call last):
  File "keras_convolutional_feature_extraction.py", line 602, in <module>
    model(i,train_input_data_interweawed_normalized,output_data_train,test_input_data_interweawed_normalized,output_data_test)
  File "keras_convolutional_feature_extraction.py", line 535, in model
    model.add(Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu" , input_shape = (3,6,3)))
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 455, in __init__
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 108, in __init__
    self.activation = activations.get(activation)
  File "/usr/local/lib/python2.7/dist-packages/keras/activations.py", line 69, in get
    return deserialize(identifier)
  File "/usr/local/lib/python2.7/dist-packages/keras/activations.py", line 61, in deserialize
    printable_module_name='activation function')
  File "/usr/local/lib/python2.7/dist-packages/keras/utils/generic_utils.py", line 157, in deserialize_keras_object
    ':' + class_name)
UnboundLocalError: local variable 'class_name' referenced before assignment
</code>```

I read some other post regarding this issue, but this doesn't seem to be similar to the other ones.

答: Advanced layers has to be added separably, and not in the same line in which the convolution layer is being defined. </p>

Title: UnboundLocalError with keras 2.0

Body:
I seem to have problems with the updated keras version. This neural network structure causes this error:

  print "Data-train-in: " + str(data_train_input[0].shape)
        print "Data-train-out: " + str(data_train_output[0].shape)
        print "Data-test-in: " + str(data_test_input[0].shape)
        #sys.exit()

        model.add(Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu" , input_shape = (3,6,3)))
        model.add(Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu", ))
        model.add(Conv2D(filters = 64, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu", ))
        model.add(Conv2D(filters = 32, kernel_size = (1,1) , padding = "same" , activation = "LeakyRelu", ))
        print model.output_shape
#        model.add(MaxPooling2D(pool_size=(3,1)))
        print model.output_shape
        model.add(Flatten())
        print model.output_shape
#        model.add(Dense(output_dim=300, input_dim=200, init="normal",activation='tanh'))
#        model.add(Dense(output_dim=32, input_dim=200, init="normal",activation='relu'))
#        model.add(Dense(output_dim=1, input_dim=32, init="normal",activation='tanh'))
        model.add(Dense(output_dim=13, input_dim=32, init="normal",activation='LeakyReLU'))
        model.add(Dense(output_dim=1,  init="normal", activation='linear'))
        print model.summary()
        model.compile(loss='mean_squared_error', optimizer="adam")

Gives this output:

Data-train-in: (3, 6, 3)
Data-train-out: (1,)
Data-test-in: (3, 6, 3)
Traceback (most recent call last):
  File "keras_convolutional_feature_extraction.py", line 602, in <module>
    model(i,train_input_data_interweawed_normalized,output_data_train,test_input_data_interweawed_normalized,output_data_test)
  File "keras_convolutional_feature_extraction.py", line 535, in model
    model.add(Conv2D(filters = 32, kernel_size = (3,3) , padding = "same" , activation = "LeakyRelu" , input_shape = (3,6,3)))
  File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 455, in __init__
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 108, in __init__
    self.activation = activations.get(activation)
  File "/usr/local/lib/python2.7/dist-packages/keras/activations.py", line 69, in get
    return deserialize(identifier)
  File "/usr/local/lib/python2.7/dist-packages/keras/activations.py", line 61, in deserialize
    printable_module_name='activation function')
  File "/usr/local/lib/python2.7/dist-packages/keras/utils/generic_utils.py", line 157, in deserialize_keras_object
    ':' + class_name)
UnboundLocalError: local variable 'class_name' referenced before assignment

I read some other post regarding this issue, but this doesn't seem to be similar to the other ones.


问:
Making a heatmap for a 1D bar in python
I would like to make a heatmap in python for the heat distribution of a bar made out of points.  Essentially it consists of a bar at some initial temperature between two reservoirs held at a constant temperature.  For example, a bar made of 20 points, each initially at 100C, and 1 point on either side of the bar, both permanently held at 0.

I have made a list of lists showing the diffusion of temperature across the bar as a function of time as such:

[ [0, 100.0, 100.0, 100.0, 0] , [0, 75.0, 100.0, 75.0, 0] , [0, 62.5, 87.5, 62.5, 0], [0, 53.125, 75.0, 53.125, 0] ].  Where each list represents the heat distribution in the bar at a certain timestep.

Is there any way to get a heat map of this, where I would have the heat of the bar at different times, stacked on eachother?

Thanks

答:
Here's a solution that uses interpolation to smooth the discrete values. If this is not appropriate for your purposes, another idea is trying the heatmap function in the seaborn library. By the way, this considers the ends of your bars as having a unit length equal to 1.

```<code>from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
from matplotlib import cm
import seaborn as sns #optional
import numpy as np
import pandas as pd

bars = [ [0, 100.0, 100.0, 100.0, 0], [0, 75.0, 100.0, 75.0, 0], [0, 62.5, 87.5, 62.5, 0], [0, 53.125, 75.0, 53.125, 0] ]

for bar in bars:
    df = pd.DataFrame( (np.array( bar )) )
    ax = plt.subplot( )
    im = ax.imshow( df.transpose( ), cmap=cm.jet, interpolation='nearest', vmin=0, vmax=100 )
    divider = make_axes_locatable( ax )
    cax = divider.append_axes( "right", size="5%", pad=0.05 )
    cb = plt.colorbar(im, cax=cax)
    cb.set_label('Temp deg C')
    ax.xaxis.set_major_formatter(plt.NullFormatter())
    ax.yaxis.set_major_formatter(plt.NullFormatter())
    plt.show(  )
</code>```

Title: Making a heatmap for a 1D bar in python

Body:
Here's a solution that uses interpolation to smooth the discrete values. If this is not appropriate for your purposes, another idea is trying the heatmap function in the seaborn library. By the way, this considers the ends of your bars as having a unit length equal to 1.

from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
from matplotlib import cm
import seaborn as sns #optional
import numpy as np
import pandas as pd

bars = [ [0, 100.0, 100.0, 100.0, 0], [0, 75.0, 100.0, 75.0, 0], [0, 62.5, 87.5, 62.5, 0], [0, 53.125, 75.0, 53.125, 0] ]

for bar in bars:
    df = pd.DataFrame( (np.array( bar )) )
    ax = plt.subplot( )
    im = ax.imshow( df.transpose( ), cmap=cm.jet, interpolation='nearest', vmin=0, vmax=100 )
    divider = make_axes_locatable( ax )
    cax = divider.append_axes( "right", size="5%", pad=0.05 )
    cb = plt.colorbar(im, cax=cax)
    cb.set_label('Temp deg C')
    ax.xaxis.set_major_formatter(plt.NullFormatter())
    ax.yaxis.set_major_formatter(plt.NullFormatter())
    plt.show(  )


问:
sed is not replacing all occurences when using cat
when I apply the following to the tail of a file:

```<code>tail test9 | sed -e '/},/N;s/,\n*\]/]/g' >wtf
</code>```

I get the correct result:

```<code>{"_id":{"},oid":"58dc04a9fbca629d612f1905"},"memberID":"114526","gender":"M","a    ge":"33","ethnicOriginCountryName":"Egypt","sect":"SU"},
{"_id":{"},oid":"58dc04a9fbca629d612f190d"},"memberID":"114534","gender":"M","age":"24","ethnicOriginCountryName":"United Kingdom","sect":"SU"}]
</code>```

however when using cat

```<code>cat test9 | sed -e '/},/N;s/,\n*\]/]/g' >wtf
</code>```

I do not get the correct result:

```<code>{"_id":{"},oid":"58dc04a9fbca629d612f1905"},"memberID":"114526","gender":"M","age":"33","ethnicOriginCountryName":"Egypt","sect":"SU"},
{"_id":{"},oid":"58dc04a9fbca629d612f190d"},"memberID":"114534","gender":"M","age":"24","ethnicOriginCountryName":"United Kingdom","sect":"SU"},
]
</code>```

答:
Using N command in sed has its limitations. It works if the input is pair of lines. In your case the input is not just pair of lines, but rather a paragraph ended by ].

The solution is to keep reading the whole paragraph, then replacing \n,] with ,], then finally printing the paragraph.

```<code>sed -e '1h;1!H;/]/!d' -e 'x;s/,\n]/]/;s/]\n//' test9
</code>```

Here's what each of those sed commands do:

1h - if it is line 1, replace hold space with the contents of pattern space.

1!H - except line 1, append a newline followed by the contents of pattern space to the hold space.

/]/!d - delete pattern space except when it contains pattern /]/.

x - swap the contents of the pattern and hold spaces.

s/,\n]/]/ - replace ,\n] with ,].

s/]\n// - remove the pattern ]\n which were inadvertenly pre-pended.

One word of advise, sed is not the right tool when working on json objects. Use jq. Your input seems to be a broken (mangled) json therefore jq will no longer work on it.

Thanks to @Yunnosch for some help.

Body:
when I apply the following to the tail of a file:

tail test9 | sed -e '/},/N;s/,\n*\]/]/g' >wtf

I get the correct result:

{"_id":{"},oid":"58dc04a9fbca629d612f1905"},"memberID":"114526","gender":"M","a    ge":"33","ethnicOriginCountryName":"Egypt","sect":"SU"},
{"_id":{"},oid":"58dc04a9fbca629d612f190d"},"memberID":"114534","gender":"M","age":"24","ethnicOriginCountryName":"United Kingdom","sect":"SU"}]

however when using cat

cat test9 | sed -e '/},/N;s/,\n*\]/]/g' >wtf

I do not get the correct result:

{"_id":{"},oid":"58dc04a9fbca629d612f1905"},"memberID":"114526","gender":"M","age":"33","ethnicOriginCountryName":"Egypt","sect":"SU"},
{"_id":{"},oid":"58dc04a9fbca629d612f190d"},"memberID":"114534","gender":"M","age":"24","ethnicOriginCountryName":"United Kingdom","sect":"SU"},
]

Body:
Using N command in sed has its limitations. It works if the input is pair of lines. In your case the input is not just pair of lines, but rather a paragraph ended by ].

The solution is to keep reading the whole paragraph, then replacing \n,] with ,], then finally printing the paragraph.

sed -e '1h;1!H;/]/!d' -e 'x;s/,\n]/]/;s/]\n//' test9

Here's what each of those sed commands do:

1h - if it is line 1, replace hold space with the contents of pattern space.

1!H - except line 1, append a newline followed by the contents of pattern space to the hold space.

/]/!d - delete pattern space except when it contains pattern /]/.

x - swap the contents of the pattern and hold spaces.

s/,\n]/]/ - replace ,\n] with ,].

s/]\n// - remove the pattern ]\n which were inadvertenly pre-pended.

One word of advise, sed is not the right tool when working on json objects. Use jq. Your input seems to be a broken (mangled) json therefore jq will no longer work on it.

Thanks to @Yunnosch for some help.


问:
Using PouchDB with SQL Server and CouchDB
I know that PouchDB only works with CouchDB compatible servers. Is there a way to use SQL Server as a backend while maintaining its original schema?

I have a thought how to accomplish this but I am not entirely sure if it is feasible. Any answer that will lead this to fruition will be appreciated.

The way I see it can be done is by using CouchDB to store the sync metadata like revisions and all things needed for a successful sync. The actual latest data will then be stored on the SQL Server following its original schema.

To be able to accomplish this I need to create a CouchDB compatible server using my stack which is C#. This will act like a proxy in between CouchDB and PouchDB so I don't actually need to implement all methods. I will have to intercept certain methods that will allow me to keep SQL Server and CouchDB in sync (following business rules) on the server at the same time take advantage of CouchDB's sync capability over the SQL Server Data. With this in place I could also add a bunch of middleware I wish in the future.

Is this thing feasible? I know that express-pouchdb exist but it is just a CouchDB compatible server with a PouchDB backend. What I wanted is to make the CouchDB and SQL Server work together. If so, how should I go about it?

答:
Might sound like a crazy idea, but you can use PouchDB on the server and plug in an alternative storage adapter that uses SQL Server. That way you don't need to reimplement the replication logic (this is really hard), you can concentrate on the storage part.

Some pointers:

https://pouchdb.com/adapters.html

https://github.com/Level/leveldown

https://github.com/calvinmetcalf/sqldown


问:
Create NSArray with row content (MySQL)
I want to create a NSArray witch contains the content of a MySQL table row

I use a php script to get the data

```<code>$response = $bdd->query('SELECT * FROM iPhoneTests');

while ($datas = $response->fetch())
{
?>
    <array>
    <integer><?php echo $datas['Temperature']; ?></integer>
    </array>

<?php
}
</code>```

and to test Iuse this code in my app

```<code>    NSURL *getTemperature = [NSURL URLWithString:@"myURL..."];
    NSError* error;
    temperature = [NSArray arrayWithContentsOfURL:getTemperature ];
    NSLog(@"%@",temperature);
</code>```

When I test in my web broswer I get all my datas but in my app, with the NSlog I only get the first value.

I on this problem since a few time, but I can't succeed
If someone see my mistake please tell me

答:
You are creating an array for each row (which by the way is invalid, because those arrays would have to be nested into an array, too).

Do it in this way:

```<code>$response = $bdd->query('SELECT * FROM iPhoneTests');
?><array><?
while ($datas = $response->fetch())
{
?>
    <integer><?php echo $datas['Temperature']; ?></integer>
<?
}
?></array>
</code>```

Title: Create NSArray with row content (MySQL)

Body:
I want to create a NSArray witch contains the content of a MySQL table row

I use a php script to get the data

$response = $bdd->query('SELECT * FROM iPhoneTests');

while ($datas = $response->fetch())
{
?>
    <array>
    <integer><?php echo $datas['Temperature']; ?></integer>
    </array>

<?php
}

and to test Iuse this code in my app

    NSURL *getTemperature = [NSURL URLWithString:@"myURL..."];
    NSError* error;
    temperature = [NSArray arrayWithContentsOfURL:getTemperature ];
    NSLog(@"%@",temperature);

When I test in my web broswer I get all my datas but in my app, with the NSlog I only get the first value.

I on this problem since a few time, but I can't succeed
If someone see my mistake please tell me

Body:
You are creating an array for each row (which by the way is invalid, because those arrays would have to be nested into an array, too).

Do it in this way:

$response = $bdd->query('SELECT * FROM iPhoneTests');
?><array><?
while ($datas = $response->fetch())
{
?>
    <integer><?php echo $datas['Temperature']; ?></integer>
<?
}
?></array>


问:
Unity touch watcher implementation

I'm trying to implement my swipeManager class into Unity,

all the logic's done, but I need to make sure the class's called once and that it's update() function is called BEFORE the rest checks if (e.g.) swipeManager.swipe.upToDown is true...

Of course i prepared the manager to be static, in order to avoid calling it multiple times (in fact I cannot rely on the automatic update() )...

I'm a total newbie on Unity, so feel free to correct me, I'm actually trying to learn as I develop, so I miss a bit of theory atm (going to learn it soon).

I have both a start and an update function, feel free to call them in comments to say "and here you go with your code".

Thanks in advance!

答:
You can check here for the Unity event functions order or you chan tale a look at here if you want to priorize scripts execution order.

Hope it helps.

Title: Unity touch watcher implementation


问:
Row not adding in grid control devExpress
am adding row in grid control through column view. But it is not working. Even though I am providing correct information.

```<code>private void Home_Load(object sender, EventArgs e)
{
    int counter;
    readStudent();
    ColumnView view = gridControl1.FocusedView as ColumnView;

    foreach (PAT p in pt_list)
    {
        String s1 = p.name;

        view.AddNewRow(); //Problem here:not adding row
        int count = view.RowCount-1;
        view.SetRowCellValue(view.GetRowHandle(count), "PAT Name", s1);

        foreach(Student1 student in st_lst)
        {
            counter = 1;
            foreach (Allocate al in al_list) {
            if (p.ID == al.AID && student.UOB == al.AUOB)
            {

                String s = student.name;
                view.SetRowCellValue(view.GetRowHandle(count), "Student "+ counter, s);

                counter++;
            }
        }

    }
    gridControl1.DataSource = view;
}
</code>```

can anybody help me with that

答:
I don't think this is still active but you cannot use the GridView as gridControl1.DataSource. This has to be a data-construct and not a sub-part of the GridControl itself. So use a list of objects or a DataTable as dataSource and add your new student there.

See the DevExpress help on how to bind a list of objects.

Body:
am adding row in grid control through column view. But it is not working. Even though I am providing correct information.

private void Home_Load(object sender, EventArgs e)
{
    int counter;
    readStudent();
    ColumnView view = gridControl1.FocusedView as ColumnView;

    foreach (PAT p in pt_list)
    {
        String s1 = p.name;

        view.AddNewRow(); //Problem here:not adding row
        int count = view.RowCount-1;
        view.SetRowCellValue(view.GetRowHandle(count), "PAT Name", s1);

        foreach(Student1 student in st_lst)
        {
            counter = 1;
            foreach (Allocate al in al_list) {
            if (p.ID == al.AID && student.UOB == al.AUOB)
            {

                String s = student.name;
                view.SetRowCellValue(view.GetRowHandle(count), "Student "+ counter, s);

                counter++;
            }
        }

    }
    gridControl1.DataSource = view;
}

can anybody help me with that


问:
Cordova can't find my Java installation, but JAVA_HOME looks valid. What's going on?
Windows 7 64-bit, with 64-bit JDK.  Cordova plugman 1.4.2-dev.  Using cygwin bash as a shell, but I don't see why that would affect anything.

```<code>$ echo $JAVA_HOME
"c:\Program Files\Java\jdk1.8.0_25"

$ echo $ANDROID_HOME
C:\Users\admin\AppData\Local\Android\Sdk

$ ls "c:\Program Files\Java\jdk1.8.0_25"
bin        include         lib          release
COPYRIGHT  javafx-src.zip  LICENSE      THIRDPARTYLICENSEREADME.txt
db         jre             README.html  THIRDPARTYLICENSEREADME-JAVAFX.txt

$ ./main.js install --platform android --project ../myproject/ --plugin phonegap-facebook-plugin-gtg --variable APP_ID="1155264567919069" --variable APP_NAME="Voice Test"
Fetching plugin "phonegap-facebook-plugin-gtg" via npm
Installing "phonegap-facebook-plugin" for android
Failed to install 'phonegap-facebook-plugin':CordovaError: Failed to run "javac -version", make sure that you have a JDK installed.
You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.
Your JAVA_HOME is invalid: "c:\Program Files\Java\jdk1.8.0_25"
</code>```

I've also tried using JAVA_HOME without the quotes.  What's going on?

答: @cubrr gave the correct answer in the comments.  The error message being produced by Cordova is extremely misleading: the problem isn't that JAVA_HOME was incorrect, but that javac wasn't on my path. This was made all the more confusing by the fact that java was on my path, so when I checked it gave correct results.  This is because the Oracle installer adds a directory to your path (c:\ProgramData\Oracle\Java\javapath) that contains links to java.exe and related programs but not the relevant JDK programs.

Body:
Windows 7 64-bit, with 64-bit JDK.  Cordova plugman 1.4.2-dev.  Using cygwin bash as a shell, but I don't see why that would affect anything.

$ echo $JAVA_HOME
"c:\Program Files\Java\jdk1.8.0_25"

$ echo $ANDROID_HOME
C:\Users\admin\AppData\Local\Android\Sdk

$ ls "c:\Program Files\Java\jdk1.8.0_25"
bin        include         lib          release
COPYRIGHT  javafx-src.zip  LICENSE      THIRDPARTYLICENSEREADME.txt
db         jre             README.html  THIRDPARTYLICENSEREADME-JAVAFX.txt

$ ./main.js install --platform android --project ../myproject/ --plugin phonegap-facebook-plugin-gtg --variable APP_ID="1155264567919069" --variable APP_NAME="Voice Test"
Fetching plugin "phonegap-facebook-plugin-gtg" via npm
Installing "phonegap-facebook-plugin" for android
Failed to install 'phonegap-facebook-plugin':CordovaError: Failed to run "javac -version", make sure that you have a JDK installed.
You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.
Your JAVA_HOME is invalid: "c:\Program Files\Java\jdk1.8.0_25"

I've also tried using JAVA_HOME without the quotes.  What's going on?


问:
How to create a new column, by variable?
My data includes data on different people (ID) over each Day of the week and the time they spend in different areas of the hospital or Ward. I am given this time, in minutes:seconds or Duration. An example of my data is:

```<code>ShiftData <- data.frame(ID = c("Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin",
                      "Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin"),
               Day = c("Monday", "Monday", "Monday", "Monday", "Monday",
                       "Monday", "Monday", "Monday", "Monday", "Monday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday"),
               Ward = c("Gen", "Anaesth", "Front Desk", "PreOp", "Front Desk",
                       "PreOp", "Front Desk", "Anaesth", "Front Desk", "Gen",
                       "Gen", "Anaesth", "PreOp", "Front Desk", "Gen",
                       "Front Desk", "PreOp", "PostOp", "Front Desk", "Anaesth"),
               Duration = c("5:35", "4:08", "4:30", "6:33", "4:17",
                            "15:35", "4:28", "9:37", "18:33", "4:20",
                            "9:45", "8:28", "6:37", "2:34", "4:27",
                            "19:35", "4:20", "9:47", "11:33", "4:26"))
</code>```

I first wish to include a column that indicates when each ID was on a rotation or shift. A "Front Desk" in the Ward column indicates when a person alters their shift. A person may start on "Front Desk", regulated by how many hours they work the day before (this calculation not required for the current analysis). My anticipated output would
    be:

```<code>ShiftData$Shift <- c(1,1,0,2,0,
                     1,0,2,0,3,
                     1,1,1,0,2,
                     0,1,1,0,2)
</code>```

My question is similar to this question except when there is a "Front Desk" I want a 0 and any activity afterward, to count sequentially up.

How do I please create this?

I know that I can include a 0 for "Front Desk" using:

```<code>ShiftData$Shift <- ifelse(ShiftData$Ward=='Front Desk', 0, NA)
</code>```

But I am unsure how to include a sequential count for every other part of the column?

答:
This problem can be solved with dplyr:

```<code>ShiftData$Shift <- (ShiftData %>%
                    group_by(ID,Day) %>%
                    mutate(tmp = ifelse(Ward=="Front Desk",1,0), #tag to sum front desk shifts
                           tmp2 = cumsum(tmp),                   #cumsum shows shifts in a day
                           Ward1 = Ward[1],                      #this and the below count your first shift if you didn't start on desk duty
                           shift = ifelse(Ward1=="Front Desk",tmp2,tmp2+1))
                    )$shift
ShiftData$Shift[ShiftData$Ward=="Front Desk"] <- 0
</code>```

Body:
My data includes data on different people (ID) over each Day of the week and the time they spend in different areas of the hospital or Ward. I am given this time, in minutes:seconds or Duration. An example of my data is:

ShiftData <- data.frame(ID = c("Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin",
                      "Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin"),
               Day = c("Monday", "Monday", "Monday", "Monday", "Monday",
                       "Monday", "Monday", "Monday", "Monday", "Monday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday"),
               Ward = c("Gen", "Anaesth", "Front Desk", "PreOp", "Front Desk",
                       "PreOp", "Front Desk", "Anaesth", "Front Desk", "Gen",
                       "Gen", "Anaesth", "PreOp", "Front Desk", "Gen",
                       "Front Desk", "PreOp", "PostOp", "Front Desk", "Anaesth"),
               Duration = c("5:35", "4:08", "4:30", "6:33", "4:17",
                            "15:35", "4:28", "9:37", "18:33", "4:20",
                            "9:45", "8:28", "6:37", "2:34", "4:27",
                            "19:35", "4:20", "9:47", "11:33", "4:26"))

I first wish to include a column that indicates when each ID was on a rotation or shift. A "Front Desk" in the Ward column indicates when a person alters their shift. A person may start on "Front Desk", regulated by how many hours they work the day before (this calculation not required for the current analysis). My anticipated output would
    be:

ShiftData$Shift <- c(1,1,0,2,0,
                     1,0,2,0,3,
                     1,1,1,0,2,
                     0,1,1,0,2)

My question is similar to this question except when there is a "Front Desk" I want a 0 and any activity afterward, to count sequentially up.

How do I please create this?

I know that I can include a 0 for "Front Desk" using:

ShiftData$Shift <- ifelse(ShiftData$Ward=='Front Desk', 0, NA)

But I am unsure how to include a sequential count for every other part of the column?

Body:
This problem can be solved with dplyr:

ShiftData$Shift <- (ShiftData %>%
                    group_by(ID,Day) %>%
                    mutate(tmp = ifelse(Ward=="Front Desk",1,0), #tag to sum front desk shifts
                           tmp2 = cumsum(tmp),                   #cumsum shows shifts in a day
                           Ward1 = Ward[1],                      #this and the below count your first shift if you didn't start on desk duty
                           shift = ifelse(Ward1=="Front Desk",tmp2,tmp2+1))
                    )$shift
ShiftData$Shift[ShiftData$Ward=="Front Desk"] <- 0


问:
Why aren't both "for loops" working?
```<code>import csv

def csv_reader(file_obj):
    reader = csv.reader(file_obj)
    # for row in reader:
        # print(" ".join(row))

    reader_2 = csv.DictReader(file_obj, delimiter=",")
    for row_2 in reader_2:
        print(row_2)

csv_path = "data.csv"
with open(csv_path, "r") as f_obj:
    csv_reader(f_obj)
</code>```

<p>I can't figure out why the second "for loop" only prints any text if the first "for loop" is commented out. </p>

答:
The CSV reader has already consumed your file.
Calling file_obj.seek(0) before using it again should do the trick.

Alternatively, opening (and then closing) the file for each operation will also work.

Title: Why aren't both "for loops" working?

Body:
import csv

def csv_reader(file_obj):
    reader = csv.reader(file_obj)
    # for row in reader:
        # print(" ".join(row))

    reader_2 = csv.DictReader(file_obj, delimiter=",")
    for row_2 in reader_2:
        print(row_2)

csv_path = "data.csv"
with open(csv_path, "r") as f_obj:
    csv_reader(f_obj)

I can't figure out why the second "for loop" only prints any text if the first "for loop" is commented out.


答: It's because you are passing the same file handler to both csv reader objects. Once you iterate over it once, you have to manually do file_obj.seek(0) for it to work as intended, or else it simply acts like an empty file.

Title: Why aren't both "for loops" working?


问:
Border CSS, colour a certain percentage
I want to achieve this effect:

You see that the orange colour is only 35% of the whole border. How can I do this?

HTML:

```<code><div id="test">
    <h1> hello</h1>
</div>
</code>```

CSS:

```<code>h1 {
    line-height: 80px;
    font-size: 20px;
    font-family: Arial;
}

#test {
    margin: auto;
    text-align: center;
    border-radius: 50%;
    height: 80px;
    width: 80px;
    border: 5px solid black;
}
</code>```

答:
Here's one way to do it with svg and some trickery using stroke dash array offsets.

http://codepen.io/flurrd/pen/zZyrBx?editors=1100

```<code><div class="container">

<h1>50%</h1>
<svg
    x="0px"
    y="0px"
    viewBox="0 0 397.6 435.3"
    enable-background="new 0 0 397.6 435.3"
    xml:space="preserve"
    class="svg"
    >
      <circle
        class="circle-bg"
        cx="198.3"
        cy="217.3"
        r="139.2"
        transform="rotate(270 198.3 217.3)"
        />

      <circle
        class="circle"
        cx="198.3"
        cy="217.3"
        r="139.2"
        transform="rotate(270 198.3 217.3)"
        />
  </svg>
</div>
</code>```

SCSS

```<code>body{
  display: flex;
  justify-content: center;
  align-items: center;
}

//circumference = 2πr
// svg circle radius is 139

$pi: 3.14159265358979;
$Twopi: $pi * 2;

$circumference: calc(#{$Twopi} * 139);
$arc-length-percent: 0.5;

.circle {
  fill: none;
  stroke-width: 10px;
  stroke: tomato;
  //0.5 - 50%
  stroke-dasharray: calc(#{$arc-length-percent} * #{$circumference}) $circumference;
}

.circle-bg {
  fill: none;
  stroke-width: 10px;
  stroke: grey;
}

//layout stuff

.container {
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  font-family: sans-serif;
}

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</code>```

Compiled CSS

```<code>body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.circle {
  fill: none;
  stroke-width: 10px;
  stroke: tomato;
  stroke-dasharray: calc(0.5 * calc(6.28319 * 139)) calc(6.28319 * 139);
}

.circle-bg {
  fill: none;
  stroke-width: 10px;
  stroke: grey;
}

.container {
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  font-family: sans-serif;
}

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</code>```

Title: Border CSS, colour a certain percentage

Body:
I want to achieve this effect:

You see that the orange colour is only 35% of the whole border. How can I do this?

HTML:

 hello

CSS:

h1 {
    line-height: 80px;
    font-size: 20px;
    font-family: Arial;
}

#test {
    margin: auto;
    text-align: center;
    border-radius: 50%;
    height: 80px;
    width: 80px;
    border: 5px solid black;
}

Body:
Here's one way to do it with svg and some trickery using stroke dash array offsets.

http://codepen.io/flurrd/pen/zZyrBx?editors=1100

<div class="container">

<h1>50%</h1>
<svg
    x="0px"
    y="0px"
    viewBox="0 0 397.6 435.3"
    enable-background="new 0 0 397.6 435.3"
    xml:space="preserve"
    class="svg"
    >
      <circle
        class="circle-bg"
        cx="198.3"
        cy="217.3"
        r="139.2"
        transform="rotate(270 198.3 217.3)"
        />

      <circle
        class="circle"
        cx="198.3"
        cy="217.3"
        r="139.2"
        transform="rotate(270 198.3 217.3)"
        />
  </svg>
</div>

SCSS

body{
  display: flex;
  justify-content: center;
  align-items: center;
}

//circumference = 2πr
// svg circle radius is 139

$pi: 3.14159265358979;
$Twopi: $pi * 2;

$circumference: calc(#{$Twopi} * 139);
$arc-length-percent: 0.5;

.circle {
  fill: none;
  stroke-width: 10px;
  stroke: tomato;
  //0.5 - 50%
  stroke-dasharray: calc(#{$arc-length-percent} * #{$circumference}) $circumference;
}

.circle-bg {
  fill: none;
  stroke-width: 10px;
  stroke: grey;
}

//layout stuff

.container {
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  font-family: sans-serif;
}

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

Compiled CSS

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.circle {
  fill: none;
  stroke-width: 10px;
  stroke: tomato;
  stroke-dasharray: calc(0.5 * calc(6.28319 * 139)) calc(6.28319 * 139);
}

.circle-bg {
  fill: none;
  stroke-width: 10px;
  stroke: grey;
}

.container {
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

h1 {
  font-family: sans-serif;
}

svg {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}


问:
How to render simple React component in MVC6 application, for dummies
I have a simple mvc6 site solution in Visual Studio 2015.

In one of my pages, I have

```<code><script type="text/jsx">
    ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById('react-app-mount'));
</script>
</code>```

But the component does not render. What scripts do I have to include in the page to make it render?
I am a total newbie to react.

Trying to figure it out on my own I got extremely confused with the gazillion of terms like 'npm, bower, babel' but nowhere I can find a decent from-scratch example on how to use those things in Visual Studio 2015. Moreover, I find suggestions that just don't work.

For instance, I read something like "you should run npm install babel", but nobody gives information on where in visual studio I should execute this command. Others speak about a package.json file that is supposed to exist somewhere in my solution, but it is just not there.

I really don't understand why things are so extremely complicated. In the old days, when you wanted to use a library, you just put a

答:
The scripts that you have to import are:

```<code><script src="https://unpkg.com/react@latest/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</code>```

But this is not the right way to do, It is for getting a demo of React.

If you want to get started with react, This might help you.
https://github.com/facebookincubator/create-react-app

Body:
I have a simple mvc6 site solution in Visual Studio 2015.

In one of my pages, I have

But the component does not render. What scripts do I have to include in the page to make it render?
I am a total newbie to react.

Trying to figure it out on my own I got extremely confused with the gazillion of terms like 'npm, bower, babel' but nowhere I can find a decent from-scratch example on how to use those things in Visual Studio 2015. Moreover, I find suggestions that just don't work.

For instance, I read something like "you should run npm install babel", but nobody gives information on where in visual studio I should execute this command. Others speak about a package.json file that is supposed to exist somewhere in my solution, but it is just not there.

I really don't understand why things are so extremely complicated. In the old days, when you wanted to use a library, you just put a

Body:
The scripts that you have to import are:

<script src="https://unpkg.com/react@latest/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

But this is not the right way to do, It is for getting a demo of React.

If you want to get started with react, This might help you.
https://github.com/facebookincubator/create-react-app


问:
how can i send facebook message using selenium webdriver
I am able to login on facebook, able to open chat but unable to send any message
Below program code I have used:

//Login on FB >> Working fine

```<code>driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("******@gmail.com");
driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("********");
driver.findElement(By.xpath(".//*[@id='u_0_l']")).click();
</code>```

// click on message icon >> Working fine

```<code> driver.findElement(By.xpath(".//*[@id='u_0_h']/li[1]/div/a/span")).click();
</code>```

//click on friends name, to whom i want to send message >> Working fine

```<code>driver.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div/div[1]/div/div/div[2]/ul/li[5]/div/div[2]/div/div[3]/div/div[1]/div/div/ul/li[2]/a")).click();
Thread.sleep(5000);
</code>```

//Send message    >>>> here, i am not getting any response, code run without entered any message or error

```<code>driver.findElement(By.xpath(".//*[@class='_552h _35li _n4k']")).sendKeys("Hiii");
driver.findElement(By.xpath("/html/body/div/div[5]/div[1]/div/div/div[1]/div/div[1]/div[2]/div/div/div/div/div[4]/div[5]/div[1]/div/div/div[2]/div/div/div")).sendKeys(Keys.ENTER);;
</code>```

答:
The correct answer since the @role has changed is :

```<code>WebElement sendmsg = driver
            .findElement(By.xpath("//div[@class='_1ia']/descendant::div[@class='_5rpu' and @role='combobox']"));
sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);
</code>```

Body:
I am able to login on facebook, able to open chat but unable to send any message
Below program code I have used:

//Login on FB >> Working fine

driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("******@gmail.com");
driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("********");
driver.findElement(By.xpath(".//*[@id='u_0_l']")).click();

// click on message icon >> Working fine

 driver.findElement(By.xpath(".//*[@id='u_0_h']/li[1]/div/a/span")).click();

//click on friends name, to whom i want to send message >> Working fine

driver.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div/div[1]/div/div/div[2]/ul/li[5]/div/div[2]/div/div[3]/div/div[1]/div/div/ul/li[2]/a")).click();
Thread.sleep(5000);

//Send message    >>>> here, i am not getting any response, code run without entered any message or error

driver.findElement(By.xpath(".//*[@class='_552h _35li _n4k']")).sendKeys("Hiii");
driver.findElement(By.xpath("/html/body/div/div[5]/div[1]/div/div/div[1]/div/div[1]/div[2]/div/div/div/div/div[4]/div[5]/div[1]/div/div/div[2]/div/div/div")).sendKeys(Keys.ENTER);;

Body:
The correct answer since the @role has changed is :

WebElement sendmsg = driver
            .findElement(By.xpath("//div[@class='_1ia']/descendant::div[@class='_5rpu' and @role='combobox']"));
sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);


问:
How can I make a random set generator with equal possibility to generate uniform sets and non-uniform sets?
So let's say I have a set of items:

```<code>['a', 'b', 'c', 'd', 'e']
</code>```

and I want to generate a random set (order does not matter) from those choices:

```<code>['a', 'e', 'd', 'c']
</code>```

which is child's play, but instead of it being unlikely to generate a uniform result:

```<code>['c', 'c', 'c', 'c']
</code>```

compared to something less uniform like:

```<code>['a', 'b', 'e', 'd']
</code>```

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

答:
This can in fact be done.  Just get a random number, and if it is over 0.5 then generate a random set, otherwise generate an extreme set from a random index.  See the following code:</p>

```<code>function generateRandomOrExtremeSet(a) {
   var n = Math.random();
   var set = [];
   if (n > 0.5)
      for (var i = 0; i < a.length; ++i)
         set[i] = a[Math.round(Math.random()*(a.length-1))];
   else {
      var index  = Math.round(Math.random() * (a.length-1));
      for (var i = 0; i < a.length; ++i) {
         if (Math.random() > 0.8) // change to adjust extremeness
            set[i] = a[Math.round(Math.random()*(a.length-1))];
         else
            set[i] = a[index];
      }
   }
   return set;
}
</code>```

Body:
So let's say I have a set of items:

['a', 'b', 'c', 'd', 'e']

and I want to generate a random set (order does not matter) from those choices:

['a', 'e', 'd', 'c']

which is child's play, but instead of it being unlikely to generate a uniform result:

['c', 'c', 'c', 'c']

compared to something less uniform like:

['a', 'b', 'e', 'd']

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

Body:
This can in fact be done.  Just get a random number, and if it is over 0.5 then generate a random set, otherwise generate an extreme set from a random index.  See the following code:

function generateRandomOrExtremeSet(a) {
   var n = Math.random();
   var set = [];
   if (n > 0.5)
      for (var i = 0; i < a.length; ++i)
         set[i] = a[Math.round(Math.random()*(a.length-1))];
   else {
      var index  = Math.round(Math.random() * (a.length-1));
      for (var i = 0; i < a.length; ++i) {
         if (Math.random() > 0.8) // change to adjust extremeness
            set[i] = a[Math.round(Math.random()*(a.length-1))];
         else
            set[i] = a[index];
      }
   }
   return set;
}


问:
JSON schema is incorrect
I'm making a JSON schema and I'm using https://tonicdev.com/npm/ajv to validate a schema against some data.
I'm not able to post code here due to confidentiality of the company, so I'll try to describe the problem:

I have 3 input fields, the first is a selector (string), the second an operator dropdown(equal, not equal, in, ni, etc) and the third is an input field that contains a value.

The idea is to have this structure "selector: operator: value ".
To clarify, say we have this JSON and imagine we have three variables selector, operator and value as schema (the idea is to get those values from the input fields mentioned above and create the schema).

```<code>const currentData = {
    "properties": {
         "id": "one",
         "string": 'some string...'
    }
}
</code>```

and I need to define the schema

```<code>const schema = {
    "properties": {
       [selector]: {"type": "string"},
       [operator]: {"type":"string"},
       [value]: {"type": string}
     }
}
</code>```

If I complete the fields with say (selector: id Operator: Equal value: "one") it should pass the validation, but if I say (selector: id  Operator: Equal value: 1) it should not pass.

This schema is wrong. Any ideas of how to define it?

答:
The documentation for ajv schema mentions specific details about how to do this with patterns.

Hope that helps!

Title: JSON schema is incorrect

Body:
I'm making a JSON schema and I'm using https://tonicdev.com/npm/ajv to validate a schema against some data.
I'm not able to post code here due to confidentiality of the company, so I'll try to describe the problem:

I have 3 input fields, the first is a selector (string), the second an operator dropdown(equal, not equal, in, ni, etc) and the third is an input field that contains a value.

The idea is to have this structure "selector: operator: value ".
To clarify, say we have this JSON and imagine we have three variables selector, operator and value as schema (the idea is to get those values from the input fields mentioned above and create the schema).

const currentData = {
    "properties": {
         "id": "one",
         "string": 'some string...'
    }
}

and I need to define the schema

const schema = {
    "properties": {
       [selector]: {"type": "string"},
       [operator]: {"type":"string"},
       [value]: {"type": string}
     }
}

If I complete the fields with say (selector: id Operator: Equal value: "one") it should pass the validation, but if I say (selector: id  Operator: Equal value: 1) it should not pass.

This schema is wrong. Any ideas of how to define it?