问:
Getting the values of ListView selected item
I have this ListView adapter:

```<code>public class UpicksAdapter extends BaseAdapter
{
    Context context;

    List<Upick> upick_list;

    public UpicksAdapter(List<Upick> listValue, Context context)
    {
        this.context = context;
        this.upick_list = listValue;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewItem viewItem = null;
        if(convertView == null)
        {
            viewItem = new ViewItem();

            LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInfiater.inflate(R.layout.listview_items, null);

            viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);

            viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);

        viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);

        return convertView;
    }
}

class ViewItem
{
    TextView SubNameTextView;
    TextView SubFullFormTextView;
}
</code>```

The ListView is in a fragment.

I need to get data from the listview selected item. I have this listener:

```<code> UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();

                Log.d("VALOR","VALOR "+item);

            }
        });
</code>```

How can I get the values of the selected item?

EDIT:

Complete Fragment code:

```<code>public class MisUpicksFragment extends Fragment   {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private SessionManager session;
    private ProgressDialog loading;
    private EditText txtbusqueda;
    private Button botonbuscar,botonrefrescar;

    //movies
    private static final String TAG = MainActivity.class.getSimpleName();
    public List<Upick> upicks;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private UpicksAdapter adapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String user_id;
    private Button btnNew;

    ListView UpicksListView;
    ProgressBar progressBar;
    String HttpURL = "http://***/upicks_todos.php";
    private OnFragmentInteractionListener mListener;

    public MisUpicksFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MensajesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MisUpicksFragment newInstance(String param1, String param2) {
        MisUpicksFragment fragment = new MisUpicksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

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

        View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

        UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);

        progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);

        new ParseJSonDataClass(getActivity()).execute();

        UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();

                Log.d("VALOR","VALOR "+item);

            }
        });

        return view;
    }

    private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
        public Context context;
        String FinalJSonResult;
        List<Upick> upickFullFormList;

        public ParseJSonDataClass(Context context) {

            this.context = context;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

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

            HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);

            try {
                httpServiceClass.ExecutePostRequest();

                if (httpServiceClass.getResponseCode() == 200) {

                    FinalJSonResult = httpServiceClass.getResponse();

                    if (FinalJSonResult != null) {

                        JSONArray jsonArray = null;
                        try {

                            jsonArray = new JSONArray(FinalJSonResult);
                            JSONObject jsonObject;
                            Upick upick;

                            upickFullFormList = new ArrayList<Upick>();

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

                                upick = new Upick();

                                jsonObject = jsonArray.getJSONObject(i);

                                upick.Subject_Name = jsonObject.getString("id_servicio");

                                upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");

                                upickFullFormList.add(upick);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else {

                    Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);

            UpicksListView.setVisibility(View.VISIBLE);

            if (upickFullFormList != null) {

                UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);

                UpicksListView.setAdapter(adapter);
            }
        }
    }

    private void logoutUser() {
        session.setLogin(false);

        // Launching the login activity
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        //finish();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
</code>```

答:
Change this code to setters.

```<code>upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
</code>```

eg:

```<code>upick.setSubjectname(jsonObject.getString("id_servicio"));
</code>```

Then inside onclick you can take values using getters

```<code>String item = upicks.get(position).getSubjectname();
</code>```

parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.

Body:
I have this ListView adapter:

public class UpicksAdapter extends BaseAdapter
{
    Context context;

    List<Upick> upick_list;

    public UpicksAdapter(List<Upick> listValue, Context context)
    {
        this.context = context;
        this.upick_list = listValue;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewItem viewItem = null;
        if(convertView == null)
        {
            viewItem = new ViewItem();

            LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInfiater.inflate(R.layout.listview_items, null);

            viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);

            viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);

        viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);

        return convertView;
    }
}

class ViewItem
{
    TextView SubNameTextView;
    TextView SubFullFormTextView;
}

The ListView is in a fragment.

I need to get data from the listview selected item. I have this listener:

 UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();

                Log.d("VALOR","VALOR "+item);

            }
        });

How can I get the values of the selected item?

EDIT:

Complete Fragment code:

public class MisUpicksFragment extends Fragment   {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private SessionManager session;
    private ProgressDialog loading;
    private EditText txtbusqueda;
    private Button botonbuscar,botonrefrescar;

    //movies
    private static final String TAG = MainActivity.class.getSimpleName();
    public List<Upick> upicks;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private UpicksAdapter adapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String user_id;
    private Button btnNew;

    ListView UpicksListView;
    ProgressBar progressBar;
    String HttpURL = "http://***/upicks_todos.php";
    private OnFragmentInteractionListener mListener;

    public MisUpicksFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MensajesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MisUpicksFragment newInstance(String param1, String param2) {
        MisUpicksFragment fragment = new MisUpicksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

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

        View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

        UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);

        progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);

        new ParseJSonDataClass(getActivity()).execute();

        UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = UpicksListView.getItemAtPosition(position).toString();

                Log.d("VALOR","VALOR "+item);

            }
        });

        return view;
    }

    private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
        public Context context;
        String FinalJSonResult;
        List<Upick> upickFullFormList;

        public ParseJSonDataClass(Context context) {

            this.context = context;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

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

            HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);

            try {
                httpServiceClass.ExecutePostRequest();

                if (httpServiceClass.getResponseCode() == 200) {

                    FinalJSonResult = httpServiceClass.getResponse();

                    if (FinalJSonResult != null) {

                        JSONArray jsonArray = null;
                        try {

                            jsonArray = new JSONArray(FinalJSonResult);
                            JSONObject jsonObject;
                            Upick upick;

                            upickFullFormList = new ArrayList<Upick>();

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

                                upick = new Upick();

                                jsonObject = jsonArray.getJSONObject(i);

                                upick.Subject_Name = jsonObject.getString("id_servicio");

                                upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");

                                upickFullFormList.add(upick);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else {

                    Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);

            UpicksListView.setVisibility(View.VISIBLE);

            if (upickFullFormList != null) {

                UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);

                UpicksListView.setAdapter(adapter);
            }
        }
    }

    private void logoutUser() {
        session.setLogin(false);

        // Launching the login activity
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        //finish();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}

Body:
Change this code to setters.

upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");

eg:

upick.setSubjectname(jsonObject.getString("id_servicio"));

Then inside onclick you can take values using getters

String item = upicks.get(position).getSubjectname();

parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.


来源: stackexchange

问:
Using Formula Language to return column values
I'm trying to return all values stored in the tNames variable.

Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.

Below is the sample code:

```<code>tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)
</code>```

I dont know why its not returning anything, will appreciate your help.

The below returns only the contact with index 0, but I want to return all contacts in each document.

```<code>tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))
</code>```

Following comments from Richard the below return the required values, but will prefer not to hard code field name.

Is there any way of using for loop to return field names and values?

```<code>tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)
</code>```

答: Maybe use your loop to create the list of fieldnames as Richard suggested, then display tNames</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to return all values stored in the tNames variable.

Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.

Below is the sample code:

tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)

I dont know why its not returning anything, will appreciate your help.

The below returns only the contact with index 0, but I want to return all contacts in each document.

tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))

Following comments from Richard the below return the required values, but will prefer not to hard code field name.

Is there any way of using for loop to return field names and values?

tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)


问:
Unit test when receiver method call each other
Imagine there is a User package which contains only two simple methods

Hello which says "Hello"

Say which implements how a user speaks

Original

```<code>package user

import "fmt"

type user struct {}

func (u user) Hello() {
    u.Say("Hello")
}

func (u user) Say(sentence string) {
    fmt.Println(sentence)
}
</code>```

However, we are not able to unit test Hello since it depends on Say which is not mockable.

After searing on StackOverflow and Goole, I summarize two methods to solve the problem, but none of them are perfect.

Method 1 - Use lambda func

user.go

```<code>package user

import "fmt"

type user struct{}

func (u user) Hello() {
    say("Hello")
}

func (u user) Say(sentence string) {
    say(sentence)
}

var say = func(sentence string) {
    fmt.Println(sentence)
}
</code>```

user_test.go

```<code>package user

import (
    "testing"
)

func TestHello(t *testing.T) {
    sayCalled := 0
    sayCallArg := ""

    mockSay := func(sentence string) {
        sayCalled++
        sayCallArg = sentence
    }
    say = mockSay

    u := user{}
    u.Hello()

    if sayCalled != 1 {
        t.Fatalf("not called")
    }
    if sayCallArg != "Hello" {
        t.Fatalf("wrong arg")
    }
}
</code>```

Method 2 - Use interface

user.go

```<code>package user

import "fmt"

type user struct {
    sayer Sayer
}

func (u user) Hello() {
    u.sayer.Say("Hello")
}

func (u user) Say(sentence string) {
    u.sayer.Say(sentence)
}

type Sayer interface {
    Say(string)
}

type sayer struct{}

func (s sayer) Say(sentence string) {
    fmt.Println(sentence)
}
</code>```

user_test.go

```<code>package user

import (
    "testing"
)

type mockSayer struct {
    called    int
    calledArg string
}

func (s *mockSayer) Say(sentence string) {
    s.called++
    s.calledArg = sentence
}

func TestHello(t *testing.T) {
    mockSayer := &mockSayer{}
    u := user{sayer: mockSayer}
    u.Hello()

    if mockSayer.called != 1 {
        t.Fatalf("not called")
    }
    if mockSayer.calledArg != "Hello" {
        t.Fatalf("wrong arg")
    }
}
</code>```

I understand most of the cases, people will suggest to use Method 2 since that's how dependency injection works in Go.

However, in this example, it's weird to extract the implementation of Say to another layer (unnecessary complexity in my opinion).

Is there any better solution to solve this kind of dependency?
or which method you prefer and why?

答:
None of the above. I don't see where you prove that the Hello method actually works, that "Hello\n" is actually written. Check the Say method output. Mock os.Stdout. For example,

user.go:

```<code>package user

import (
    "fmt"
    "io"
    "os"
)

type user struct{}

const hello = "Hello"

func (u user) Hello() {
    u.Say(hello)
}

var stdwrite = io.Writer(os.Stdout)

func (u user) Say(sentence string) {
    fmt.Fprintln(stdwrite, sentence)
}
</code>```

user_test.go:

```<code>package user

import (
    "bytes"
    "io"
    "testing"
)

func TestHello(t *testing.T) {
    u := user{}

    u.Hello() // for real

    defer func(w io.Writer) { stdwrite = w }(stdwrite)
    stdwrite = new(bytes.Buffer)

    u.Hello() // for test

    got := stdwrite.(*bytes.Buffer).String()
    want := hello + "\n"
    if got != want {
        t.Errorf("want: %q got: %q", want, got)
    }
}
</code>```

Output:

```<code>$ go test -v
=== RUN   TestHello
Hello
--- PASS: TestHello (0.00s)
PASS
ok      say 0.001s
</code>```

Body:
Imagine there is a User package which contains only two simple methods

Hello which says "Hello"

Say which implements how a user speaks

Original

package user

import "fmt"

type user struct {}

func (u user) Hello() {
    u.Say("Hello")
}

func (u user) Say(sentence string) {
    fmt.Println(sentence)
}

However, we are not able to unit test Hello since it depends on Say which is not mockable.

After searing on StackOverflow and Goole, I summarize two methods to solve the problem, but none of them are perfect.

Method 1 - Use lambda func

user.go

package user

import "fmt"

type user struct{}

func (u user) Hello() {
    say("Hello")
}

func (u user) Say(sentence string) {
    say(sentence)
}

var say = func(sentence string) {
    fmt.Println(sentence)
}

user_test.go

package user

import (
    "testing"
)

func TestHello(t *testing.T) {
    sayCalled := 0
    sayCallArg := ""

    mockSay := func(sentence string) {
        sayCalled++
        sayCallArg = sentence
    }
    say = mockSay

    u := user{}
    u.Hello()

    if sayCalled != 1 {
        t.Fatalf("not called")
    }
    if sayCallArg != "Hello" {
        t.Fatalf("wrong arg")
    }
}

Method 2 - Use interface

user.go

package user

import "fmt"

type user struct {
    sayer Sayer
}

func (u user) Hello() {
    u.sayer.Say("Hello")
}

func (u user) Say(sentence string) {
    u.sayer.Say(sentence)
}

type Sayer interface {
    Say(string)
}

type sayer struct{}

func (s sayer) Say(sentence string) {
    fmt.Println(sentence)
}

user_test.go

package user

import (
    "testing"
)

type mockSayer struct {
    called    int
    calledArg string
}

func (s *mockSayer) Say(sentence string) {
    s.called++
    s.calledArg = sentence
}

func TestHello(t *testing.T) {
    mockSayer := &mockSayer{}
    u := user{sayer: mockSayer}
    u.Hello()

    if mockSayer.called != 1 {
        t.Fatalf("not called")
    }
    if mockSayer.calledArg != "Hello" {
        t.Fatalf("wrong arg")
    }
}

I understand most of the cases, people will suggest to use Method 2 since that's how dependency injection works in Go.

However, in this example, it's weird to extract the implementation of Say to another layer (unnecessary complexity in my opinion).

Is there any better solution to solve this kind of dependency?
or which method you prefer and why?

Body:
None of the above. I don't see where you prove that the Hello method actually works, that "Hello\n" is actually written. Check the Say method output. Mock os.Stdout. For example,

user.go:

package user

import (
    "fmt"
    "io"
    "os"
)

type user struct{}

const hello = "Hello"

func (u user) Hello() {
    u.Say(hello)
}

var stdwrite = io.Writer(os.Stdout)

func (u user) Say(sentence string) {
    fmt.Fprintln(stdwrite, sentence)
}

user_test.go:

package user

import (
    "bytes"
    "io"
    "testing"
)

func TestHello(t *testing.T) {
    u := user{}

    u.Hello() // for real

    defer func(w io.Writer) { stdwrite = w }(stdwrite)
    stdwrite = new(bytes.Buffer)

    u.Hello() // for test

    got := stdwrite.(*bytes.Buffer).String()
    want := hello + "\n"
    if got != want {
        t.Errorf("want: %q got: %q", want, got)
    }
}

Output:

$ go test -v
=== RUN   TestHello
Hello
--- PASS: TestHello (0.00s)
PASS
ok      say 0.001s


答:
The ArrayList.get() method is used to get the element of a specified
  position within the list.

```<code>String str_ITEM= upicks.get(position).yourGETMETHOD();
</code>```

Title: Getting the values of ListView selected item

Body:
The ArrayList.get() method is used to get the element of a specified
  position within the list.

String str_ITEM= upicks.get(position).yourGETMETHOD();


问:
onLayout not called in react native
I am trying to detect the width change with this code

```<code>class MyClass extends Component {
  onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
    alert('ok');
  }
</code>```

the the onLayout function is never called. Is something wrong with the code? I found the code in this website.

答:
Did you ever add onLayout to a component that MyClass renders? It's not a lifecycle method on the React.Component instance (like componentDidMount), it's an event from another component that you can capture by providing an onLayout  callback property to the other component. It's a feature of the react-native builtin components.

```<code>class MyClass extends Component {
  onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
    alert('ok');
  }

  render() {
    return (
      <View onLayout={e => this.onLayout(e)} />
    )
  }
}
</code>```

Title: onLayout not called in react native

Body:
I am trying to detect the width change with this code

class MyClass extends Component {
  onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
    alert('ok');
  }

the the onLayout function is never called. Is something wrong with the code? I found the code in this website.

Body:
Did you ever add onLayout to a component that MyClass renders? It's not a lifecycle method on the React.Component instance (like componentDidMount), it's an event from another component that you can capture by providing an onLayout  callback property to the other component. It's a feature of the react-native builtin components.

class MyClass extends Component {
  onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
    alert('ok');
  }

  render() {
    return (
      <View onLayout={e => this.onLayout(e)} />
    )
  }
}


问:
Best way to trim strings after data entry. Should I create a custom model binder?
I'm using ASP.NET MVC and I'd like all user entered string fields to be trimmed before they're inserted into the database.   And since I have many data entry forms, I'm looking for an elegant way to trim all strings instead of explicitly trimming every user supplied string value.  I'm interested to know how and when people are trimming strings.

I thought about perhaps creating a custom model binder and trimming any string values there...that way, all my trimming logic is contained in one place.  Is this a good approach?  Are there any code samples that do this?

答:
Late to the party, but the following is a summary of adjustments required for MVC 5.2.3 if you are to handle the skipValidation requirement of the build-in value providers.

```<code>public class TrimStringModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // First check if request validation is required
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest &&
            bindingContext.ModelMetadata.RequestValidationEnabled;

        // determine if the value provider is IUnvalidatedValueProvider, if it is, pass in the
        // flag to perform request validation (e.g. [AllowHtml] is set on the property)
        var unvalidatedProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;

        var valueProviderResult = unvalidatedProvider?.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation) ??
            bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        return valueProviderResult?.AttemptedValue?.Trim();
    }
}
</code>```

Global.asax

```<code>    protected void Application_Start()
    {
        ...
        ModelBinders.Binders.Add(typeof(string), new TrimStringModelBinder());
        ...
    }
</code>```

Body:
Late to the party, but the following is a summary of adjustments required for MVC 5.2.3 if you are to handle the skipValidation requirement of the build-in value providers.

public class TrimStringModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // First check if request validation is required
        var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest &&
            bindingContext.ModelMetadata.RequestValidationEnabled;

        // determine if the value provider is IUnvalidatedValueProvider, if it is, pass in the
        // flag to perform request validation (e.g. [AllowHtml] is set on the property)
        var unvalidatedProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;

        var valueProviderResult = unvalidatedProvider?.GetValue(bindingContext.ModelName, !shouldPerformRequestValidation) ??
            bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        return valueProviderResult?.AttemptedValue?.Trim();
    }
}

Global.asax

    protected void Application_Start()
    {
        ...
        ModelBinders.Binders.Add(typeof(string), new TrimStringModelBinder());
        ...
    }


问:
Angular 5 - Can't set header for HttpClient
I am trying to make a POST call using HttpClient in an Angular 5 project, and I want to set the header:

```<code>import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}
</code>```

For some reason, the Content-Type header does not seem to be in the request I am making.

Why is this?

答:
If i see correctly, what you're showing us is OPTIONS preflight request (CORS), not actual POST request.

There should be 2 'requests in question'. http method for one should be OPTIONS (the one you showed here, its called preflight cors request) and one actual POST (if server allows it for your client). If host is different than locahost:4200, which i assume is, then you have to enable cors requests on your server for localhost:4200 client.

Body:
I am trying to make a POST call using HttpClient in an Angular 5 project, and I want to set the header:

import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { AuthData }    from './models/auth-data';

@Injectable()
export class AuthService {

    constructor(private http: HttpClient) { }

    auth = (data: AuthData) => {

        var url = "https://.../login";
        var payload = data;
        var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
        var options =  {
            headers: headers
        };

        this.http.post(url, payload, options).subscribe();
    }
}

For some reason, the Content-Type header does not seem to be in the request I am making.

Why is this?


问:
Kafka producer send blocks indefinitely when kafka servers are down
I'm using Kafka 0.11.0.0.  I have a test program that publishes to a Kafka topic; if the zookeeper and Kafka servers are down (which is normal in my development environment; I bring them up as needed) then the call to KafkaProducer<>.send() hangs indefinitely.

I either need to have send() return, preferably indicating the error; or I need a way to check whether the servers are up or down.  Basically, I want my test tool to be able tell me, "Hey, dummy, start up Kafka!" instead of hanging.

Is there a way for my producer task to determine whether the servers are up or down?

I'm calling the send() like this:

```<code>kafkaProducer.send(new ProducerRecord<>(KAFKA_TOPIC, KAFKA_KEY,
    message), (rm, ex) -> {
        System.out.println("**** " + rm + "\n**** " +ex);
});
</code>```

I have linger.ms = 1; I've tried retries=0, 1, and 2, and send() still blocks.  I've never seen the callback called.

Older messages suggest setting metadata.fetch.timeout.ms to a small value, but that's gone in 0.11.  Others suggest calling command line utilities to see if the servers are OK...but the referenced utilities also seem to be gone.

What's the graceful way to get this done?

答:
We can send messages to broker in three ways :

Fire-and-forget :
We send a message to the server and don’t really care if it arrives successfully or not. Most of the time, it will arrive successfully, since Kafka is highly available and the producer will retry sending messages automatically. However, some messages will get lost using this method.

Asynchronous send
We call the send() method with a callback function, which gets triggered when it receives a response from the Kafka broker.

Synchronous send
We send a message, the send() method returns a Future object, and we use get() to wait on the future and see if the send() was successful or not.

The simplest way to send a message synchronously is as follows:

```<code>ProducerRecord<String, String> record =
            new ProducerRecord<>(KAFKA_TOPIC, KEY, message);
    try {
            producer.send(record).get();
    } catch (Exception e) {
             e.printStackTrace();
    }
</code>```

Here, we are using Future.get() to wait for a reply from Kafka. This method will throw an exception if the record is not sent successfully to Kafka. If there were no errors, we will get a RecordMetadata object that we can use to retrieve the offset the message was written to.

hope this helps.

Body:
I'm using Kafka 0.11.0.0.  I have a test program that publishes to a Kafka topic; if the zookeeper and Kafka servers are down (which is normal in my development environment; I bring them up as needed) then the call to KafkaProducer<>.send() hangs indefinitely.

I either need to have send() return, preferably indicating the error; or I need a way to check whether the servers are up or down.  Basically, I want my test tool to be able tell me, "Hey, dummy, start up Kafka!" instead of hanging.

Is there a way for my producer task to determine whether the servers are up or down?

I'm calling the send() like this:

kafkaProducer.send(new ProducerRecord<>(KAFKA_TOPIC, KAFKA_KEY,
    message), (rm, ex) -> {
        System.out.println("**** " + rm + "\n**** " +ex);
});

I have linger.ms = 1; I've tried retries=0, 1, and 2, and send() still blocks.  I've never seen the callback called.

Older messages suggest setting metadata.fetch.timeout.ms to a small value, but that's gone in 0.11.  Others suggest calling command line utilities to see if the servers are OK...but the referenced utilities also seem to be gone.

What's the graceful way to get this done?

Body:
We can send messages to broker in three ways :

Fire-and-forget :
We send a message to the server and don’t really care if it arrives successfully or not. Most of the time, it will arrive successfully, since Kafka is highly available and the producer will retry sending messages automatically. However, some messages will get lost using this method.

Asynchronous send
We call the send() method with a callback function, which gets triggered when it receives a response from the Kafka broker.

Synchronous send
We send a message, the send() method returns a Future object, and we use get() to wait on the future and see if the send() was successful or not.

The simplest way to send a message synchronously is as follows:

ProducerRecord<String, String> record =
            new ProducerRecord<>(KAFKA_TOPIC, KEY, message);
    try {
            producer.send(record).get();
    } catch (Exception e) {
             e.printStackTrace();
    }

Here, we are using Future.get() to wait for a reply from Kafka. This method will throw an exception if the record is not sent successfully to Kafka. If there were no errors, we will get a RecordMetadata object that we can use to retrieve the offset the message was written to.

hope this helps.

ContentLicense: CC BY-SA 4.0


问:
passing values between custom components in Flex - mxml
how can i pass values from my custom components back to the main.mxml?
 i need to do this to pass back ana array collection </p>

答:
You can call directly into Application using the static Application.application.yourPublicMethodName() or .yourPublicPropertyName = n, but you might also consider using the event framework, to keep your components loosely coupled.  Since your component is by definition an event dispatcher, you can simply dispatch an event from within it, and have your Application class listen for that event.

In MXML, that looks something like this, for the component class:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">

    <mx:Metadata>
        [Event(name="buttonClicked", type="flash.events.Event")]
    </mx:Metadata>

    <mx:Script>
        <![CDATA[

            public var someValue:int = 0;

            private function buttonClick():void
            {
                someValue = 1;
                dispatchEvent(new Event("buttonClicked"));
            }

        ]]>
    </mx:Script>

    <mx:Button label="Click Me" click="buttonClick()" />

</mx:Canvas>
</code>```

... and for the Application, like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">

    <mx:Script>
        <![CDATA[

            import mx.controls.Alert;

            private function myComponent_buttonClicked(event:Event):void
            {
                Alert.show(event.currentTarget.someValue.toString());
            }

        ]]>
    </mx:Script>

    <local:MyComponent buttonClicked="myComponent_buttonClicked(event)" />

</mx:Application>
</code>```

The Event metadata tag in the component class tells the compiler the component dispatches a flash.events.Event-type event ("buttonClicked"), which exposes it as an event on the MyComponent tag; then, all you need to do is wire up a listener for that event, and through the event's currentTarget property, you get access to all of the component's public data.

Just figured I'd offer up an interesting alternative for ya.  Hope it helps!

OwnerDisplayName: luckoftheirish

ContentLicense: CC BY-SA 2.5

Body:
You can call directly into Application using the static Application.application.yourPublicMethodName() or .yourPublicPropertyName = n, but you might also consider using the event framework, to keep your components loosely coupled.  Since your component is by definition an event dispatcher, you can simply dispatch an event from within it, and have your Application class listen for that event.

In MXML, that looks something like this, for the component class:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">

    <mx:Metadata>
        [Event(name="buttonClicked", type="flash.events.Event")]
    </mx:Metadata>

    <mx:Script>
        <![CDATA[

            public var someValue:int = 0;

            private function buttonClick():void
            {
                someValue = 1;
                dispatchEvent(new Event("buttonClicked"));
            }

        ]]>
    </mx:Script>

    <mx:Button label="Click Me" click="buttonClick()" />

</mx:Canvas>

... and for the Application, like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">

    <mx:Script>
        <![CDATA[

            import mx.controls.Alert;

            private function myComponent_buttonClicked(event:Event):void
            {
                Alert.show(event.currentTarget.someValue.toString());
            }

        ]]>
    </mx:Script>

    <local:MyComponent buttonClicked="myComponent_buttonClicked(event)" />

</mx:Application>

The Event metadata tag in the component class tells the compiler the component dispatches a flash.events.Event-type event ("buttonClicked"), which exposes it as an event on the MyComponent tag; then, all you need to do is wire up a listener for that event, and through the event's currentTarget property, you get access to all of the component's public data.

Just figured I'd offer up an interesting alternative for ya.  Hope it helps!

OwnerDisplayName: Christian Nunciato


问:
mysql query works when ran in phpmyadmin, but returns an error when ran in php
Using the following function, I am attempting to update data to a database. The query works well when directly ran in phpmyadmin, but produces an error when running from php.

Here is the function

```<code>function edit_row($table, $columns, $where){
        db_connect();
        $query = "BEGIN WORK; SET AUTOCOMMIT=0; UPDATE $table SET $columns WHERE $where;    COMMIT;";
        echo $query; //this is to control for typing errors when testing in phpmyadmin
        mysql_query($query) or die ("Entry could not be made, " . mysql_error());
        db_close();
}
</code>```

running this command:

```<code>edit_row("hello","test = 'some other string'", "test = 'somestring'");
</code>```

echo outputs:

```<code>BEGIN WORK; SET AUTOCOMMIT=0; UPDATE hello SET test = 'some other string' WHERE test = 'some string'; COMMIT;
</code>```

error produced:

```<code>Entry could not be made, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET AUTOCOMMIT=0; UPDATE hello SET test = 'some other string' WHERE test = 'so' at line 2
</code>```

It appears to cut off the last bit of the query string, but not sure if this is a quirk of the die() method

答:
You cannot execute multiple queries in a single call to mysql_query - you need to break-up your query into four separate calls.

As per the PHP mysql_query documentation:

mysql_query() sends a unique query
  (multiple queries are not supported)
  to the currently active database on
  the server that's associated with the
  specified link_identifier.

The reason this works in phpMyAdmin, is because phpMyAdmin is in fact carrying out four separate queries in the background after de-constructing the statement(s) entered.

Body:
Using the following function, I am attempting to update data to a database. The query works well when directly ran in phpmyadmin, but produces an error when running from php.

Here is the function

function edit_row($table, $columns, $where){
        db_connect();
        $query = "BEGIN WORK; SET AUTOCOMMIT=0; UPDATE $table SET $columns WHERE $where;    COMMIT;";
        echo $query; //this is to control for typing errors when testing in phpmyadmin
        mysql_query($query) or die ("Entry could not be made, " . mysql_error());
        db_close();
}

running this command:

edit_row("hello","test = 'some other string'", "test = 'somestring'");

echo outputs:

BEGIN WORK; SET AUTOCOMMIT=0; UPDATE hello SET test = 'some other string' WHERE test = 'some string'; COMMIT;

error produced:

Entry could not be made, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET AUTOCOMMIT=0; UPDATE hello SET test = 'some other string' WHERE test = 'so' at line 2

It appears to cut off the last bit of the query string, but not sure if this is a quirk of the die() method


问:
Error when install postgresql in linux mint sarah
I want to install postgresql in my computer Linux mint sarah, and I finish procedure installation but when I type psql in my cmd postgres error, like this :

Error when install PostgreSQL

psql: could not connect to server: No such file or directory
      Is the server running locally and accepting
      connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

how I fixed that  ??
thanks

答:
The error states that the psql utility can't find the socket to connect to your database server.

Either you don't have the database service running in the background, or the socket is located elsewhere, or perhaps the pg_hba.conf needs to be fixed.

Step 1: Verify that the database is running

The command may vary depending on your operating system. But on most *ix systems the following would work, it will search for postgres among all running processes

```<code>ps -ef | grep postgres
</code>```

On my system, mac osx, this spits out

```<code>501   408     1   0  2Jul15 ??         0:21.63 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres -r /usr/local/var/postgres/server.log
</code>```

The last column shows the command used to start the server, and the options.

You can look at all the options available to start the postgres server using the following.

```<code>man postgres
</code>```

From there, you'd see that the options -D and -r are respectively the datadir & the logfilename.
Step 2: If the postgres service is running

Use find to search for the location of the socket, which should be somewhere in the /tmp

```<code>sudo find /tmp/ -name .s.PGSQL.5432
</code>```

If postgres is running and accepting socket connections, the above should tell you the location of the socket. On my machine, it turned out to be:

```<code>/tmp/.s.PGSQL.5432
</code>```

Then, try connecting via psql using this file's location explicitly, eg.

```<code>psql -h /tmp/ dbname
</code>```

Step 3: If the service is running but you don't see a socket

If you can't find the socket, but see that the service is running, Verify that the pg_hba.conf file allows local sockets.

Browse to the datadir and you should find the pg_hba.conf file.

By default, near the bottom of the file you should see the following lines:

```<code># "local" is for Unix domain socket connections only
local       all       all       trust
</code>```

If you don't see it, you can modify the file, and restart the postgres service.

Body:
The error states that the psql utility can't find the socket to connect to your database server.

Either you don't have the database service running in the background, or the socket is located elsewhere, or perhaps the pg_hba.conf needs to be fixed.

Step 1: Verify that the database is running

The command may vary depending on your operating system. But on most *ix systems the following would work, it will search for postgres among all running processes

ps -ef | grep postgres

On my system, mac osx, this spits out

501   408     1   0  2Jul15 ??         0:21.63 /usr/local/opt/postgresql/bin/postgres -D /usr/local/var/postgres -r /usr/local/var/postgres/server.log

The last column shows the command used to start the server, and the options.

You can look at all the options available to start the postgres server using the following.

man postgres

From there, you'd see that the options -D and -r are respectively the datadir & the logfilename.
Step 2: If the postgres service is running

Use find to search for the location of the socket, which should be somewhere in the /tmp

sudo find /tmp/ -name .s.PGSQL.5432

If postgres is running and accepting socket connections, the above should tell you the location of the socket. On my machine, it turned out to be:

/tmp/.s.PGSQL.5432

Then, try connecting via psql using this file's location explicitly, eg.

psql -h /tmp/ dbname

Step 3: If the service is running but you don't see a socket

If you can't find the socket, but see that the service is running, Verify that the pg_hba.conf file allows local sockets.

Browse to the datadir and you should find the pg_hba.conf file.

By default, near the bottom of the file you should see the following lines:

# "local" is for Unix domain socket connections only
local       all       all       trust

If you don't see it, you can modify the file, and restart the postgres service.


问:
Git add example for ignored files
How can I ignore file changes but can add or update its example, e.g. with -f flag. For example:
I have a secret file, e.g. secret.properties and I don't want to accidentally add this file to Git history, but I want other team members know how to setup the project.

Notes: I have checked out git rm --cached <path>, but it just completely delete the file from index. And git update-index --assume-unchanged <path> does not prevent other people from updating and also might produce conflicts.

答: I think you firsly put these file in remote and local repositories. Than you need to add it to .gitignore file, so git will ignore all the changes you made in the file. It will stay MY_PASSWORD=changeme in remote repository, but locally everyone will change it and git will ignore it. So, if any new collegues will start, they are also able to pull that file as it is, but any changes they made will not affect the remote repo.

Title: Git add example for ignored files


问:
PG::UndefinedColumn: ERROR in case of same DB is used for two different projects which are connected with each other in Rails
I'm running two projects as a different repository with git. One is admit another one is Web in rails, both are connected with each other, Basically same database is used. I only made the migration on admin report and then cloned it into the web. The problem is, I'm deploying it on the server and test cases failed the error says

```<code>ActionView::Template::Error: PG::UndefinedColumn: ERROR:  column fees.discount does not exist
</code>```

I just don't understand why it has been happening, in admin I have that field presents.

I think schema.rb may playing role in this case. I'm not so sure about it.

Here is my migration,

```<code>class AddDiscountToFeel < ActiveRecord::Migration[5.0]
   def change
     add_column :fees, :discount, :integer, default: nil, null: true
   end
 end
</code>```

And here is my Model fields in development:

```<code> 2.3.1 :008 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]
</code>```

And here is my Model fields in test:

```<code>C238s-iMac:web c238$ RAILS_ENV=test rails c
Loading test environment (Rails 5.0.0.1)
2.3.1 :001 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]
</code>```

And here is my error's snap:

Any help will be appreciated.

答:
Yes, I was right

It has been long time in web that I haven’t updated schema from admin that’s why I’ve faced this issue.

Solution: Copied schema.rb from admin into web repo, because both projects use same DB.

May the answer will helpful for someone also.

Body:
I'm running two projects as a different repository with git. One is admit another one is Web in rails, both are connected with each other, Basically same database is used. I only made the migration on admin report and then cloned it into the web. The problem is, I'm deploying it on the server and test cases failed the error says

ActionView::Template::Error: PG::UndefinedColumn: ERROR:  column fees.discount does not exist

I just don't understand why it has been happening, in admin I have that field presents.

I think schema.rb may playing role in this case. I'm not so sure about it.

Here is my migration,

class AddDiscountToFeel < ActiveRecord::Migration[5.0]
   def change
     add_column :fees, :discount, :integer, default: nil, null: true
   end
 end

And here is my Model fields in development:

 2.3.1 :008 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]

And here is my Model fields in test:

C238s-iMac:web c238$ RAILS_ENV=test rails c
Loading test environment (Rails 5.0.0.1)
2.3.1 :001 > Fee.column_names
 => ["id", "booth_id", "amount", "description", "created_at", "updated_at", "discount"]

And here is my error's snap:

Any help will be appreciated.


答:
in your callback listener you have adapter object just use that like below.</p>

```<code>UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = parent.getSelectedItem().toString();

                Log.d("VALOR","VALOR "+item);

            }
        });
</code>```

Body:
in your callback listener you have adapter object just use that like below.

UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {

                String item = parent.getSelectedItem().toString();

                Log.d("VALOR","VALOR "+item);

            }
        });


问:
DAX Switch Logic translated to TSQL
How would I perform the below DAX expression in TSQL?

```<code>Channel Mapping: =
     SWITCH(
        TRUE (),
           NOT ( ISERROR ( SEARCH ( "ChannelOne", ChannelFact[ChannelName] ) ) ), "C1",
           NOT ( ISERROR ( SEARCH ( "ChannelTwo", ChannelFact[ChannelName] ) ) ), "C2",
           NOT ( ISERROR ( SEARCH ( "Channel2", ChannelFact[ChannelName] ) ) ), "C2",

        "Not Mapped"
)
</code>```

I think it needs the CASE logic but unsure how to put together.

答:
```<code>SELECT CASE ChannelName WHEN "ChannelOne" THEN "C1"
                        WHEN "ChannelTwo" THEN "C2"
                        WHEN "Channel2" THEN "C2"
                ELSE "Not Mapped" END AS "Channel Mapping"
FROM
ChannelFact
</code>```

Thanks.

Title: DAX Switch Logic translated to TSQL

Body:
How would I perform the below DAX expression in TSQL?

Channel Mapping: =
     SWITCH(
        TRUE (),
           NOT ( ISERROR ( SEARCH ( "ChannelOne", ChannelFact[ChannelName] ) ) ), "C1",
           NOT ( ISERROR ( SEARCH ( "ChannelTwo", ChannelFact[ChannelName] ) ) ), "C2",
           NOT ( ISERROR ( SEARCH ( "Channel2", ChannelFact[ChannelName] ) ) ), "C2",

        "Not Mapped"
)

I think it needs the CASE logic but unsure how to put together.

Body:
SELECT CASE ChannelName WHEN "ChannelOne" THEN "C1"
                        WHEN "ChannelTwo" THEN "C2"
                        WHEN "Channel2" THEN "C2"
                ELSE "Not Mapped" END AS "Channel Mapping"
FROM
ChannelFact

Thanks.


问:
removeAll seems to affect its argument
I have written a generic Partition class (a partition is a division of a set into disjoint subsets, called parts). Internally this is a Map<T,Integer> and a Map<Integer,Set<T>>, where the Integers are the labels of the parts. For example partition.getLabel(T t) gives the label of the part that t is in, and partition.move(T t, Integer label) moves t to the partition labelled by label (internally, it updates both the Maps).

But my method for moving a Collection of objects to a new part does not work. It seems that Set.removeAll() is affecting its argument. I think the problem is something like a ConcurrentModificationException, but I can't work it out. Sorry the code is rather long, but I have marked where the problem is (about half-way down), and the output at the bottom should make it clear what the problem is - at the end the partition is in an illegal state.

```<code>    import java.util.*;

    public class Partition<T> {
  private Map<T,Integer> objToLabel = new HashMap<T,Integer>();
     private Map<Integer,Set<T>> labelToObjs =
       new HashMap<Integer,Set<T>>();
     private List<Integer> unusedLabels;
     private int size;  // = number of elements

     public Partition(Collection<T> objects) {
      size = objects.size();
      unusedLabels = new ArrayList<Integer>();
      for (int i = 1; i < size; i++)
       unusedLabels.add(i);
      // Put all the objects in part 0.
      Set<T> part = new HashSet<T>(objects);
      for (T t : objects)
       objToLabel.put(t,0);
      labelToObjs.put(0,part);
     }

     public Integer getLabel(T t) {
      return objToLabel.get(t);
     }
     public Set<T> getPart(Integer label) {
      return labelToObjs.get(label);
     }
     public Set<T> getPart(T t) {
      return getPart(getLabel(t));
     }

     public Integer newPart(T t) {
      // Move t to a new part.
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      move(t, newLabel);
      return newLabel;
     }
     public Integer newPart(Collection<T> things) {
      // Move things to a new part. (This assumes that
      // they are all in the same part to start with.)
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      moveAll(things, newLabel);
      return newLabel;
     }
     public void move(T t, Integer label) {
      // Move t to the part "label".
      Integer oldLabel = getLabel(t);
      getPart(oldLabel).remove(t);
      if (getPart(oldLabel).isEmpty())  // if the old part is
       labelToObjs.remove(oldLabel);  // empty, remove it
      getPart(label).add(t);
      objToLabel.put(t,label);
     }
     public void moveAll(Collection<T> things, Integer label) {
      // Move all the things from their current part to label.
      // (This assumes all the things are in the same part.)
      if (things.size()==0)  return;

      T arbitraryThing = new ArrayList<T>(things).get(0);
      Set<T> oldPart = getPart(arbitraryThing);

   // THIS IS WHERE IT SEEMS TO GO WRONG //////////////////////////
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);
      System.out.println("Now doing oldPart.removeAll(things) ...");
      oldPart.removeAll(things);
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);

      if (oldPart.isEmpty())
       labelToObjs.remove(objToLabel.get(arbitraryThing));

      for (T t : things)
       objToLabel.put(t,label);
      getPart(label).addAll(things);
     }

     public String toString() {
      StringBuilder result = new StringBuilder();
      result.append("\nPARTITION OF " + size + " ELEMENTS INTO " +
        labelToObjs.size() + " PART");
      result.append((labelToObjs.size()==1 ? "" : "S") + "\n");
      for (Map.Entry<Integer,Set<T>> mapEntry :
        labelToObjs.entrySet()) {
       result.append("PART " + mapEntry.getKey() + ": ");
       result.append(mapEntry.getValue() + "\n");
      }
      return result.toString();
     }

     public static void main(String[] args) {
      List<String> strings =
        Arrays.asList("zero one two three".split(" "));

      Partition<String> p = new Partition<String>(strings);
      p.newPart(strings.get(3));  // move "three" to a new part
      System.out.println(p);

      System.out.println("Now moving all of three's part to the " +
        "same part as zero.\n");
      Collection<String> oldPart = p.getPart(strings.get(3));
      //oldPart = Arrays.asList(new String[]{"three"});  // works fine!
      p.moveAll(oldPart, p.getLabel(strings.get(0)));
      System.out.println(p);
     }
    }

/* OUTPUT
PARTITION OF 4 ELEMENTS INTO 2 PARTS
PART 0: [two, one, zero]
PART 1: [three]

Now moving all of three's part to the same part as zero.

 oldPart = [three]
 things = [three]
Now doing oldPart.removeAll(things) ...
 oldPart = []
 things = []

PARTITION OF 4 ELEMENTS INTO 1 PART
PART 0: [two, one, zero]
*/
</code>```

答: Using my debugger I place a breakpoint before the removeAll and I can see (as I suspected) that oldPart and things as the same collection so removing all elements clears that collection.</p>

Title: removeAll seems to affect its argument

Body:
I have written a generic Partition class (a partition is a division of a set into disjoint subsets, called parts). Internally this is a Map<T,Integer> and a Map<Integer,Set<T>>, where the Integers are the labels of the parts. For example partition.getLabel(T t) gives the label of the part that t is in, and partition.move(T t, Integer label) moves t to the partition labelled by label (internally, it updates both the Maps).

But my method for moving a Collection of objects to a new part does not work. It seems that Set.removeAll() is affecting its argument. I think the problem is something like a ConcurrentModificationException, but I can't work it out. Sorry the code is rather long, but I have marked where the problem is (about half-way down), and the output at the bottom should make it clear what the problem is - at the end the partition is in an illegal state.

    import java.util.*;

    public class Partition<T> {
  private Map<T,Integer> objToLabel = new HashMap<T,Integer>();
     private Map<Integer,Set<T>> labelToObjs =
       new HashMap<Integer,Set<T>>();
     private List<Integer> unusedLabels;
     private int size;  // = number of elements

     public Partition(Collection<T> objects) {
      size = objects.size();
      unusedLabels = new ArrayList<Integer>();
      for (int i = 1; i < size; i++)
       unusedLabels.add(i);
      // Put all the objects in part 0.
      Set<T> part = new HashSet<T>(objects);
      for (T t : objects)
       objToLabel.put(t,0);
      labelToObjs.put(0,part);
     }

     public Integer getLabel(T t) {
      return objToLabel.get(t);
     }
     public Set<T> getPart(Integer label) {
      return labelToObjs.get(label);
     }
     public Set<T> getPart(T t) {
      return getPart(getLabel(t));
     }

     public Integer newPart(T t) {
      // Move t to a new part.
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      move(t, newLabel);
      return newLabel;
     }
     public Integer newPart(Collection<T> things) {
      // Move things to a new part. (This assumes that
      // they are all in the same part to start with.)
      Integer newLabel = unusedLabels.remove(0);
      labelToObjs.put(newLabel,new HashSet<T>());
      moveAll(things, newLabel);
      return newLabel;
     }
     public void move(T t, Integer label) {
      // Move t to the part "label".
      Integer oldLabel = getLabel(t);
      getPart(oldLabel).remove(t);
      if (getPart(oldLabel).isEmpty())  // if the old part is
       labelToObjs.remove(oldLabel);  // empty, remove it
      getPart(label).add(t);
      objToLabel.put(t,label);
     }
     public void moveAll(Collection<T> things, Integer label) {
      // Move all the things from their current part to label.
      // (This assumes all the things are in the same part.)
      if (things.size()==0)  return;

      T arbitraryThing = new ArrayList<T>(things).get(0);
      Set<T> oldPart = getPart(arbitraryThing);

   // THIS IS WHERE IT SEEMS TO GO WRONG //////////////////////////
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);
      System.out.println("Now doing oldPart.removeAll(things) ...");
      oldPart.removeAll(things);
      System.out.println(" oldPart = " + oldPart);
      System.out.println(" things = " + things);

      if (oldPart.isEmpty())
       labelToObjs.remove(objToLabel.get(arbitraryThing));

      for (T t : things)
       objToLabel.put(t,label);
      getPart(label).addAll(things);
     }

     public String toString() {
      StringBuilder result = new StringBuilder();
      result.append("\nPARTITION OF " + size + " ELEMENTS INTO " +
        labelToObjs.size() + " PART");
      result.append((labelToObjs.size()==1 ? "" : "S") + "\n");
      for (Map.Entry<Integer,Set<T>> mapEntry :
        labelToObjs.entrySet()) {
       result.append("PART " + mapEntry.getKey() + ": ");
       result.append(mapEntry.getValue() + "\n");
      }
      return result.toString();
     }

     public static void main(String[] args) {
      List<String> strings =
        Arrays.asList("zero one two three".split(" "));

      Partition<String> p = new Partition<String>(strings);
      p.newPart(strings.get(3));  // move "three" to a new part
      System.out.println(p);

      System.out.println("Now moving all of three's part to the " +
        "same part as zero.\n");
      Collection<String> oldPart = p.getPart(strings.get(3));
      //oldPart = Arrays.asList(new String[]{"three"});  // works fine!
      p.moveAll(oldPart, p.getLabel(strings.get(0)));
      System.out.println(p);
     }
    }

/* OUTPUT
PARTITION OF 4 ELEMENTS INTO 2 PARTS
PART 0: [two, one, zero]
PART 1: [three]

Now moving all of three's part to the same part as zero.

 oldPart = [three]
 things = [three]
Now doing oldPart.removeAll(things) ...
 oldPart = []
 things = []

PARTITION OF 4 ELEMENTS INTO 1 PART
PART 0: [two, one, zero]
*/


问:
How to set Total Price with a quantity option list using Jquery
I'm just trying to adjust the total price dynamically when a quantity from 1-5 is selected. I am new to using Jquery so any help is greatly appreciated, thank you!

HTML:

```<code><table>
    <thead>
        <tr>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>
            </td>
            <td id="price" data-price="@i.Price">$@i.Price</td>
        </tr>
    </tbody>
</table>

<p>Total Price: $<span id="total></span></p>
</code>```

JAVASCRIPT:

```<code><script>
    $(document).ready(function () {

        var p = $("#price").find("[data-price]")

        $("#quantity").change(function () {
            var q = $(this).find(':selected').data('quantity');
            var total = p * q;
            $("#total").text(total);
        });
    });
</script>
</code>```

答:
You already find the element with id price, so just get the data-price of it.

$(document).ready(function () {
    const p = $("#price").data('price');

    $("#quantity").change(function () {
        const q = $(this).find(':selected').data('quantity');
        const total = p * q;
        $("#total").text(total);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>
            </td>
            <td id="price" data-price="1000">1000</td>
        </tr>
    </tbody>
</table>

<p>Total Price: $<span id="total"></span></p></code>```

Body:
I'm just trying to adjust the total price dynamically when a quantity from 1-5 is selected. I am new to using Jquery so any help is greatly appreciated, thank you!

HTML:

            Quantity
            Price

                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>

            $@i.Price

Total Price: $

JAVASCRIPT:

Body:
You already find the element with id price, so just get the data-price of it.

$(document).ready(function () {
    const p = $("#price").data('price');

    $("#quantity").change(function () {
        const q = $(this).find(':selected').data('quantity');
        const total = p * q;
        $("#total").text(total);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select id="quantity">
                    <option data-quantity="1">1</option>
                    <option data-quantity="2">2</option>
                    <option data-quantity="3">3</option>
                    <option data-quantity="4">4</option>
                </select>
            </td>
            <td id="price" data-price="1000">1000</td>
        </tr>
    </tbody>
</table>

<p>Total Price: $<span id="total"></span></p>


问:
Call to a member function real_escape_string() on array in
I am struggling with something strange.  I am running a mysqli::real_escape_string on a function to prepare an SQL statement.  I am taking data from one database and developing a query to insert it into a database on a different server.

There error message I get is:

Fatal error: Uncaught Error: Call to a member function real_escape_string() on array in ...

I tried logging a is_array() function right before calling the real_escape_string() and it confirms that it is not an array.  I am getting this whether I pass in a numeric or a string value.   I thought perhaps it was an encoding issue, but I'm not sure how to deal with those.  I tried to convert it before, but that also didn't work:

```<code>$str = $row[$key];                     // Tried on two strings '1' (is_numeric = True), and 'Kevin'
is_array( $str );                      // Returns False
$str = mb_convert_encoding($row[$key], 'UTF-8');    // Consequently, also tried 'latin1' with the same result.
$db->real_escape_string( $str );
</code>```

That also did not work, still is returning the array error.

Any other suggestions on what to try?

Thanks.

答:
Check your variable with function var_dump()</p>

```<code>var_dump($str);
</code>```

Body:
I am struggling with something strange.  I am running a mysqli::real_escape_string on a function to prepare an SQL statement.  I am taking data from one database and developing a query to insert it into a database on a different server.

There error message I get is:

Fatal error: Uncaught Error: Call to a member function real_escape_string() on array in ...

I tried logging a is_array() function right before calling the real_escape_string() and it confirms that it is not an array.  I am getting this whether I pass in a numeric or a string value.   I thought perhaps it was an encoding issue, but I'm not sure how to deal with those.  I tried to convert it before, but that also didn't work:

$str = $row[$key];                     // Tried on two strings '1' (is_numeric = True), and 'Kevin'
is_array( $str );                      // Returns False
$str = mb_convert_encoding($row[$key], 'UTF-8');    // Consequently, also tried 'latin1' with the same result.
$db->real_escape_string( $str );

That also did not work, still is returning the array error.

Any other suggestions on what to try?

Thanks.

Body:
Check your variable with function var_dump()

var_dump($str);


问:
WPF Zooming with Slider Changing ScrollViewer Size
I currently have the following code:

```<code><ScrollViewer DockPanel.Dock="Top">
            <InkCanvas Name="InkCanvasOnImage" Height="203">
                <InkCanvas.LayoutTransform>
                    <ScaleTransform ScaleX="{Binding ElementName=ZoomSlider,Path=Value}" ScaleY="{Binding ElementName=ZoomSlider,Path=Value}"></ScaleTransform>
                </InkCanvas.LayoutTransform>
            </InkCanvas>
        </ScrollViewer>

        <Slider DockPanel.Dock="Top" Name="ZoomSlider" Value="1" Minimum="0.3" Maximum="3" Height="20" />
</code>```

When I adjust the slider, the entire ScrollViewer is changing sizes, and moving the slider up and down in the application. What I intended was just the image that is inside the InkCanvas to zoom in and out. Am I using the right WPF control for this, or did I mess up somewhere? My understanding is that I'm altering the scale of the InkCanvas and not the ScrollViewer Dimensions with the Slider.

答:
Apply Scale Transformation On Image Instead Of InkCanvas

```<code><ScrollViewer DockPanel.Dock="Top">
            <InkCanvas Name="InkCanvasOnImage" Height="203">

                <Image Source="AddImageSourceHere">
                    <Image.LayoutTransform>
                        <ScaleTransform ScaleX="{Binding ElementName=ZoomSlider,Path=Value}" ScaleY="{Binding ElementName=ZoomSlider,Path=Value}"></ScaleTransform>
                    </Image.LayoutTransform>
                </Image>

            </InkCanvas>
        </ScrollViewer>

        <Slider DockPanel.Dock="Top" Name="ZoomSlider" Value="1" Minimum="0.3" Maximum="3" Height="20" />
</code>```

Body:
I currently have the following code:

<ScrollViewer DockPanel.Dock="Top">
            <InkCanvas Name="InkCanvasOnImage" Height="203">
                <InkCanvas.LayoutTransform>
                    <ScaleTransform ScaleX="{Binding ElementName=ZoomSlider,Path=Value}" ScaleY="{Binding ElementName=ZoomSlider,Path=Value}"></ScaleTransform>
                </InkCanvas.LayoutTransform>
            </InkCanvas>
        </ScrollViewer>

        <Slider DockPanel.Dock="Top" Name="ZoomSlider" Value="1" Minimum="0.3" Maximum="3" Height="20" />

When I adjust the slider, the entire ScrollViewer is changing sizes, and moving the slider up and down in the application. What I intended was just the image that is inside the InkCanvas to zoom in and out. Am I using the right WPF control for this, or did I mess up somewhere? My understanding is that I'm altering the scale of the InkCanvas and not the ScrollViewer Dimensions with the Slider.

Body:
Apply Scale Transformation On Image Instead Of InkCanvas

<ScrollViewer DockPanel.Dock="Top">
            <InkCanvas Name="InkCanvasOnImage" Height="203">

                <Image Source="AddImageSourceHere">
                    <Image.LayoutTransform>
                        <ScaleTransform ScaleX="{Binding ElementName=ZoomSlider,Path=Value}" ScaleY="{Binding ElementName=ZoomSlider,Path=Value}"></ScaleTransform>
                    </Image.LayoutTransform>
                </Image>

            </InkCanvas>
        </ScrollViewer>

        <Slider DockPanel.Dock="Top" Name="ZoomSlider" Value="1" Minimum="0.3" Maximum="3" Height="20" />


问:
How to loop through a object array in an Alexa Intent?
So the problem is I am not able to loop through the question's array in the loop in the quizIntent handler. Only the first question is shown and then it does not move any further. Rest of the code is working fine.
What I want to do is Keep on asking questions till the array runs out of them and break out of the loop when the user gives a wrong answer.

I am just a newbie to Alexa Programming. Please help.

Here is my array

```<code>    const got = [
    {
        question: "Grey Wind, Lady, Ghost, Shaggydog, Summer and the sixth direwolve's name is?",
        answer: 'nymeria',
    },
    {
        question: "What was the name of the sinister castle where Arya and Gendry were held prisoner in season two?",
        answer: 'harrenhal',
    },
    {
        question: "What is a person called that can enter the minds of animals?",
        answer: 'warg',
    },
    {
        question: "What was the name of the Stark ancestral sword that was melted down by Tywin Lannister?",
        answer: 'ice',
    }
];
</code>```

Here is my Alexa Intent

```<code>    var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to appear for a trial by combat");
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("A five year old has more courage than you.");
        this.emit(":responseReady");
       }

       for(var i = 0; i <got.length; i++){
            var myanswer = this.event.request.intent.slots.answer.value;
            var item = got[i].question;
            this.response.speak(item).listen();
            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. You are dead");
                this.emit(':responseReady');

            }
            if(i==got.length-1){
                this.response.speak("You won");
                this.emit(':responseReady');
            }

      }

   },
   "LaunchRequest": function () {
    this.response.speak("Valar Morghulis").listen("You are supposed to say Valar Dohareis");
    this.emit(":responseReady");
   }

};
</code>```

Here is my Intent Schema in case you wanna look at that too

```<code>{
  "languageModel": {
    "types": [
      {
        "name": "answerSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Nymeria",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Harrenhal",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Warg",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Ice",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "decisionSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Yes",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "No",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Naah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yeah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yup",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Nope",
              "synonyms": []
            }
          }
        ]
      }
    ],
    "intents": [
      {
        "name": "AMAZON.CancelIntent",
        "samples": []
      },
      {
        "name": "AMAZON.HelpIntent",
        "samples": []
      },
      {
        "name": "AMAZON.StopIntent",
        "samples": []
      },
      {
        "name": "customIntent",
        "samples": [
          "Valar Dohareis",
          "hello",
          "hola"
        ],
        "slots": []
      },
      {
        "name": "quizIntent",
        "samples": [
          "{decision}",
          "The answer is {answer}"
        ],
        "slots": [
          {
            "name": "decision",
            "type": "decisionSlot"
          },
          {
            "name": "answer",
            "type": "answerSlot"
          }
        ]
      }
    ],
    "invocationName": "quiz game"
  }
}
</code>```

答:
One way I figured out to solve this issue was :

```<code>    var i = 0;
var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to take part in a trial by combat?").listen();
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("Battles have been won against harder odds! Even little Lyanna Mormont has more courage than you.");
        this.emit(":responseReady");
       }

       if(i<=got.length){
           var item = got[i].question;
           if(i == 0){
                this.response.speak("Be attentive; just like life, I won't repeat or give you a second chance. Here you go; " + item).listen();
                this.emit(":responseReady");
           }
           else {
           this.response.speak(item).listen();
           this.emit(":responseReady");
           }
        }
   },

    "answerIntent": function () {
            var myanswer = this.event.request.intent.slots.answer.value;

            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. The correct answer is " + got[i].answer + ". You are dead.");
                this.emit(':responseReady');

            }
            i++;
            if(i==got.length){
                i=0;
                this.response.speak("You emerged the ultimate victor. The best in all of Planetos.");
                this.emit(':responseReady');
            }
            this.response.speak("You survived. Say ready, when you are, for the next combat!").listen();
            this.emit(':responseReady');
    },
</code>```

The idea is to switch back and forth through the quiz intent and the answer intent.

Body:
So the problem is I am not able to loop through the question's array in the loop in the quizIntent handler. Only the first question is shown and then it does not move any further. Rest of the code is working fine.
What I want to do is Keep on asking questions till the array runs out of them and break out of the loop when the user gives a wrong answer.

I am just a newbie to Alexa Programming. Please help.

Here is my array

    const got = [
    {
        question: "Grey Wind, Lady, Ghost, Shaggydog, Summer and the sixth direwolve's name is?",
        answer: 'nymeria',
    },
    {
        question: "What was the name of the sinister castle where Arya and Gendry were held prisoner in season two?",
        answer: 'harrenhal',
    },
    {
        question: "What is a person called that can enter the minds of animals?",
        answer: 'warg',
    },
    {
        question: "What was the name of the Stark ancestral sword that was melted down by Tywin Lannister?",
        answer: 'ice',
    }
];

Here is my Alexa Intent

    var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to appear for a trial by combat");
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("A five year old has more courage than you.");
        this.emit(":responseReady");
       }

       for(var i = 0; i <got.length; i++){
            var myanswer = this.event.request.intent.slots.answer.value;
            var item = got[i].question;
            this.response.speak(item).listen();
            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. You are dead");
                this.emit(':responseReady');

            }
            if(i==got.length-1){
                this.response.speak("You won");
                this.emit(':responseReady');
            }

      }

   },
   "LaunchRequest": function () {
    this.response.speak("Valar Morghulis").listen("You are supposed to say Valar Dohareis");
    this.emit(":responseReady");
   }

};

Here is my Intent Schema in case you wanna look at that too

{
  "languageModel": {
    "types": [
      {
        "name": "answerSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Nymeria",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Harrenhal",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Warg",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Ice",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "decisionSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Yes",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "No",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Naah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yeah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yup",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Nope",
              "synonyms": []
            }
          }
        ]
      }
    ],
    "intents": [
      {
        "name": "AMAZON.CancelIntent",
        "samples": []
      },
      {
        "name": "AMAZON.HelpIntent",
        "samples": []
      },
      {
        "name": "AMAZON.StopIntent",
        "samples": []
      },
      {
        "name": "customIntent",
        "samples": [
          "Valar Dohareis",
          "hello",
          "hola"
        ],
        "slots": []
      },
      {
        "name": "quizIntent",
        "samples": [
          "{decision}",
          "The answer is {answer}"
        ],
        "slots": [
          {
            "name": "decision",
            "type": "decisionSlot"
          },
          {
            "name": "answer",
            "type": "answerSlot"
          }
        ]
      }
    ],
    "invocationName": "quiz game"
  }
}

Body:
One way I figured out to solve this issue was :

    var i = 0;
var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to take part in a trial by combat?").listen();
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("Battles have been won against harder odds! Even little Lyanna Mormont has more courage than you.");
        this.emit(":responseReady");
       }

       if(i<=got.length){
           var item = got[i].question;
           if(i == 0){
                this.response.speak("Be attentive; just like life, I won't repeat or give you a second chance. Here you go; " + item).listen();
                this.emit(":responseReady");
           }
           else {
           this.response.speak(item).listen();
           this.emit(":responseReady");
           }
        }
   },

    "answerIntent": function () {
            var myanswer = this.event.request.intent.slots.answer.value;

            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. The correct answer is " + got[i].answer + ". You are dead.");
                this.emit(':responseReady');

            }
            i++;
            if(i==got.length){
                i=0;
                this.response.speak("You emerged the ultimate victor. The best in all of Planetos.");
                this.emit(':responseReady');
            }
            this.response.speak("You survived. Say ready, when you are, for the next combat!").listen();
            this.emit(':responseReady');
    },

The idea is to switch back and forth through the quiz intent and the answer intent.


问:
Use XML child node as label in Spark list itemRenderer
In ActionScript, I whittle down my XML to a series of nodes, all formed like this:

```<code><option letter="A">
    <letter>A</letter>
    <response>Thank you</response>
    <posFeed>Excellent</posFeed>
    <negFeed>Terrible</negFeed>
    <score>-1</score>
    <elimOptions>B</elimOptions>
</option>
</code>```

When I set this series as the dataProvider for my Spark list that uses a custom item renderer with a Spark label, I set the label.text={data}, which displays each full set of nodes as a list item.

If I don't want to whittle the XML down to just the  nodes beforehand (I'd like the full set intact for other functions I have to perform), how can I set just the response node to be the data to use for the label in the itemRenderer? I tried setting the label text={data.response}, but that doesn't work (a full set of nodes still appears as each list item.

答:
Like this:

```<code><fx:Declarations>
    <fx:XML id="data">
        <options>
            <option letter="A">
                <letter>A</letter>
                <response>Thank you</response>
                <posFeed>Excellent</posFeed>
                <negFeed>Terrible</negFeed>
                <score>-1</score>
                <elimOptions>B</elimOptions>
            </option>
            <option letter="B">
                <letter>B</letter>
                <response>Thank you B</response>
                <posFeed>Excellent B</posFeed>
                <negFeed>Terrible B</negFeed>
                <score>-1</score>
                <elimOptions>B</elimOptions>
            </option>
        </options>
    </fx:XML>
</fx:Declarations>

<s:List labelField="response">
    <s:dataProvider>
        <s:XMLListCollection source="{data.option}" />
    </s:dataProvider>
</s:List>
</code>```

I should add that when I did this, I didn't have any trouble using a custom item renderer:

```<code><s:List itemRenderer="DataItemRenderer">
    <s:dataProvider>
        <s:XMLListCollection source="{data.option}" />
    </s:dataProvider>
</s:List>

<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                xmlns:mx="library://ns.adobe.com/flex/mx"
                autoDrawBackground="true">

    <s:Label text="{data.response}"/>

</s:ItemRenderer>
</code>```

Body:
In ActionScript, I whittle down my XML to a series of nodes, all formed like this:

<option letter="A">
    <letter>A</letter>
    <response>Thank you</response>
    <posFeed>Excellent</posFeed>
    <negFeed>Terrible</negFeed>
    <score>-1</score>
    <elimOptions>B</elimOptions>
</option>

When I set this series as the dataProvider for my Spark list that uses a custom item renderer with a Spark label, I set the label.text={data}, which displays each full set of nodes as a list item.

If I don't want to whittle the XML down to just the  nodes beforehand (I'd like the full set intact for other functions I have to perform), how can I set just the response node to be the data to use for the label in the itemRenderer? I tried setting the label text={data.response}, but that doesn't work (a full set of nodes still appears as each list item.

Body:
Like this:

<fx:Declarations>
    <fx:XML id="data">
        <options>
            <option letter="A">
                <letter>A</letter>
                <response>Thank you</response>
                <posFeed>Excellent</posFeed>
                <negFeed>Terrible</negFeed>
                <score>-1</score>
                <elimOptions>B</elimOptions>
            </option>
            <option letter="B">
                <letter>B</letter>
                <response>Thank you B</response>
                <posFeed>Excellent B</posFeed>
                <negFeed>Terrible B</negFeed>
                <score>-1</score>
                <elimOptions>B</elimOptions>
            </option>
        </options>
    </fx:XML>
</fx:Declarations>

<s:List labelField="response">
    <s:dataProvider>
        <s:XMLListCollection source="{data.option}" />
    </s:dataProvider>
</s:List>

I should add that when I did this, I didn't have any trouble using a custom item renderer:

<s:List itemRenderer="DataItemRenderer">
    <s:dataProvider>
        <s:XMLListCollection source="{data.option}" />
    </s:dataProvider>
</s:List>

<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                xmlns:mx="library://ns.adobe.com/flex/mx"
                autoDrawBackground="true">

    <s:Label text="{data.response}"/>

</s:ItemRenderer>


问:
User email not showing in template [METEOR]!
I have a user index and would like to display information on each user. User ID shows up fine, but the app isn't showing emails.

Here is my template:

```<code><template name="users">
  <h1>List of all users</h1>
  {{#each users}}
    <div class="list_item">
      <p>ID: {{_id}}</p>
      <p>Email: {{email}}</p>
    </div>
  {{/each}}
</template>
</code>```

And here are my routes:

```<code>Router.route('/users', function () {
  this.render('users');
}, {
  waitOn: function() {
    return [
      Meteor.subscribe('users')
    ]
  },

  data:  {users: Meteor.users.find({})}
});
</code>```

And finally, my publication:

```<code>Meteor.publish('users', function () {
  return Meteor.users.find({}, {fields: {emails: 1, profile: 1}});
});
</code>```

Any ideas?

答:
```<code>{{ currentUser.emails.[0].address }}
</code>```

Body:
I have a user index and would like to display information on each user. User ID shows up fine, but the app isn't showing emails.

Here is my template:

<template name="users">

List of all users

  {{#each users}}

ID: {{_id}}

Email: {{email}}

  {{/each}}
</template>

And here are my routes:

Router.route('/users', function () {
  this.render('users');
}, {
  waitOn: function() {
    return [
      Meteor.subscribe('users')
    ]
  },

  data:  {users: Meteor.users.find({})}
});

And finally, my publication:

Meteor.publish('users', function () {
  return Meteor.users.find({}, {fields: {emails: 1, profile: 1}});
});

Any ideas?

Body: {{ currentUser.emails.[0].address }}