Diplaying multiple names from ListView into a single view

Question: I'm using a ListView to display an array of names.
Code for it looks like this:
public class Imenik extends ListActivity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  final String[] seznam = getResources().getStringArray(R.array.seznam_array);
  setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, seznam));

  final ListView lv = getListView();
  lv.setTextFilterEnabled(true);

  lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if ("Baj And".equals(seznam[position]))
            { Intent i = new Intent(Imenik.this,Bajzelj.class); startActivity(i); lv.getItemIdAtPosition(position); }
            else if ("Bes Jaz".equals(seznam[position]))
            { Intent i = new Intent(Imenik.this,Bajzelj.class); startActivity(i); }
        }
      });
    }

}

Now I would like to display this names into just one view (Only one name per choice) with different data (one xml file).
public class Bajzelj extends Activity {

int position;

    /** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    this.setTitle("Interni imenik");
    setContentView(R.layout.main);

    final String[] seznam = getResources().getStringArray(R.array.seznam_array);

    {
    if  ("Bajželj Andrej".equals(seznam[position]))
    {
        TextView ime = (TextView) findViewById(R.id.ime);
        ime.setText("And Baj");
        TextView telefon = (TextView) findViewById(R.id.telefon);
        telefon.setText("Telefon: +386 1 476");
        TextView gsm = (TextView) findViewById(R.id.mobitel);
        gsm.setText("GSM: +386 41 ");
        TextView skype = (TextView) findViewById(R.id.skype);
        skype.setText("Skype: ba+");
        TextView email = (TextView) findViewById(R.id.email);
        email.setText("E-pošta: email@example.com");
        ImageView slika = (ImageView) findViewById(R.id.slika);
        slika.setImageResource(R.drawable.andbaj);
    }
    else if ("Bes Jan".equals(seznam[position]))
    {
        TextView ime = (TextView) findViewById(R.id.ime);
        ime.setText("Jan Bes");
        TextView telefon = (TextView) findViewById(R.id.telefon);
        telefon.setText("Telefon: +386 1 4");
        TextView gsm = (TextView) findViewById(R.id.mobitel);
        gsm.setText("GSM: +386 41 75");
        TextView skype = (TextView) findViewById(R.id.skype);
        skype.setText("Skype: sf");
        TextView email = (TextView) findViewById(R.id.email);
        email.setText("E-pošta: Jan.Besej.si");
        ImageView slika = (ImageView) findViewById(R.id.slika);
        slika.setImageResource(R.drawable.besjaz);
    }
    }
}

}
Is it possible to display them like this? I'm not a programmer so I'm having a lot of troubles with this one. I know that I should check for position somehow but I don't know how to do this?
Thanks in advance to anybody who is willing to help me.
Comment: I am not clear with the question... Can you please specify more clearly. You are displaying data in a list view from an array. When clicked on each item what you want to perform...?
Comment: I'm trying to do this - When I choose a name from listView I would like it to open an Activity Bajzelj. And then depending on the name I choose I would like to fill it with personal date (each person has different data). For activity Bajzelj I would like to use just one xml that has empty TextViews and ImageView.
Comment: Ok, I understood your requirement. where you are getting problem.. In preparing xml file or in fetching particular data.
Comment: In fetching particular data. It always shows just the first persons data and even when I choose second person from listview it show the same data again.
Answer: follow this more effective way.

Use a Map object to store individual user data.
Add these map objects to the List.
Use custom adapter to display in the ListView.
Whenever user clicks on particular list item, pass its position in intent.
get position from Bundle and retrieve the particular user data from map of List.
display all the data of the user.

If you want a code snippet send me the user data fields i can send you the code snippet.
here is the code.
Test.java
package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class Test extends Activity{
    public Map<String,Object> userData;
    public static List<Object> userList;

    String[] name = {"name_one","name_two","name_three","name_four","name_five"};
    String[] lastName = {"lastName_one","lastName_two","lastName_three","lastName_four","lastName_five"};
    String[] telephoneNumber = {"telephoneNumber_one","telephoneNumber_two","telephoneNumber_three","telephoneNumber_four","telephoneNumber_five"};
    String[] mobileNumber = {"mobileNumber_one","mobileNumber_two","mobileNumber_three","mobileNumber_four","mobileNumber_five"};
    String[] skypeUserName = {"skypeUserName_one","skypeUserName_two","skypeUserName_three","skypeUserName_four","skypeUserName_five"};
    String[] email = {"email_one","email_two","email_three","email_four","email_five"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        userList = new ArrayList<Object>();
        for(int i=0;i<5;i++){
            userList.add(getUserData(i));
        }
        ListView lv = (ListView)findViewById(R.id.list);
        ListCustAdapter adapter = new  ListCustAdapter(this, userList);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                Intent i = new Intent(Test.this,Test2.class);
                i.putExtra("position", position);
                startActivity(i);

            }
        });
    }

    public Map<String,Object> getUserData(int i){
        userData = new HashMap<String,Object>();
        userData.put("name", name[i]);
        userData.put("lastName", lastName[i]);
        userData.put("telephoneNumber", telephoneNumber[i]);
        userData.put("mobileNumber", mobileNumber[i]);
        userData.put("skypeUserName", skypeUserName[i]);
        userData.put("email", email[i]);
        return userData;
    }
}

Test2.java
package com.test;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test2 extends Activity{
    TextView name,lname,phono,cellno,sky,email;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test2);
        Bundle bundle = getIntent().getExtras();
        int position = bundle.getInt("position");
        name = (TextView)findViewById(R.id.name);
        lname = (TextView)findViewById(R.id.last_name);
        phono = (TextView)findViewById(R.id.telephoneNumber);
        cellno = (TextView)findViewById(R.id.mobileNumber);
        sky = (TextView)findViewById(R.id.skypeUserName);
        email = (TextView)findViewById(R.id.email);

        name.setText((String)((Map<String,Object>)Test.userList.get(position)).get("name"));
        lname.setText((String)((Map<String,Object>)Test.userList.get(position)).get("lastName"));
        phono.setText((String)((Map<String,Object>)Test.userList.get(position)).get("telephoneNumber"));
        cellno.setText((String)((Map<String,Object>)Test.userList.get(position)).get("mobileNumber"));
        sky.setText((String)((Map<String,Object>)Test.userList.get(position)).get("skypeUserName"));
        email.setText((String)((Map<String,Object>)Test.userList.get(position)).get("email"));

    }
}

ListCustAdapter.java
package com.test;

import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListCustAdapter extends BaseAdapter {
    public Activity context;
    private List<Object> list;

    public ListCustAdapter(Activity context, List<Object> list) {
        super();
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @SuppressWarnings("unchecked")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        TextView tv = new TextView(context);
        tv.setText((String) ((Map<String, Object>) list.get(position)).get("name"));
        return tv;
    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

  <ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/list"
    />

</LinearLayout>

test2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/name"/>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/last_name"/>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/telephoneNumber"/>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/mobileNumber"/>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/skypeUserName"/>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id = "@+id/email"/>

</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Test"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity android:name=".Test2"/>
    </application>
</manifest>

Then run and enjoy......!
Comment: Thank a code snippet would be just what I need. User data fields are: Name & Last name, Telephone number, mobile number, skype user name, Email.
Comment: @user925185 from where you are getting these data..? from an array for each field or some other means..?
Comment: I put them myself in. I have a function for each person that contains all the data for that person. I just need to figure out how to remeber the intents decision (which name I pick) and open the right one.
Comment: Thanks a lot. I owe you a couple of beers :) ... There is only thing that isn't working, a problem with userList in lines - name.setText((String)((Map)Test.userList.get(position)).get("name"));
Comment: I have tested it on my system everything is working fine... are you getting any error...?
Comment: Yes I'm getting an error with userList as I described above. And Eclipse is only offering me a solution: Rename in file. So application isn't going thrue.
Comment: I'm getting an error in Test2.java file with these two things Test.userList. - after I import junit.framework.Test; -> Test problem is resolved and I get notice that .userList - "userList cannot be resolved or is not a filed" ... so I can't compile this project because Eclipse won't let me until there are mistakes in it.
Answer: The way in which you are passing the ID to the new activity is strange.  Try using this:
Intent i = new Intent(Imenik.this,Bajzelj.class);
i.putExtra("id", id);
startActivity(i);

Then, once you're in your Bajzelj activity, get the id like this:
Bundle bundle = getIntent().getExtras();
long _id = bundle.getLong("id");


Power set-Commutative ring

Question: $\mathbb{Z},\mathbb{Q}$... are commutative rings because, for example, $xy=yx, x, y\in \mathbb{Z}$?
Could you give me examples for power set being commutative ring?
Answer: Let $X$ be a set; $\wp(X)$ becomes a Boolean ring when you take intersection as multiplication and symmetric difference as addition. This ring is isomorphic to the direct product of $|X|$ copies of the two-element ring.

Power set-Commutative ring


Matrix that satisfies polynomial $x^{n}-1$ is diagonalizable

Question: Let $A$ be an $n\times n$ matrix that satisfies the polynomial $p(x)=x^n-1$ (Update: $p$ is not necessarily the characteristic polynomial), that is $A^n-I=0$.
I am trying to prove that $A$ is diagonalizable over $\mathbb{C}$. (I am not sure if this is true yet.)

What I tried:
Let $\mu(x)$ be the minimal polynomial of $A$. Then $\mu(x)$ divides $p(x)$. Since $p(x)$ has no repeated roots, $\mu(x)$ has no repeated roots either.
Fact: The roots of $\mu(x)$ are precisely the eigenvalues of $A$.
Thus $A$ has distinct eigenvalues. If $A$ has $n$ distinct eigenvalues, then we are done.
However, $\mu(x)$ may be of degree less than $n$... I am stuck here.
Comment: [A matrix is diagonalizable iff its minimum polynomial can be factored and has roots all distinct.](https://en.wikipedia.org/wiki/Minimal_polynomial_(linear_algebra)#Applications) There need not be exactly $n$ of them.
Answer: Well, the point is: regardless of $p$ being the actual characteristic polynomial, $\mu$ divides $p$ and $p$ is square-free. Since $$p(x)=(x-\lambda_1)\cdots (x-\lambda_n)$$
with $\lambda_i=\lambda_j\Rightarrow i=j$, the fact that $\mu\mid p$ yields that $\mu$ is square-free, i.e. it cannot have distinct roots. So the matrix is diagonalizable in $\Bbb C$.
Comment: @G.S please go ahead and copy them. I don't intend to put an answer together from my phone
Comment: Ok I think I understand.
Comment: Wait... How do we know the eigenvalues are precisely the roots of $p$? ($p$ is not necessarily the characteristic polynomial here, sorry for the confusing notation)
Comment: @yoyostein we know that every eigenvalue is a root of $p$, but not that every root of $p$ is an eigenvalue.  This is enough, however, for us to know that if $p$ has no repeated roots, there are no repeated eigenvalues in the minimal polynomial.
Comment: @Omnomnomnom Shouldn't it be every eigenvalue is a root of the minimal polynomial and thus $p$, but not every root of $p$ is an eigenvalue?
Comment: Yeah, I wrote it backwards the first time
Comment: Oh, my! Sorry! All this time I thought $p$ was the characteristic polynomial!
Comment: @Omnomnomnom Since your comments solve the question, and correcting my post would amount to copy them, can you please write them as a full answer, so that I can remove this answer?
Comment: I don't quite understand the meaning of "square free". In my consideration square free means that it is of the form $(x-a_{1})(x-a_{2})..(x-a_{k})$. With all roots distinct. But then why do you say that "it cannot have distinct roots"?. And how do you come to the conclusion that A is diagonalizable in $\mathbb{C}$? . (By the way almost every matrix is diagonalizable in $\mathbb{C}$). The criterion I know says the opposite. That if the minimal polynomial is of the form $(x-a_{1})(x-a_{2})..(x-a_{k})$ then the matrix is diagonalizable!
Answer: All roots are different: use $(x^n-1,nx^{n-1})=1$, and there are $n$ of them. Therefore(/Moreover) the minimal polynomial is equal to the characteristic polynomial, since they have same roots and the latter has degree $n$.
Comment: See Arturo's answer: http://math.stackexchange.com/questions/56745/minimal-polynomial-and-diagonalizable-matrix
Comment: "Equals"? We only have tat it divides it -- it may not be equals to the characteristic polynomial.
Comment: @ClementC. ... since all of roots are distinct and need to be root of minimal polynomial.
Comment: Yes, but that relies on the fact that you have $n$ distinct roots. Phrased as in your answer, this seems to read "if the minimal polynomial has all roots that are different, then it is equal to the characteristic polynomial" (which is false). Writing "Therefore, since there are $n$ of them (and the characteristic polynomial has degree $n$), [...]$ would remove the ambiguity.
Comment: I was supposing we are talking under this question and I can't see how someone understand  "if the minimal polynomial has all roots that are different, then it is equal to the characteristic polynomial" because there is no "if the minimal polynomial has all roots that are ..." statement.
Comment: You literally wrote " All roots are different: [how to prove it]. **Therefore** (/Moreover) minimal polynomial equals to characteristic polynomial." (emphasis mine)
Comment: I really cant understand. Can you edit the answer?
Comment: OK -- I made a change, feel free to discard it. (Sorry for the extended conversation, and if it feels like nitpicking to you).
Comment: Update: $p$ isn't necessarily the characteristic polynomial
Comment: No, it is necessarily. Since degree of $x^n-1$  is $n$ and $A$ is an $n \times n$ matrix.
Comment: @studentforever I guess that here the OP is saying that $p(X)=X^n -1$ is not the characteristic polynomial, only that it is *a* polynomial such that $p(A)=0$. For instance, the characteristic polynomial could very well be $(X-1)^n$


App está fechando ao depurar no Android

Question: Estou tentando executar o app no Android, onde quero listar os dados cadastrados em uma tabela Mysql. Estou tentando dessa forma:
Conexão
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Conexao {

    public static String postDados(String urlUsuario, String parametrosUsuarios){

        URL url;
        HttpURLConnection connection = null;

        try{

           url = new URL(urlUsuario);

           connection = (HttpURLConnection) url.openConnection();

           connection.setRequestMethod("POST");
           connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
           connection.setRequestProperty("Content-Lenght","" + Integer.toString(parametrosUsuarios.getBytes().length));
           connection.setRequestProperty("Content-Language","pt-BR");
           connection.setUseCaches(false);
           connection.setDoInput(true);
           connection.setDoOutput(true);

           /*
           DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
           dataOutputStream.writeBytes(parametrosUsuarios);
           dataOutputStream.flush();
           dataOutputStream.close();
           */

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            outputStreamWriter.write(parametrosUsuarios);
            outputStreamWriter.flush();

           InputStream inputStream = connection.getInputStream();

           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
           String linha;
           StringBuffer resposta = new StringBuffer();

           while ((linha = bufferedReader.readLine()) != null){
                resposta.append(linha);
                resposta.append('\r');
           }

           bufferedReader.close();

           return resposta.toString();

        }catch (Exception erro){

            return null;
        }finally {

            if(connection != null){
                connection.disconnect();
            }
        }
    }
}

Listar dados
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ListarDados extends AppCompatActivity {

TextView txtListar;
public static TextView data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listar_dados);

        txtListar = (TextView) findViewById(R.id.data);

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if(networkInfo != null && networkInfo.isConnected()){

            new SolicitaDados().execute();

        }else {
            Toast.makeText(getApplicationContext(), "Nenhuma conexão ativa", Toast.LENGTH_LONG).show();
        }
    }

    private class SolicitaDados extends AsyncTask<Void, Void, Void> {

        String data = "";
        String dataParsed = "";
        String singleParsed = "";

        @Override
        protected Void doInBackground(Void... voids){

            try {
                URL url = new URL("http://192.168.0.13/projeto/android/listar.php");

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                InputStream inputStream = httpURLConnection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String linhas = "";

                while(linhas != null){

                    linhas = bufferedReader.readLine();

                    data = data + linhas;

                }

                JSONArray JA = new JSONArray(data);

                  for(int i = 0; i < JA.length(); i++){

                      JSONObject JO = (JSONObject) JA.get(i);

                      singleParsed = "Email: " + JO.get("Email") + "Senha :" + JO.get("Senha") + "\n";

                      dataParsed = dataParsed + singleParsed;

                  }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            ListarDados.data.setText(this.dataParsed);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Intent voltar = new Intent(ListarDados.this, ConteudoSistema.class);
        startActivity(voltar);
    }
}

O PHP está dessa forma:
<?php
$conexao = mysqli_connect('localhost','root','sucesso','projeto');

$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");

while($jm = mysqli_fetch_array($sql)){
       $mostrar[] = $jm["Email"];
       $mostrar[] =  $jm["Senha"];
}

echo json_encode($mostrar);

Quando tento executar, diz que o app parou e em seguida fecha. Na depuração, o erro é:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
                  Process: br.com.projeto.acessosistema, PID: 2192
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:318)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                      at java.lang.Thread.run(Thread.java:761)
                   Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
                      at br.com.projeto.acessosistema.ListarDados$SolicitaDados.doInBackground(ListarDados.java:88)
                      at br.com.projeto.acessosistema.ListarDados$SolicitaDados.doInBackground(ListarDados.java:56)
                      at android.os.AsyncTask$2.call(AsyncTask.java:304)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                      at java.lang.Thread.run(Thread.java:761)

A linha 88:
dataParsed = dataParsed + singleParsed;

A linha 56:
String singleParsed = "";

O que pode estar de errado?
Comment: Percebi que parece não funcionar com arquivos PHP, pois quando testei através do site http://myjson.com/ e depois com um arquivo js funcionou corretamente. O que pode ser?
Answer: Consegui resolver o fechamento automático. O problema era no PHP e ajustei o código para:
<?php
$conexao = mysqli_connect('localhost','root','sucesso','projetos');

$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");

$mostrar = array();
//$mostrar["dados"] = array();

foreach($sql as $linha){

$listar["Email"] = $linha["Email"];
$listar["Senha"] = $linha["Senha"];

array_push($mostrar,$listar);
}
echo json_encode($mostrar);

App está fechando ao depurar no Android


Where is compiler in exe programs?

Question: I know that for some code to work on computer, it should be compiled or interpreted, but some programs such as games or other desktop applications are run when clicked on. I wonder where the compiler or interpreter is. Is it embedded inside the program or there is something extremely advanced to understand?
Comment: It's on the person's machine who compiles the exe
Comment: A compiler is like a factory robot: it's only needed to create the executable code, but once the product is built you don't need it anymore to use the product.
Comment: Whereas an interpreter is indeed more like a CD player - you as the consumer do need it to use the CD.
Comment: thanks for your answers
Answer: exe programs like games are already the result of compiling. When you click on a exe, no compiler is necessary anymore. The compiler is on the computer of the developer.
Interpreted languages like Python or JavaScript need an engine to run on your computer. That is not the same as a compiler.

Where is compiler in exe programs?


How do I programmatically disable a filter from a text format?

Question: Suppose I have a text format like full_html and I have an enabled filter with ID my_filter_id.
How can I disable the filter programmatically from full_html.
I needed to put this in an update hook.
Hopefully its a one-liner.
Answer: I did find a solution thought it wasn't a one liner. This will remove the filter from all text formats.
use Drupal\filter\Entity\FilterFormat;

function MYMODULE_update_10000(&$sandbox) {
  $filters = filter_formats();
  foreach ($filters as $name => $filter) {

    /* @var $filter Drupal\filter\Entity\FilterFormat */
    // Instantiate the filter collection prior to removing the filters to
    // avoid fatal errors.
    $filter->filters();
    $filter->removeFilter('my_filter_id');
    $filter->save();
  }

}

I found the solution from Drupal.org


Facebook API (PHP) Post available to nobody but me

Question: I have a very strange problem. I developed a little PHP-Script and a Facebook-App which posts to my Pages. The App's permissions are: publish_actions and manage_pages.
And it works like a charm, with one major hook: These Posts aren't visible to anyone but me. They are showing up on my wall, I can see them on the Page and even in Insights, they're visible. See this: https://i.stack.imgur.com/NqgYt.png
As you can see it's a public post, and only one person saw it: me. Here's the direct link: https://www.facebook.com/permalink.php?story_fbid=793772960651385&id=110373632307818
if you click it you'll get the message: "This page is currently unavailable" ... or something like that.
Has anyone else had such a problem? Thanks in advance for any help.
EDIT: This is the code that does the job:
function page_message($page_id, $data){
    // my persistent access-token
    $user_access_token = '◼◼◼◼◼◼';

    $config = array();
    $config['appId'] = '353943021379058';
    $config['secret'] = '◼◼◼◼◼◼';
    $config['fileUpload'] = false; // optional

    $facebook = new Facebook($config);

    // get the list of my pages
    $response = $facebook->api("/gonzo187/accounts/", 'GET', array('access_token' => $user_access_token));

    $args = $data;

    $args['access_token']  = '';

    foreach($response["data"] as $page){
        if($page["id"] == $page_id){
            echo '');
            $args["access_token"] = $page["access_token"];
        }
    }

    if($args["access_token"]){
        $return = $facebook->api("/$page_id/feed", "post", $args); // It works!!
    }else{
        $return = false;
    }

    return $return;
}

EDIT2: the $data-Array:
$data = array(
    'page_id'   => '153090891543315',
    'data'      => array(
        'message'   => "wer watchng u!\n\nrly!",
        'link'      => "https://www.nsa.gov/",
    )
);

Comment: Can you provide your code?
Comment: Have you made your app public by disabling development mode in your app settings?
Comment: no i hadn't. it is now online. i left it in dev-mode to prevent listing in the app store. is there another way to prevent this?
Comment: Your app is only published, when you start a submission under `Submit Items for Approval`
Comment: Glad to hear; I would like to post it as answer to your question. Please approve it.
Answer: You have to disable developer mode in your app settings under review & status.
From the facebook docs

Development Mode
When testing your apps, place them into Development Mode. This hides
  your app entirely from all users who you have not authorized in the
  App Dashboard to see the app, for the roles described below. Please
  note that when your app is in Development Mode, you cannot call any
  API calls on behalf of users who cannot see your app.


What is the intuition behind A-λI?

Question: This is step one in a lot of problems I solve. It is a tool that I do not intuitively understand

We care about when it's determinant is 0 because then we can find eigenvalues.
We care about the kernel of resulting matrices after we substitute calculated eigenvalues in for λ.

Why is A-λI so magical?
Comment: Do you understand the eigenvalue problem? We're finding the solution of Ax=λx.
Comment: So then we are looking for a constant that can replace a linear transformation?
Comment: We're looking for such vectors x(the eigenvectors) and λ(the eigenvalues) satifies the equation, not a constant to replace a linear transformation. Solving eigenvalue problems can be useful, one example is the diagnozilation of matrix.
Answer: The null space of $A-\lambda I$ is precisely the eigenspace $E_\lambda$ of $A$ with eigenvalue $\lambda$.
Heuristically, I tend to think of it in terms of "prevailing winds". On $E_\lambda$, applying $A$ just scales input vectors $v$ by $\lambda$. Now imagine adding a "headwind" to $A$ which subtracts $\mu$ times $v$. On $E_\lambda$, that means $v$ will be scaled by $\lambda - \mu$. If we picked $\lambda - \mu = 1$, everything in $E_\lambda$ would be still, i.e. fixed. That's great and all, but the "most important" subspace of a linear operation is its kernel, not its fixed space. So if we pick $\lambda - \mu = 0$, everything in $E_\lambda$ will be in the kernel, which will be effectively making $E_\lambda$ the most important subspace.

What is the intuition behind A-λI?


Scroll to a particular position of an image inside ScrollView

Question: I have a long image inside a scrollview. On change of the time, I would like the scrollview scroll to the right.
ScrollView(.horizontal, showsIndicators: true, content: {
                    VStack {
                        Image(uiImage: s_img).resizable().frame(height:audioImageHeight)
                    }

                })

A few issues I have encountered here:

The width of the scrollview should be same as the image width. I therefore obtain the image width using UIImage. Originally I planned to use GeometryReader but fails to obtain that.
There will be a value change using a Timer. I would like the scrollview automatically scroll to the right when the timer start
I tried to use ScrollViewReader or ScrollViewProxy, none of them work. Most of the answers in the forum can use proxy.scrollTo() but normally there is a "id" to scroll to that position. In my case, there is no Id, the position is the offset of the ScrollView content. In the past, it was achieve by UIScrollView.setContentOffset(). How to achieve in Swiftui?
Answer: Just give your image an id and your be able to scroll to its unipoints.
struct ContentView: View {

    var body: some View {
        ScrollViewReader { proxy in
            VStack {
                Button("Scroll to Bottom rigth of the contents") {
                    withAnimation {
                        proxy.scrollTo(10001, anchor: .bottomTrailing)
                    }
                }
                Button("Scroll to Top left of the contents") {
                    withAnimation {
                        proxy.scrollTo(10001, anchor: .topLeading)
                    }
                }
            }
            .buttonStyle(.bordered)
            ScrollView([.horizontal, .vertical]) {

                Image(systemName: "star")
                    .resizable()
                    .aspectRatio(1, contentMode: .fit)
                    .frame(width: 800, height: 1200)
                    .id(10001)
            }
        }
    }
}


Is there a way to know the node being viewed?

Question: I have a context where I'm placing a block onto a wiki page. Is there anyway for the block to know the node id of the wiki page?
I'd like to write some code in the block's views-view--block--field.tpl.php template file to display something only to the wiki page's owner. With the block being placed on the wiki's page via context, the block needs what node(wiki) page it is displaying and who the node's owner is.
Answer: Wow - I just got a reply back from Acquia support that answers the issue. menu_get_object() seems to be one of those magically functions I never knew about. Neat.
global $user;
$node = menu_get_object();

if ($node && $user) {

  print '
node uid = ' . $node->uid;
  print '
user uid = ' . $user->uid;

  if ($node->uid == $user->uid) {
    print t('
You are the author of the current node.');
  }

}

Comment: `$user` will always be initialized to an object, even in the case the current user is the anonymous user. I am not sure what you are achieving by using `if ($node && $user) {}`.
Answer: I think the best way to achieve this would be to use nodereference to reference the content type for the block to the wiki page, and then create an argument in views to limit display to current user.
Comment: Sorry you lost me a bit... Can you explain how I would use the nodereference and setup the views argument? Thanks Danielle.
Answer: I would use hook_node_view() as well but it depends.


Disinfecting woodwind instruments

Question: I've bought an interesting instrument recently, a zurna, which I was really excited about. The problem is the same day I first used it (without cleaning it before, yes I know, stupid) I got quite an unpleasant case of gastroenteritis. I can not say for certain that zurna is to blame, nevertheless I want to thoroughly disinfect the instrument before I play it again. There was already a question about effect of rubbing alcohol on reeds. Although I am interested if there are any commonly used techniques of cleaning and disinfecting woodwind instruments besides it, that would least damage them?
Answer: Rubbing alcohol will not damage the wood of reeds or the body of the instrument.  But there might be problems with the surface finish (if any) of the instrument and/or any glue used on the reed.  I don't know of any other disinfectant that wouldn't cause more problems than rubbing (isopropyl) alcohol, though.  Try it out on a small area first.
Comment: Thanks! I'll accept your answer, but I'll add as a comment: I didn't see the answer at the time so I just thoroughly washed the mouthpiece with soap and water and then washed it when 95% alcohol. Played it without any problems. Don't know if this is an appropriate process but seems to work in my case.

Disinfecting woodwind instruments


Conditional Operator in Java where I don't want the false Boolean to do anything

Question: I am a extremely beginner programming student working with Java.
For a section of an assignment I have a for loop that looks for a specific character in a string, and if it finds that character, it needs to update my count for a later section of the code. For this particular assignment, we are required to only use the conditional (ternary) operator. I have been able to complete the code using an if statement, but like I said, I need to use a conditional operator.
Is there a way for the false statement from a conditional operator to do nothing? Or should I have it update some garbage variable that doesn't matter instead?
This works
if (someString.charAt(i) == someChar) {
    someInt++;
}

But trying to get this working
someString.charAt(i) == someChar ? someInt++ : (this right here);

Comment: The way to do this is: `count += (condition) ? 1 : 0`
Comment: Please show your code (even if you can't complete all of it just yet).  Without code to clarify English descriptions are hard to decipher.
Comment: Pleases also add the `if` statement that you think is working.  The rest of the code would be useful too.
Comment: Yeah, for this problem it that looks like it'll work.  It's pretty unidomatic though, I wouldn't write real code that way.  Not a great problem selected by teacher.
Comment: That does it! Got it working, this one section was holding up my entire program and I just wanted to use the simple if statement... Thanks!
Answer: Maybe something like this can help?
    public int answer(String input, char match) {
        int counter = 0;
        for (final char character : input.toCharArray()) {
            counter += character == match ? 1 : 0;
        }
        return counter;
    }

Comment: Yup, that does it! Thanks!
Comment: If you think it was helpful, please up vote, hopefully this snippet can help others with similar question.
Comment: I did, but I don't have enough reputation for it to appear publicly.
Comment: No problem. Good day!
Answer: public static int count(String str, char ch) {
    return str.isEmpty() ? 0 : (str.charAt(0) == ch ? 1 : 0) + count(str.substring(1), ch);
}

Comment: I don't think that's what the OP was asking.


Describing trend magnitude or detecting trends

Question: I have time series data. One observation per time period, about 10 observations or so. When describing the data (I am interested in descriptive statistics), I'd like to say that there is either a "trend up", "trend down", or "no trend".
I'd like to have a general algorithm for determining if there is a trend. There should be good citations to support the use of this algorithm. I need to say "I am using technique X" and give a citation. This is an important part of my question. You can easily roll your own — what I need is something that's well established and citable and has a specific name.
"What exactly do we mean by trend?" you might ask. I do not have a clear answer to this. So this question is open to some interpretation. Interpret away.
Here is what I've thought of so far.
Joinpoint. Calculate a bunch of different piecewise regressions. Pick one.  Calculate a bunch of different piecewise regressions. Pick one.
This seems like huge overkill. Specialized software. Lots of different regression models. Multiple hypothesis testing. Assumes the trend has a specific functional form — in other words, it's not descriptive. On the plus side, this is citable.
I just need a simple descriptive statistic.
Mann-Kendall test. I could use the Mann-Kendall test, comparing the latest observation to all the previous ones. Find the comparison with the lowest p-value. If $p-value < .05$, say there is a trend from that point on.
Problems. Hypothesis testing. Multiple hypothesis testing — I don't know how to correctly adjust the critical level in this case.
Correlation coefficient. I could just look at $r$ and say that there is a trend if $|r| > a$. I think this would be a bad approach in general, since not all trends are linear.
Effect size. Compare the latest observation with the lowest / highest observation in the series. If the effect size from this comparison is large enough, then I say that there is a trend.
This method is dangerous. It works well if the trend is "well-behaved". But if there is an outlier that is either very high or very low, it might give a bad result.
To fix this, instead of comparing to the highest / lowest observation, you could just compare to the observation $n$ time period ago. Say, latest observation versus the one 10 periods ago. Again, this would work well for "well-behaved" trends, but I could see potential problems here.
Integrate effect size. I think this is an improvement on the above. Compare the latest observation with all the previous ones. Assign a score to each comparison: if the effect size > $a$, score = +1; if the effect size < $-a$, score = -1; otherwise, score = 0. Add up the scores, and do something with that.
I could even vary the absolute value of the scores. When comparing with a recent observation, the absolute value of the score could be high; when comparing with an old observation, it could be low.
Smoothing. Because I have so few data points, I am cautious about smoothing or filters, though I have not looked into it properly.
Comment: Since your objective is *description,* it is difficult to see why you would be concerned with correcting for multiple hypothesis testing. You can overcome the objection to effect size (it is not robust) by using a robust estimator, such as Theil-Sen. There is such an admixture of competing concerns expressed in this question (which, in itself, is understandable) that one is left wondering what, precisely, you mean by "descriptive statistics." Perhaps you could elaborate on that?
Comment: Thanks @whuber. I looked up Theil-Sen, very interesting. By "descriptive statistics" I mean that I just want to make statements about the data itself. I do not want to be making inferences about future data.
Comment: If you are an `R` user, or are willing to try it out, take at look at `stl` [(seasonal decomposition by Loess)](https://www.google.com/search?q=seasonal+decomposition+by+loess&ie=utf-8&oe=utf-8). This approach might give you some ideas to help you narrow your options.
Comment: This "integrate effect size" idea is similar in concept to Common language effect size https://en.wikipedia.org/wiki/Effect_size#Common_language_effect_size .
Answer: First, I would suggest to have a look at the book of P. Brockwell and R. Davis, Introduction to Time Series and Forecasting, 2002, second edition, Springer, New-York. The first chapter deals with trend estimation, and tests for stationarity. It is not too technical and full of examples and the first chapter is really easy. If you need a more technical reference, you can have a look at Time Series: theory and methods, 1991, second edition, Springer, New-York, by the same authors. That is for the citation part of your question.
If you consider a time series $\{X_t\}$, you can always decompose it into a trend, a seasonal component and  a (stationary) random noise, that is you can write $X_t = m_t + s_t + Y_t$, where $m_t$ is the trend component, $s_t$ is the seasonal component and $Y_t$ is a stationary series.
First, I would suggest to test the stationarity of the observed series. You can use different tests to do so, based for instance on sample correlations.
If there is evident deviation from stationarity, you could try to estimate a trend. There are many ways to do it. You've mentioned filtering, but you can also think about polynomial fitting (linear regression of your series using $t, t^2, t^3,\dots$ as explanatory variables) or exponential fitting (linear regression on the log of your observations with $t$ as explanatory variable).
Finally, once you've done your trend estimation, test the stationarity of your residuals. If the residuals are not stationary you need some more sophisticated model for your trend.
You can use a blackbox algorithm to extract the trend and the seasonal component. As already mentioned before the stl function in R does the job, but at the price of a lack of interpretability (how the trend is extracted).
hope it helps!
Answer: In my opinion the answer to your question involves the one bullet point that apparently reflected your current minimum understanding i.e. Smoothing. Detecting a trend in a sequence of longitudinal vales requires a proper determination of the smoothing filter. Unusual values not representative of the typical auto-correlative structure need to be identified and their effect nullified. Unusual values may be one-time only pulses or seasonal pulses (which are in truth NOT unusual but systematic ). Furthermore before correctly identifying a reasonable filter/equation one needs to identify/remedy level shift changes(really intercept changes) in the history. Now that the data has been cleaned up one needs to use the auto-correlative structure to form an efficient ARIMA model. This ARIMA model may incorporate differencing operators and then may have a steady-state differential which could be classified as a trend. Alternatively the residuals from the ARIMA model may suggest/evidence a set of residuals which follow a linear trend suggesting the need for adding a deterministic series to your ARIMA model of the form 0,0,0,0,0,1,2,3,4,5 where a trend is suggested at period 6 . Of course there can be one or more of these trends e.g. x1=1,2,3,4,5,7,9,11,13,15,17 etc. which may be needed. I have programmed and have helped developed software which performs this tour-de-force. There is a 30 day free trial which could be useful to you in your work. The software is called AUTOBOX and I believe it's twofold trend detection procedures are unique in available software. Spline procedures do not work as the user has to pre-determine the number of splines and the length of each spline


How the big guys monitor their servers?

Question: I'm wondering what software the web scale guys are using to monitor their n arrays of servers in the server farm(s).
What does facebook, twitter, digg use? How google does it?
I'm looking for a solution to our own monitoring requirements. Our servers sit in the cloud, AppEngine & EC2. We are looking to monitor the "application" (which is build from many small services) meaning that the end result should be a system that can monitor both response time (+alivenss and co.) and application validness: If I do X then Y should happen, then after 2 hours verify the Z was processed and T was appended to the correct log...
The ideal solution would be a system that I can deploy unit tests to, the same unit tests I'm using to test the software while developing.
Recommendations, pointers, comments are highly welcome - I'm looking for directions to attack this issue.
Thanks,
Maxim.
Comment: They do it two ways. They monitor from inside, some of which will be server performance monitoring (RAM, CPU, IO) and some will be instrumentation of the application(s), showing internal bottlenecks. They will also monitor from outside, which sounds like what you're asking more about. From the outside can be pretty easy - use something like HPOV/HP BAC, or an external hosted service, to do the desired (synthetic) transactions and record the times. Using an internal tool, you could also generate load, either against prod or test targets.
Answer: I watched this a while ago. It's 'A day in the life of Facebook operations'. They use cfengine2 (deployment), nagios (monitoring), ganglia (monitoring and trending) plus a lot of in-house tools. Funny to see some of the tools we use are used in such a massive scale (+60.000 servers)
Comment: Working for a company with a huge fleet of servers (10s of thousand) I can confirm that it is accurate. Especially the "in-house" part.
Comment: +1 for that video.  Excellent!

How the big guys monitor their servers?


how to stream video on-site generated from link preview in a text area?

Question: I am using opengraph filter module to generate preview from url. It is working perfectly. Now if a user has shared a video or image through url on the site and the preview is generated, when someone clicks on that preview, it takes the user to the link page (external website). What I want is, it should open on my site i.e embed on my site so that user can see the picture or video, generated from link preview, on my website. Currently, there is a video filter module which converts links to embeded videos, but it requires users to use this format [video:url] when sharing videos, but this format [video:url] for sharing a video link is not desirable, so leave it. I just mentioned it for reference/information.
Comment: Do you mean when the user click the preview, it will change it to video player and play the video? And now you can display the thumbnail and also the video player but you don't know how to combine them?
Comment: Yes, the first part of your comment is exactly what I want. Second part is not because the video filter module, which changes the video link into an embeded video, requires a user to use this format [video:http://example.com] when sharing a video link, which is obviously not desirable. Yes, I can only generate thumbnail preview for now using open graph filter.
Comment: opengraph_filter module only support these og type `array('title', 'description', 'image', 'url', 'type');`. I found it from the module. You need to implements `template_preprocess_opengraph_filter` for supporting the video....
Comment: I have edited the question. See last part. FYI, the video filter module does not generate a preview. Leave video filter module if its creating confusion.
Comment: Can you please tell me how?
Answer: Opengraph Filter module provides this: template_preprocess_opengraph_filter()
You can implements it in your custom module or theme for reading the video url. Then you can use the video url to output the player.
function mytheme_preprocess_opengraph_filter(&$variables) {
  $key = 'video';
  if (isset($variables['metatags']['og'][$key])) {
    $video_url = $variables['metatags']['og'][$key];

    // more code to operate $video_url.
    // dpm($video_url);
  }
}

You can start with it. It would be a long story if you want to load the video after clicking the thumbnails. I would suggest you to split the question into multiple specific questions for different step. It is more easy for other to provide answer and also for those who is looking for answer. Thanks.
Comment: ok i will try. Can you suggest me how should I split my question?
Comment: What is og? Do i need to enable metatags module?
Comment: There is several step for your case. 1) get the video url from og. 2) generate the video player from video url. 3) ajax replace the video player with binding click event on thumbnails...... These steps would be a lot of code....
Comment: og is Open Graph
Comment: shared a [Question] (http://drupal.stackexchange.com/questions/211437/how-to-generate-video-player-from-video-url-link-in-textarea-on-whole-website)
Comment: I would like to clarify one more thing about OG. When it generates a thumbnail preview from url, it is clickable. When I click it, it takes me to the actual link website. What do you mean by "1) get the video url from og.


In the FL studio for doing a chicken pickin' how can I add a mute note to the piano roll?

Question: In this video, he says he mutes a string; for creating a sound like that in a piano roll in the FL studio, what should I do?
I was using Ploc2, and I changed multiple settings, but I couldn't make a sound like that:
Answer: There is no "mute note" in MIDI- or in the FL studio piano roll.  You can't make that sound in the FL studio piano roll (technically, you can't make any sound in the FL studio piano roll, because the piano roll is just instructions for the instrument which will actually make the sound).
You are using the Ploc 2 preset for Harmor, which I don't believe can create this sound out of the box.  You could create (or find) a different synth patch that makes that sound, using this patch only for "muted" notes, or modify the existing one so that modulating some parameter (mod X, mod Y, velocity, etc) creates that sound.
I'm not totally sure what sound you're envisioning, since the Ploc 2 regular sound isn't super similar to a guitar's regular sound to begin with, but perhaps just try playing a high G with Mod X 0%, Mod Y 50%, Mod Z 100%.  Maybe you could also edit Mod X to shorten the low pass filter envelope more aggressively, further "muting" the note.
Answer: I don't use FL but I have had a bit of success simulating muted guitar sounds with a different DAW by making the notes I want to sound muted be as short as you can make them, a 1/64 or even a 1/128 or shorter if possible. Another thing you can do is select a specific pitch and use only that pitch for all the muted notes. Experiment with notes in different registers to see which best simulates a muted string when played with a very short duration. Also experiment with the velocity of the muted notes, they may need to be louder than the regular notes to sound good.
Below is an image with long and short 8th notes on a C note to give you an idea of what you can try:


How to get label text from table reference on database based on TableName and FieldName

Question: Problem
How to get label text from table reference on database  based on TableName and FieldName dynamically from database and show on view createEmployee .
Details
Meaning i need to get label text dynamically from database not static from model
SO that Every Time i  need to change text of label i will change it from database depend on reference table
AND No need to change from code .
IF You give me function or any thing general because i have more models and view i need to make like that)
Tools used sql server 2012 and visual studio 2017 asp.net core 2.1
Database Have two tables Employee and Reference
Reference Table (have 3 key as composit keys(Code,TableName,FieldName))
Models classes Include HRContext
public class ReferenceFile
    {
        public int Code { get; set; }
        public string TableName { get; set; }
        public string FieldName { get; set; }
        public string EnglishtextforLabel{ get; set; }

    }
 public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public int EmployeeAge { get; set; }
    }
 public class HRContext : DbContext
    {
        public HRContext(DbContextOptions<HRContext> options)
: base(options)
        { }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<ReferenceFile> ReferenceFiles { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Employee>()
               .HasKey(t => new { t.EmployeeId });

            modelBuilder.Entity<ReferenceFile>()
                .HasKey(t => new { t.Code,t.TableName,t.FieldName });
        }
    }

        <form asp-action="Create">

                <input asp-for="EmployeeName" class="form-control" />

                <input asp-for="EmployeeAge" class="form-control" />

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

Query Get Data from reference Table
SELECT TableName, FieldName,EnglishtextforLabel FROM ReferenceFile WHERE (FieldName = 'EmployeeId' ) AND TableName = 'Employee'

Here i need to get label on view create from table reference not static field name
Sample data for ReferenceTable
Code  TableName  FieldName    EnglishtextforLabel
1      Employee  EmployeeId          Code
2      Employee  EmployeeName        Name
3      Employee  EmployeeAge         Age

As reference table above sample labels on view create must be Give me the Result below
:
Code

Name

Age

Answer: Just use Model Binding... then you can use your FieldName in the label:
@model MyModelType

@Model.FieldName
<input asp-for="EmployeeName" class="form-control" />


Subconsultas Select

Question: Meu banco esta assim:
cd_cliente |  nr_ddd  |   nr_telefone
30         |  11      |   25622791
30         |  11      |   25622791

Meu select esta assim:
"SELECT * FROM tb_telefones WHERE nr_ddd="+ddd+" AND nr_telefone="+telefone+"";

Ele retorna do banco a partir dos parâmetros ddd e telefone, os numeros que são iguais a eles.
Eu quero que a partir desse parâmetros (parametros nr_ddd e nr_telefone), ele retorne o valor de cd_cliente, e faça uma nova consulta, retornado tos os ddds e telefones que tem cd_cliente  igual.
Comment: Sua pergunta está confusa. Re-leia e ajuste para que possamos te ajudar. Se possível informe a estrutura das tabelas e seja mais claro sobre o que você precisa.
Answer: Contando que a tabela "tb_telefones" tenha as colunas que mencionou (o que faz sentido), então este select poderá lhe ajudar:
SELECT * FROM tb_telefones
WHERE cd_cliente IN (SELECT cd_cliente FROM tb_telefones
                     WHERE nr_ddd="+ddd+"
                     AND nr_telefone="+telefone+")

Garanta que ddd e nr_telefone sejam inteiros e não terá problemas com o select.

Subconsultas Select


Cakephp Self referring Model Not working

Question: I have a table
Medias:
    ID,
    PARENT_ID
    PATH
    TITLE

Items:
    ID
    medias
    Title
    description

Models
class ImageGallery extends AppModel {

    public $name = 'ImageGallery';
    public $useTable = "medias";

    var $belongsTo = array(
        'Parent' =>
        array('className' => 'ImageGallery',
            'foreignKey' => 'parent_id',
            'dependent' => false,
        ),
    );

    var $hasMany = array(
        'Children' =>
        array('className' => 'ImageGallery',
            'foreignKey' => 'parent_id',
            'dependent' => false,
        ),
    );
}

class Item extends AppModel {

    public $useTable = "items";
    public $validate = array(
        'title' => array(
            'rule' => 'notEmpty'
        ),

    );

    public $belongsTo = array(

        'Gallery'   => array(
            'className' => 'ImageGallery',
            'foreignKey'    =>  'medias'),
    );

    public $hasMany = array(
        'ItemMeta'  => array( 'className' => 'ItemMeta'),
    );
}

The media table contains gallery information.  Images are stored in parent_id relation.
When I request Item->find('all'); I am getting only one entry from Media table, but I want to get all its children too. :(
I can get its children by using $this->ImageGallery->findById(10);, but I want to get them with the Item Model.
Answer: Use the containable behavior to specify which associated models you want the query to get.  http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
$this->Item->find('all', array('contain' => array('ImageGallery' => array('Children'))));

If you're looking to go deeper than just the child level, like if you want to get the rest of the tree, then you'll need to either write something to recursively fetch the children, the children's children, etc., or perhaps you can alter your code and models to make use of CakePHP's Tree Behavior.  See http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html and http://www.dereuromark.de/2013/02/17/cakephp-and-tree-structures/


How to fix extended property on express request

Question: I'm building a middleware in javascript where I can get the information of the user by using the famous "req" of the route handler.
When i do a console.log(currentUser), I get the expected value but the currentUser is giving a typescript error warning: Property 'currentUser' does not exist on type 'Request<{}, any, any, ParsedQs, Record<string, any>>'.ts(2339)
Below is my piece of code:
middleware
const currentUser = async (req, res, next) => {
  if (!req.cookies?.token) return next();

  try {
    const payload = jwt.verify(req.cookies.token, process.env.JWT_SECRET);

    req.currentUser = payload;
  } catch {}

  next();
};

exports.currentUser = currentUser;

currentUser
const { currentUser } = require("../middleware");

router.get("/users/currentuser", currentUser, (req, res) => {
  const { currentUser } = req;
  console.log(currentUser);
});

exports.currentUser = router;

and this is the result when I do the console.log:
{
id: '625c2298ec690d8db4c6b37d',
email: 'firstname.lastname@example.com',
role: 'user',
name: 'Martin',
iat: 1650218344,
exp: 1650304744
}
Can some one help me out fixing this in javascript because i'm not familiar with typescript.
Thank you in advanced!
Answer: The Request type of Router contains some fixed properties.
If you want to add your own custom properties to it, either use
req.currentUser = payload;
OR
Create a type for own use like below, and use it for req
export type CustomRequest = ExpressRequest & {
  currentUser?: string | JwtPayload;
};

Hope this helps
Answer: for this one you can use Type.
type NewRequest = Request & {
  currentUser: string | JwtPayload,
}

async (req:NewRequest, res:Response, next:NextFunction)

I Hope, this will help you. Thanks)


Nx Module Federation with Angular - No provider for HttpClient

Question: I have setuped a micro front-end Nx (13.10.3) workspace with Angular (13.3.0) and @nrwl/angular (13.10.3) module federation. When I try to load a route which is loading a remote module I am getting the error below. I have added HttpClientModule in the app.module.ts.
core.mjs:6500 ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(RemoteEntryModule)[HttpClient -> HttpClient -> HttpClient -> HttpClient]:
  NullInjectorError: No provider for HttpClient!
NullInjectorError: R3InjectorError(RemoteEntryModule)[HttpClient -> HttpClient -> HttpClient -> HttpClient]:
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (core.mjs:11160:27)
    at R3Injector.get (core.mjs:11327:33)
    at R3Injector.get (core.mjs:11327:33)
    at R3Injector.get (core.mjs:11327:33)
    at NgModuleRef.get (core.mjs:21886:33)
    at R3Injector.get (core.mjs:11327:33)
    at NgModuleRef.get (core.mjs:21886:33)
    at Object.get (core.mjs:21563:35)
    at lookupTokenUsingModuleInjector (core.mjs:3365:39)
    at getOrCreateInjectable (core.mjs:3477:12)
    at resolvePromise (zone.js:1211:1)
    at resolvePromise (zone.js:1165:1)
    at zone.js:1278:1
    at _ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.mjs:25605:33)
    at _ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at drainMicroTaskQueue (zone.js:585:1)

Comment: Only provide it in the shell app, after the browserModule
Answer: My team has recently gone through this process and this is what has worked for us across multiple remotes:
Quick caveat for posterity: avoid exposing the remote's AppModule, use RemoteEntryModule or another feature module instead e.g. DashboardModule, NavigationModule, etc. (You are already doing this in the above example using RemoteEntryModule)

Import HttpClientModule in your shell's AppModule
Import HttpClientModule in your remote's RemoteEntryModule or feature module.

The shell should import BrowserModule/BrowserAnimationsModule in its AppModule.
Individual remotes' RemoteEntryModule/feature modules should only import CommonModule.
You can import BrowserModule/BrowserAnimationsModule (in addition to your RemoteEntryModule/feature module) in the individual MFEs' AppModule so they will build and serve independently - AppModule code should not be exposed to the shell.


Using CreateML Model in Xcode (ActivityClassifier)

Question: I created an activity classifier model using CreateML and imported the model into my XCode project. And am trying to find answers to the following questions.. I created the instance of the model like this:
let activityClassifier = MyActivityClassifier_4()

How am I supposed to access the constants of the model? For example, the prediction window value that shows here on the metadata of the model. I am having hard time finding an example code to get these values. I tried something along these line let predictionWindowSize = activityClassifier.model.modelParameters but could not figure it out.

Also, the model expects stateIn as an input. How can I create an empty MLMultiArray that matches the expected shape?
stateIn: MLMultiArray(shape: <#T##[NSNumber]#>, dataType: <#T##MLMultiArrayDataType#>)
I assume there is a suggested way to fetch features shape and etc...

I would greatly appreciate if you could also direct me on how to find these answers...
Answer: You can get the metadata by accessing modelDescription.metadata. For author, description, license, and version, you can use the appropriate MLModelMetadataKey:
e.g.
let model = try! MyActivityClassifier_4(configuration: .init()).model
let author = model.modelDescription.metadata[.author]

For the metadata in the "additional metadata" section, you need to use the .creatorDefinedKey key to get a nested dictionary. Things like prediction_windows are stored there.
if let dict = model.modelDescription.metadata[.creatorDefinedKey] as? [String: Any],
   let predictionWindow = dict["prediction_window"] {
    print(predictionWindow)
}

For the inputs, you can see the shape and type of the array just by going to the "Predictions" tab after opening your model in Xcode.

In this case, both of the inputs shown above would be a double array with a single dimension, 100 elements in length. You can create it like this.
MLMultiArray(shape: [100], dataType: .double)

If you want to do this programmatically, you can too. Just give the name of your input to model.modelDescription.inputDescriptionsByName, and get the multiArrayConstraint.
if let constraint = model.modelDescription.inputDescriptionsByName["stateIn"]?.multiArrayConstraint {
    print(constraint.shape)
    print(constraint.dataType)
}

Comment: Thank you! How are these two different? `let model = try! MyActivityClassifier_4(configuration: .init()).model` and `let activityClassifier = MyActivityClassifier_4()` then accessing model in activityClassifier?
Comment: @Megool The parameterless `init` for `MLModel` is deprecated. (Did Xcode not generate a warning for this?) You should use the throwing `init(configuration:)` and handle errors correctly (Though for the sake of example here, I didn't do this).
Comment: gotcha, thanks. You seem to be pretty experienced with CoreML. Do you mind taking a look at my other question? https://stackoverflow.com/questions/77150967/statein-input-for-activityclassifier-in-coreml


Reverse Graphical network mapping architecture

Question: Hi everyone i've got the issue to handle a network that has not documentation whatsoever but is there any tool or procedure in order to create the network architecture model, or i should do it node by node, and graphical modeling with Visio or Dia.
Thanks!
Comment: You might want to make the title a bit more relevant to the actual question 'Graphical network mapping', just 'Network mapping' or similar. I'd be interested if you find anything that does this automatically.
Answer: there can be two types of it, one is very strategic high level architecture which can be made very easily for any executive level reporting purpose and for the technical reference i would suggest you do the node by node and using visio can be more efficient and a quality output.
Answer: There are tools that can do this automatically, but the only one I know of is OPNET's NetMapper. There are probably others, I just don't know what they are.
If you are attempting to map a small network, it is probably easiest to follow the other answer's suggestion and do it manually, node-by-node.


Likelihood of next trial given N trials

Question: Forgive me for my notation and lack of formatting prowess, it's been a while since I've done any of this.
We have flipped a biased coin (unknown weight) $n$ times and received $k$ successes (or heads).  I am trying to calculate the probability that there be a success on flip $N+1$
If we assume the bias $p$ is sampled uniformly (and is constant throughout the flip), then is the correct way to calculate this:
$\int P(p| X)*p \partial p$  where $X$ is n successes and k failures
thus
$P(p| X) = \frac{P(X|p)*f(p)}{\int_{0}^{1} P(X|p) \partial p}$
Assuming a uniform prior for $p$ and that ${\int_{0}^{1} P(X|p)} = \frac{1}{n+1}$, we get
$\int_{0}^{1} P(X|p)*(n+1)*p \partial p $
where $P(X|p)$ is the binomial probability.
Is this correct?
Comment: What LaTeX symbol were you trying to produce with `\dp`? You can see if it has another name (that MathJax can recognize) by using Detexify: http://detexify.kirelabs.org/classify.html
Comment: I was trying to do 'integrate with respect to p'
Comment: My apologies if I jumped the gun on editing `\dp`, I didn't know you wanted the partial derivative.
Comment: Is not it a martingale?
Answer: You have a problem using $p$ both as a probability or bias and as a density function, so let's use $f(p)$ as the prior density instead.  Then $f(p)=1$ since you have assumed it is uniform on $[0,1]$.
It is useful to know that $(n+1) {n \choose k} \int_{x=0}^1 x^k (1-x)^{n-k} \; dx = 1$, related to the Beta distribution
So the posterior density is
$$f(p|k \text{ heads out of } n) = \frac{Pr(k \text{ heads out of } n|p) f(p)}{\int_{q=0}^1 Pr(k \text{ heads out of } n|q) f(q) \, dq} $$ $$ = \frac{ {n \choose k} p^k (1-p)^{n-k}  1}{\int_{q=0}^1 {n \choose k} q^k (1-q)^{n-k} 1 \; dq} = (n+1){n \choose k} p^k (1-p)^{n-p}$$
and the answer to the question is
$$Pr({n+1}^\text{th} \text{ trial is heads }| k \text{ heads out of } n) = E[p|k \text{ heads out of } n]$$
$$= \int_{p=0}^1 p \; f(p|k \text{ heads out of } n) \; dp = \int_{p=0}^1 (n+1){n \choose k} p^{k+1} (1-p)^{n-k} \; dp =  \frac{k+1}{n+2}$$

Likelihood of next trial given N trials


Is there standard normal cumulative distribution function in GAMS?

Question: I want to code the following formula in GAMS,
 R(i)= Phi[beta*Log10(M(i)/W*D)]

Where 'Phi' is a standard normal cumulative distribution function.
  Scalar beta=0.34, W=70, D=41;
  Parameter M(i)/1 375, 2 450, 3 876,4 212,5 125/;

I didn't find standard normal cumulative distribution function in GAMS, is it available? How can I code this formulation in GAMS?
Comment: This and your next question appear to be duplicates, except the other one is for Matlab. That one is on hold, so I suspect this one will be put on hold too.
Answer: You can do this in GAMS with extrinsic libraries, stolib. For cumulative normal, you would use:
$funclibin stolib stodclib
function cdfnorm / stolib.cdfnormal /

Implementation follows the syntax:
parameter_x = cdfnorm(a,mu,sd);

...where a is the point up to which you want to evaluate the distribution; and mu and sd are its parameters.
See here for more details: https://www.gams.com/mccarl/newsletter/news35.pdf or search the McCarl guide that comes with your distribution of GAMS for stolib (if it's at least v23.6 (I think)).
Comment: You might also check the errorf function, which is built in to GAMS. Just search for it here: https://www.gams.com/latest/docs/UG_Parameters.html


How can I display tags on one line

Question: How to change the below output of a drupal article Tags display with bootstrap theme

To something like this which is displayed in stackoverflow below any questions

Is there a ready made module available, I know this can be achieved using JS tagEditor plugin for jQuery
I tried to use Expert Field format mode in Display Suite by setting span for the item tag, it is not working
Answer: I solved this using below CSS
.field--name-field-tags .field--item {
   display: inline;
}

.field--name-field-tags .field--item a,
.field--name-field-tags .field--item a:visited,
.field--name-field-tags .field--item a:active,
.field--name-field-tags .field--item a:hover {
   color: #fff;
   background-color: #ff5588;
   padding: 1px 5px 1px 5px;
   border-radius: 3px;
}

which gave this output

I used Asset Injector which is easy online edit

How can I display tags on one line


HTML CSS how to make a dynamic multicolumn table from a 2D table with JavaScript

Question: I would like to make a dynamic multicolumn table from a static 2D table, like the picture below (see solution):

The correct HTML-code as folows:

              Name
              Role

              Adam
              AAA

              Adam
              BBB

              Adam
              CCC

              Bert
              AAA

              Bert
              CCC

              Cesar
              BBB

Comment: Start by wrapping the data in thead and tbody to separate the headers from the data
Comment: AFAIK this isn't something HTML+CSS is capable of. You need to either render this HTML on the back end or use JavaScript on the front-end.
Comment: Thanks good idé I did that now.
Answer: I used jquery to iterate through the table. First created all different roles array and then individual names array.  Then created individual rows for each names. I have added comments in the code.

              Name
              Role

              Adam
              AAA

              Adam
              BBB

              Adam
              CCC

              Bert
              AAA

              Bert
              CCC

              Cesar
              BBB


Find the volume of the solid that lies above the cone : $z^2 = x^2 + y^2$ and inside the sphere $x^2 + y^2 + (z-2)^2 = 4$

Question: Using spherical coordinates find the volume of the solid that lies above the cone: $z^2 = x^2 + y^2$ and inside the sphere $x^2 + y^2 + (z-2)^2 = 4$
I'm aware that there's a similar question here using a different method.
Assuming it's the same problem I should get the same sol. but my attempts with spherical coor. yield a different answer so I need to know where the mistake is.
My attempt :
The solid is bounded above by the sphere centered at $(0,0,2)$ and below by the circle at which the sphere and the cone intersect: $x^2+y^2=2z$ (at $z=2$) whose projection on the $xy$-plane is $x^2+y^2=4$
So the limits are given by : $$ Q= \{ 0 \leq \rho \leq 2 \;,\; 0 \leq \phi \leq \frac{\pi}{2} \;,\; 0 \leq \theta \leq 2\pi \}$$
$$
\begin{align}
V &= \underset{Q}{\iiint} \rho^2 \sin(\phi) \;d\rho \;d\phi \;d\theta \\
&= \int_0^{2\pi} \int_0^{\frac{\pi}{2}} \int_0^{2} \rho^2 \sin(\phi) \;d\rho \;d\phi \;d\theta \\
&= \int_0^{2\pi} \int_0^{\frac{\pi}{2}} \sin(\phi) \left[ \frac{1}{3} \rho^3  \right]_0^2 \;d\phi \;d\theta
= \int_0^{2\pi} \int_0^{\frac{\pi}{2}} \frac{8}{3} \sin(\phi) \;d\phi \;d\theta \\
&= \int_0^{2\pi} \frac{8}{3} \bigg[ \sin(\phi)  \bigg]_0^{\frac{\pi}{2}} \;d\theta \\
&= \frac{8}{3} \int_0^{2\pi} d\theta \\
&= \frac{16}{3}\pi
\end{align}
$$

Edit: Thank you for correcting me on the limits for $\rho$. But I imagined the problem to be computing the volume of the hemisphere $z = \sqrt{4-x^2-y^2}+2$.
Mainly because it's supported by the answered questions in my textbook. The book claims the answer to be $\dfrac{16}{3}\pi$ but without showing the steps. Therefore I interpreted "the solid that lies above the cone" in the question as " (strictly) above but not inside".
 Hence,
$$
\begin{align}
V &= \underset{Q}{\iiint} \rho^2 \sin(\phi) \;d\rho \;d\phi \;d\theta \\
&= \int_0^{2\pi} \int_0^{\frac{\pi}{2}} \int_2^{4\cos(\phi)} \rho^2 \sin(\phi) \;d\rho \;d\phi \;d\theta \\
&(\cdots) \Rightarrow \; V = \frac{16}{3}\pi
\end{align}
$$

I attached an image visualizing my understanding of the problem.
Answer: The error here is that you have the upper integration limit for $\rho$ as a constant, 2, but it clearly isn't. Refer to the diagram in the answer to the question you posted:

You need to integrate $\rho$ from $0$ at the origin to the point where $$x^2+y^2+(z-2)^2=2^2\tag{1}$$ which doesn't result in a constant $\rho$. Noting that $\rho^2=x^2+y^2+z^2$ and $z=\rho\cos\phi$, we can rewrite (1) as
$$
\rho^2-4\rho\cos\phi+4=4
$$
Hopefully you can solve this. So we are integrating over $\rho$ from $0$ to

 $\rho=4\cos\phi$.

So the $\rho^2$ part of the integral should result in

 ${4^3\over3}\cos^3\phi$.

Then it's easy to integrate $\cos^n\phi\sin\phi$ using substitution.
Comment: Thank you so much for the insight. Indeed I wasn't careful with the integration limits of $\rho$. I followed from your hints and ended up with $V = \frac{32}{3} \pi$ but then I realized I should integrate from $\rho = 2$ as oppose to $\rho = 0$ since the question asks for the volume that lies _above_ the cone, Which yields $V=\frac{16}{3} \pi$. Which is in tandem with the solution in the textbook.
Answer: As a check, the volume is the sum of a half-circle and a cone with a circular base, i.e.
$$ V= \frac{2\pi r^3}3 + \frac13 (\pi r^2)r=\pi r^3  \overset{r=2} = 8\pi$$


Expected value of a "sample unit"

Question: This is within the context of "survey sampling".
Let $P = \{1,...,N\}$ be the target population, and $S = \{s_1,...,s_n\}$ a sample from P. P and S are identified by the corresponding values of the characteristics of interest:
$S = {X_1,...,X_n} \subset {x_1,...,x_N} = P$
The population mean and variance are $\mu$ and $\sigma^2$, respectively.
These are defined by $\mu = \frac{1}{N} \sum_i^n x_i$ and $\sigma^2 = \frac{1}{N}\sum_i^n (x_i - \mu)^2$
Sampling is performed by "simple random sampling" without replacement.
Question
A first lemma states that:

$P(X_i=\xi_j) = \frac{m}{N}$, with m the number of times a distinct value $\xi_j$  of $X_i$ is present in the original population.

Two further lemmas state now that:

$E[X_i] = \mu$ and $Var[X_i] = \sigma^2$

This is confusing to me. If $X_i$ is one particular observation, say $X_1 = 5$, drawn from a normal distribution with $\mu = 0, \sigma^2 = 1$, how can the expected value of this particular observation (called a "sample unit" in our lecture notes) be equal to the mean of the entire population?
Comment: Maybe I'm even more dense than usual tonight, but this Question leaves me totally clueless. // Are you dealing with samples from a _multivariate_ population here? Maybe $n$-variate? // You need to provide some context in your question. Can you define symbols? Explain how $(x_1,\dots,x_n)$ is a _population?_ Maybe show what you have tried and why you need help. Maybe say what topic you are studying. Name/author of text where lemmas appear.
Comment: Thank you for the feedback - these are lecture notes which are unfortunately not publicly available. But I have added more context and made what I wrote more precise.
Answer: Your notation is quite confusing to me, but about item number two:  "random sample" means that the random variables $X_1, \dots, X_n$ are independent and identically distributed. Particularly, they all have the same mean and variance. That is why $\text{E}(X_i) = \mu$ and $\text{Var}(X_i) = \sigma^2$.
I think you are confused about the difference between a random variable $X$ and the realized value $x$ that you get when you draw from $X$. If you drew a value of 5 from a random variable $X$ with a $N(0, 1)$ distribution---which would be extraordinary, by the way, since it would be 5 standard deviations away from the mean---then you don't take the "expected value of this particular observation". The particular observation 5 is a constant. You could take the expected value of $X$, the random variable, and you would find that $\text{E}(X) = 0$, since the expected value of a normally-distributed random variable is equal to the first parameter $(0)$ of the distribution.
Comment: I think you may still be confused. $\text{E}(X_i)$ is just the expected value of the random variable $X_i$. It's got nothing to do with infinitely many samples. Typically, when you take a random sample of size $n$, this can be thought of as involving one draw from each of the (independent and identically-distributed) random variables $X_1, X_2, \dots, X_n$. They each have an expected value (which are all equal). So $\text{E}(X_1) = \mu, \text{E}(X_2) = \mu$, and so on.
Comment: If you are still confused, I would suggest either consulting your instructor, and/or asking another question on this site (with more details and explanations). If you are taking an introductory statistics course then I think you probably haven't understood the basic setup of random sampling yet. If on the other hand, you are taking a more advanced or specialized statistics course, then perhaps I am the one who is confused here.
Comment: Thank you, that is helpful, and you are right that I am confused by the notation. I understand as you write that E(X) = 0. What was confusing to me was the subscript "i" in $X_i$. I understand now that $E[X_i]$ refers to the expected value over all $X_i$, with i in 1,..,N (N being the sample size) over infinitely many samples. Does that then not imply that $E[X_i] \rightarrow \infty$, that is, that we have convergence to the population mean when the number of times we sample goes to infinity?

Expected value of a "sample unit"


ng build does not recognize any environment other than dev and prod

Question: Can someone tell why I am getting the following error when I try to run the following command?  Perhaps I am doing this incorrectly?  I have pretest and test that I would like to build differently from either dev or prod.
Any help would be greatly appreciated.
ng build --enivronment=pretest --target=pretest -bh http://somehost.stuff.gov:7019

I get the following error:
    The option '--enivronment' is not registered with the build command. Run `ng build --help` for a list of supported options.
Invalid build target. Only 'development' and 'production' are available.
Error: Invalid build target. Only 'development' and 'production' are available.
    at NgCliWebpackConfig.validateBuildOptions (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\models\webpack-config
.js:55:19)
    at new NgCliWebpackConfig (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\models\webpack-config.js:12:14)
    at Class.run (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\tasks\build.js:30:31)
    at Class.run (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\commands\build.js:216:26)
    at resolve (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\ember-cli\lib\models\command.js:261:20)
    at new Promise (<anonymous>)
    at Class.validateAndRun (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\ember-cli\lib\models\command.js:240:12)
    at Promise.resolve.then.then (C:\Users\Denis.Putnam\Documents\development\pcocar-app\node_modules\@angular\cli\ember-cli\lib\cli\cli.js:140:24)
    at <anonymous>

This is my .angular-cli.json file:
    {
  "project": {
    "version": "1.0.0-beta.28.3",
    "name": "pcocar-app"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "pretest": "environments/environment.pretest.ts",
        "test": "environments/environment.test.ts",
        "preprod": "environments/environment.preprod.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "files": "src/**/*.ts",
      "project": "src/tsconfig.json"
    },
    {
      "files": "e2e/**/*.ts",
      "project": "e2e/tsconfig.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "prefixInterfaces": false,
    "inline": {
      "style": false,
      "template": false
    },
    "spec": {
      "class": false,
      "component": true,
      "directive": true,
      "module": false,
      "pipe": true,
      "service": true
    }
  }
}

Comment: see this https://github.com/angular/angular-cli/issues/3387#issuecomment-264961243
Answer: Is it the typo for environment?
ng build --enivronment=pretest --target=pretest -bh http://somehost.stuff.gov:7019

Multiple build environments have not always been supported by Angular, so I would also check what version you are running.
Comment: Its just another way to build https://github.com/angular/angular-cli/wiki/build.

ng build can specify both a build target (--target=production or --target=development) and an environment file to be used with that build (--environment=dev or --environment=prod). By default, the development build target and environment are used."
Comment: You are correct.  I see the typo.  Can you tell me what --target is for?


SelectOneMenu não é carregado ao selecinar objeto para edição

Question: Tenho um componente SelectOneMenu (Primefaces) de cidades, que é carregado de acordo com o estado selecionado.
Meu componente está com seguinte comportamento, logo após salvar o objeto e em seguida seleciona-lo no DataTable através de um commandLink para edição, o componente é carregado com a cidade normalmente, mas se eu sair da página e retornar para depois fazer a edição, esse componente não vem carregado.
Já fiz o degug e o valor da cidade vem preenchido, mas não sei porque não é apresentado no componente. Se alguém puder me ajudar, já tentei de tudo.
Classe Endereco com os mapeamentos
@Entity
@Table(name="TENDERECO", schema="SGCADM")
public class Endereco implements Serializable{
private Cidade cidade;
    private Estado estado;
    private Pessoa pessoa;

@JoinColumn(name = "CODCID", referencedColumnName = "CODCID")
        @ForeignKey(name = "fk_endereco_cidade")
        public Cidade getCidade() {
            if (cidade == null) {
                cidade = new Cidade();
            }
            return cidade;
        }

        public void setCidade(Cidade cidade) {
            this.cidade = cidade;
        }

        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "CODESTA", referencedColumnName = "CODESTA")
        @ForeignKey(name = "fk_endereco_estado")
        public Estado getEstado() {
            if (estado == null) {
                estado = new Estado();
            }
            return estado;
        }
        public void setEstado(Estado estado) {
            this.estado = estado;
        }

        @OneToOne(targetEntity = Pessoa.class, fetch=FetchType.LAZY)
        @JoinColumn(name = "CODPES", referencedColumnName = "CODPES")
        @ForeignKey(name = "fk_endereco_pessoa")
        public Pessoa getPessoa() {
            return pessoa;
        }
        public void setPessoa(Pessoa pessoa) {
            this.pessoa = pessoa;
        }

Bean com scopo @viewScoped
@ManagedBean(name="funcionarioBean")
@ViewScoped
public class FuncionarioBean implements Serializable{

    @EJB private FuncionarioBO funcionarioBO;

    @EJB private CidadeBO cidadeBO;

    @EJB private EstadoBO estadoBO;

    @PostConstruct
    public void init(){
        this.listCargo = cargoBO.buscarCargos();
        this.listEstado = estadoBO.buscarEstados();
        this.listGerentesSupervisores = funcionarioBO.listaGerentesSupervisores();
        listarFuncionarios();
    }

    public void populaCidades(AjaxBehaviorEvent event) throws TransactionalException {
        listCidadePorEstado = cidadeBO.buscarCidadesPorEstado(getFuncionario().getEndereco().getEstado().getCodigoEstado());
    }

    public void salvar() throws PersistenceException, ParseException {
        try {
            funcionario.setDataCadastro(dataAtual);
            funcionario.setTipoPessoa(TipoPessoaEnum.FISICA);
            funcionario.setDataNascimento(formata.parse(DateUtils.formataData(funcionario.getDataNascimento())));
            funcionario.getEndereco().setDataCadastro(dataAtual);
            funcionario.getEndereco().setPessoa(funcionario);
            funcionarioBO.salvarFuncionario(funcionario);
            FacesUtil.info("Funcionário foi salvo com sucesso ! ");
            listarFuncionarios();
            limpar();
        } catch (TransactionalException e) {
            e.printStackTrace();
            logger.error("Não foi possível salvar Funcionario ! " + e.getMessage());
            FacesUtil.error(FacesMessage.SEVERITY_ERROR, "Não foi possível salvar funcionário ! ", e.getMessage());
        }
    }

    public void editar(){
        funcionario = funcionarioBO.find(funcionario.getCodigoFuncionario());
        disable = false;
        btnNew = true;
        btnSave = false;
        btnCancel = false;
    }

}

Implementação do Método buscaCidadePorEstado
public List<Cidade> buscarCidadesPorEstado(Long codigoEstado) throws TransactionalException{
         Criteria cri = getSession().createCriteria(Cidade.class)
                 .add(Restrictions.eq("estado.codigoEstado", codigoEstado));
        return cri.list();

    }

selectOneMenu Estado e Cidade junto com commandLink que busca
o objeto selecionado do meu dataTable:

  <f:selectItem itemLabel="" itemValue="" />
  <f:selectItems value="#{funcionarioBean.listEstado}" var="item" itemLabel="#{item.descricao}" itemValue="#{item.codigoEstado}" />
  <f:ajax event="change" render="Selcid" listener="#{funcionarioBean.populaCidades}" />

  <f:selectItem itemLabel="" itemValue="" />
  <f:selectItems value="#{funcionarioBean.listCidadePorEstado}" var="cid" itemLabel="#{cid.descricao}" itemValue="#{cid.codigoCidade}" />

    <f:setPropertyActionListener value="#{obj}" target="#{funcionarioBean.funcionario}" />

Comment: Olá! Faz um pouco de tempo que não uso o PrimeFaces, mas já tive problemas como esse e as vezes eu conseguia resolver atualizando o componente, neste caso o SelectOneMenu. Tenta fazer isso e nos informa o que acontece =)
Comment: È necessário informar um converter no selectOneMenu, em muitos casos também é necessário ser feito a rescrita do método Equals. No site do primefaces tem um exemplo bem completo: http://www.primefaces.org/showcase/ui/input/oneMenu.xhtml
Comment: Onde está declarada a lista listCidadePorEstado?
Comment: Se você fizer a edição sem sair da página a alteração é gravada normalmente?
Answer: Não precisa colocar o update="Selcid" no seu combo de estado?
 <f:ajax event="change" render="Selcid" update="Selcid" listener="#{funcionarioBean.populaCidades}" />

Answer: Chame populaCidades no editar():
 public void editar(){
        funcionario = funcionarioBO.find(funcionario.getCodigoFuncionario());
        populaCidades(null);
        disable = false;
        btnNew = true;
        btnSave = false;
        btnCancel = false;
    }

Quando você entra a primeira vez na página, para criar o funcionário você não espera que a lista de cidades esteja preenchida. Ao escolher um estado vai disparar o evento e popular a lista de ciades. OK. Daí quando você volta para a listagem e seleciona o mesmo funcionário para edição, como o escopo do managed bean é view, funcionarioBean ainda está com listCidadePorEstado preenchido.
Agora, se você sai da página, isto é do escopo, quando volta para a página e escolhe o funcionário para edição a lista de cidades não está preenchida e não ocorreu nenhum evento que a popule.


Is there a implementaion of the foundation framework for panels?

Question: I recently heard about the foundation framework and I wondered if there is an implementation for panels.
Answer: There is ongoing work in the Zurb Foundation Theme to implement Panels support.
It look's like there has been some progress, I'd check that discussion out first and foremost; then have a look at the search for Panels in that module. There might be more...


Background com Perdas

Question: Estou trabalhando com bootstrap e tenho uma imagem em alta definição que sera usada como background de uma área. O que ocorre é que eu tenho dois problemas:
1º Meu background tem que se adaptar com perdas a diversas resoluções, ele sempre estará centralizado, como o exemplo abaixo:

No caso, a imagem vermelha corresponde a área total da imagem e a azul, apenas o que estará sendo disponível.
Como poderia proceder?
1º O outro problema é que a imagem terá um scrolling semelhante as imagens de fundo desse site: http://www.whitepavilion.com.br/homologacao/
Answer: 1º Sobre a imagem ficar no centro, de forma simples, você pode utilizar o seguinte código CSS:
O que ele faz é basicamente expandir a imagem a todo o contexto da div em que ela está, ajustando a altura e largura quando necessário, e com o comando 'center center' no background você indica que ela deve ser centralizada, não importa o monitor.

html{
  background: url(URL_Exemple.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Exemplo Prático: JsFiddle

2º Sobre o Scrolling, pelo que entendi está se referindo ao "Parallax", efeito de a imagem se mover lentamente dentro do bloco conforme o usuário faz o movimento no scroll.
Existe varias formas de se realizar esse procedimento, recomendo dar uma lida neste tópico do nosso amigo Diego Eis
Parallax simples com JQuery e CSS

Background com Perdas