问:
Button from Fragment is Crashing the app
I put a Button in fragment with the corresponding listener. Every time I call on this activity the app crashes. Logcat show a null pointer exception. The code below is a snippet from the Fragment class.

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.setAdapter(new MyCarProfileRecyclerViewAdapter(carProfileContent.ITEMS, mListener));
    }

    Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });

    return view;
}
</code>```

Logcat shows:

```<code>FATAL EXCEPTION: main
Process: com.example.app, PID: 13571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.CarProfileListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mikepuno.parkeazy.CarProfileFragment.onCreateView(CarProfileFragment.java:78)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5353)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)
</code>```

I've been looking at multiple similar issues here but it just don't seem to work for me. Am I missing anything from the way I added the Button and the listener?

fragment_carprofile_list.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.mikepuno.parkeazy.CarProfileFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.mikepuno.parkeazy.CarProfileFragment"
    tools:listitem="@layout/fragment_carprofile" />
</code>```

fragment_carprofile.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/plateNumberTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="?attr/textAppearanceListItem" />

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

        <TextView
            android:id="@+id/brandTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/modelTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/colorTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <Button
            android:id="@+id/editCarProfileButton"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:text="Edit" />

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

Adapter Class

```<code>public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

    private final List<CarProfile> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_carprofile, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
        holder.mBrandTextView.setText(mValues.get(position).getBrand());
        holder.mModelTextView.setText(mValues.get(position).getModel());
        holder.mColorTextView.setText(mValues.get(position).getColor());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mPlateNumberTextView;
        public final TextView mBrandTextView;
        public final TextView mModelTextView;
        public final TextView mColorTextView;
        public CarProfile mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
            mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
            mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
            mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
        }
    }
}
</code>```

答:
After you inflate your view

```<code>View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);
</code>```

you assume that view is RecyclerView. That means root element is recyclerview.

Then trying to find a button inside of that recyclerview by doing

```<code>Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
</code>```

which returns null ofcourse. Then trying to set a click listener on null object.

Looks like your xml file is wrong. If your each row has button that you are trying to find, you need to catch it in your adapter class then notify fragment to do your process.

SOLUTION (EDIT):

Remove these lines from onCreateView in Fragment.

```<code>Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });
</code>```

You have already a interface that notify the fragment.
So that we are going to use it for editing.

So the final adapter class should be like

```<code>public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

private final List<CarProfile> mValues;
private final OnListFragmentInteractionListener mListener;

public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
    mValues = items;
    mListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_carprofile, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.mItem = mValues.get(position);
    holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
    holder.mBrandTextView.setText(mValues.get(position).getBrand());
    holder.mModelTextView.setText(mValues.get(position).getModel());
    holder.mColorTextView.setText(mValues.get(position).getColor());
}

@Override
public int getItemCount() {
    return mValues.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public final TextView mPlateNumberTextView;
    public final TextView mBrandTextView;
    public final TextView mModelTextView;
    public final TextView mColorTextView;
    public CarProfile mItem;

    public ViewHolder(View view) {
        super(view);

        view.setClickable(true); // This is important
        view.setOnClickListener(this);

        mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
        mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
        mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
        mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
    }

    public void onClick(View view) {
       if (null != mListener) {
            mListener.onListFragmentInteraction(mValues.get(getAdapterPosition()));
       }
    }

    @Override
    public String toString() {
        return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
    }
   }
</code>```

Then your fragment

```<code>    @Override
    public void onListFragmentInteraction(CarProfile profile) {
        // TODO Pass your profile to ReserverActivity by using bundles.
        startActivity(new Intent(getActivity(), ReserveActivity.class));
    }
</code>```

You can improve the code by notify fragment on your button click. So your button click listener and notify code must also be in here.

Body:
I put a Button in fragment with the corresponding listener. Every time I call on this activity the app crashes. Logcat show a null pointer exception. The code below is a snippet from the Fragment class.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.setAdapter(new MyCarProfileRecyclerViewAdapter(carProfileContent.ITEMS, mListener));
    }

    Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });

    return view;
}

Logcat shows:

FATAL EXCEPTION: main
Process: com.example.app, PID: 13571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.CarProfileListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mikepuno.parkeazy.CarProfileFragment.onCreateView(CarProfileFragment.java:78)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5353)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)

I've been looking at multiple similar issues here but it just don't seem to work for me. Am I missing anything from the way I added the Button and the listener?

fragment_carprofile_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.mikepuno.parkeazy.CarProfileFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.mikepuno.parkeazy.CarProfileFragment"
    tools:listitem="@layout/fragment_carprofile" />

fragment_carprofile.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/plateNumberTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="?attr/textAppearanceListItem" />

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

        <TextView
            android:id="@+id/brandTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/modelTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/colorTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <Button
            android:id="@+id/editCarProfileButton"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:text="Edit" />

    </LinearLayout>
</LinearLayout>

Adapter Class

public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

    private final List<CarProfile> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_carprofile, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
        holder.mBrandTextView.setText(mValues.get(position).getBrand());
        holder.mModelTextView.setText(mValues.get(position).getModel());
        holder.mColorTextView.setText(mValues.get(position).getColor());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mPlateNumberTextView;
        public final TextView mBrandTextView;
        public final TextView mModelTextView;
        public final TextView mColorTextView;
        public CarProfile mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
            mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
            mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
            mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
        }
    }
}

Body:
After you inflate your view

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

you assume that view is RecyclerView. That means root element is recyclerview.

Then trying to find a button inside of that recyclerview by doing

Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);

which returns null ofcourse. Then trying to set a click listener on null object.

Looks like your xml file is wrong. If your each row has button that you are trying to find, you need to catch it in your adapter class then notify fragment to do your process.

SOLUTION (EDIT):

Remove these lines from onCreateView in Fragment.

Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });

You have already a interface that notify the fragment.
So that we are going to use it for editing.

So the final adapter class should be like

public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

private final List<CarProfile> mValues;
private final OnListFragmentInteractionListener mListener;

public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
    mValues = items;
    mListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_carprofile, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.mItem = mValues.get(position);
    holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
    holder.mBrandTextView.setText(mValues.get(position).getBrand());
    holder.mModelTextView.setText(mValues.get(position).getModel());
    holder.mColorTextView.setText(mValues.get(position).getColor());
}

@Override
public int getItemCount() {
    return mValues.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public final TextView mPlateNumberTextView;
    public final TextView mBrandTextView;
    public final TextView mModelTextView;
    public final TextView mColorTextView;
    public CarProfile mItem;

    public ViewHolder(View view) {
        super(view);

        view.setClickable(true); // This is important
        view.setOnClickListener(this);

        mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
        mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
        mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
        mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
    }

    public void onClick(View view) {
       if (null != mListener) {
            mListener.onListFragmentInteraction(mValues.get(getAdapterPosition()));
       }
    }

    @Override
    public String toString() {
        return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
    }
   }

Then your fragment

    @Override
    public void onListFragmentInteraction(CarProfile profile) {
        // TODO Pass your profile to ReserverActivity by using bundles.
        startActivity(new Intent(getActivity(), ReserveActivity.class));
    }

You can improve the code by notify fragment on your button click. So your button click listener and notify code must also be in here.


来源: stackexchange

问:
Passing a non-associative function to reduce
My program has this line:

```<code>Function<String, Integer> f = (String s) -> s.chars().reduce(0, (a, b) -> 2 * a + b);
</code>```

The function being passed to reduce is not associative. Reduce's documentation says that the function passed must be associative.

How can I rewrite this as an expression which doesn't break reduce's contract?

答:
Under the current implementation and IFF you are not going to use parallel - you are safe with what you have right now. Obviously if you are OK with these disclaimers.

Or you can obviously create the function with a for loop:

```<code> Function<String, Integer> f = s -> {
        int first = s.charAt(0) * 2 + s.charAt(1);
        int total = first;

        for (int x = 1; x < s.length() - 1; x++) {
            total = total * 2 + s.charAt(x + 1);
        }

        return total;

    };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My program has this line:

Function<String, Integer> f = (String s) -> s.chars().reduce(0, (a, b) -> 2 * a + b);

The function being passed to reduce is not associative. Reduce's documentation says that the function passed must be associative.

How can I rewrite this as an expression which doesn't break reduce's contract?

Body:
Under the current implementation and IFF you are not going to use parallel - you are safe with what you have right now. Obviously if you are OK with these disclaimers.

Or you can obviously create the function with a for loop:

 Function<String, Integer> f = s -> {
        int first = s.charAt(0) * 2 + s.charAt(1);
        int total = first;

        for (int x = 1; x < s.length() - 1; x++) {
            total = total * 2 + s.charAt(x + 1);
        }

        return total;

    };


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答:
If knowing the order rapidly is a big concern, then consider adding an 'order' field to your element - and override your queue implementation to fill that field.

I would not consider the LinkedList 'index' as a solution.  It is implemented as a list traversal.

ContentLicense: CC BY-SA 2.5


问:
How to remove "Chrome is being controlled by automated test software"
How can I remove this message by default?

I'm using Puppeteer, when chromium launches, it shows this message.

答:
You can try

puppeteer.launch({
  args: ['--disable-infobars']
})
```
<p>https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions
https://peter.sh/experiments/chromium-command-line-switches/#disable-infobars</p>
<hr />
<p><strong>2020 UPDATE:</strong></p>
<p>This flag has been deprecated by chromium citing that its a security risk and "can be misused for malicious purposes"</p>
<p>You can achieve the same effect by using:</p>
<pre class="lang-js prettyprint-override"><code>puppeteer.launch({
  ignoreDefaultArgs: ['--enable-automation']
})
</code>```

This however may have other side effects.

Body:
You can try

puppeteer.launch({
  args: ['--disable-infobars']
})

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions
https://peter.sh/experiments/chromium-command-line-switches/#disable-infobars

2020 UPDATE:

This flag has been deprecated by chromium citing that its a security risk and "can be misused for malicious purposes"

You can achieve the same effect by using:

puppeteer.launch({
  ignoreDefaultArgs: ['--enable-automation']
})

This however may have other side effects.

ContentLicense: CC BY-SA 4.0


问:
Failed to update autoscale configuration. (Azure scale set)
I'm receiving the following error when trying to manually increase the number of instances above 10 on an Azure Scale set.

Failed to update autoscale configuration for 'XXXX'.{  "error": {
  "details": [],  "code":
  "InboundNatPoolFrontendPortRangeSmallerThanRequestedPorts",
  "message": "The frontend port range for the inboundNATpool
  /subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Network/loadBalancers/LB-xxx/inboundNatPools/DebuggerListenerNatPool-4vhwwa8stp
  is smaller than the requested number of ports 15 in VM scale set
  /subscriptions/xxx/resourceGroups/xxxx/providers/Microsoft.Compute/virtualMachineScaleSets/XXXX."
  }  }

The default number of instances is 3 and any number up to 10 works as expected. The subscription has plenty of available cores.

Looking at the referenced load balancer in Azure portal, I cannot see any settings that are obviously linked to this error message. The LB has a setting 'SKU' that has a value of 'Basic' which i guess may be an issue? (although reading up on this would indicate the limit there is 100)

There are no google results for the code 'InboundNatPoolFrontendPortRangeSmallerThanRequestedPorts' and searching for parts of the error message didn't give any meaningful results.

Any pointers appreciated

答: Keep in mind that if you have overprovisioning on, you will temporarily get more VMs than you asked for (documentation here). So you'll need to have enough NAT rules to accomidate the extra VMs. You should never need more than 2 times as many NAT rules as VMs (so if your VM max is 10, you should never need more than 20 NAT rules in the pool).</p>


问:
Function returning a lambda expression
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:

```<code>auto retFun() -> decltype ([](int x) -> int)
{
    return [](int x) { return x; }
}
</code>```

Nor this:

```<code>int(int) retFun();
</code>```

I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?

答:
You don't need a handcrafted function object, just use std::function, to which lambda functions are convertible:

This example returns the integer identity function:

```<code>std::function<int (int)> retFun() {
    return [](int x) { return x; };
}
</code>```

Title: Function returning a lambda expression

Body:
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:

auto retFun() -> decltype ([](int x) -> int)
{
    return [](int x) { return x; }
}

Nor this:

int(int) retFun();

I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?

Body:
You don't need a handcrafted function object, just use std::function, to which lambda functions are convertible:

This example returns the integer identity function:

std::function<int (int)> retFun() {
    return [](int x) { return x; };
}


问:
How to display tooltip in zoomable circle graph
I have tried displaying tooltip in zoomable circle packing. I need to display it onMouseover, and i am able to get the alert but not in tooltip format.

Can someone help me to get this..

Thanks.

答:
Please find the below. Hope this helps you.

```<code>var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);

var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.style("background", "#000")
.text("a simple tooltip");

d3.select("body")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; })
.on("mouseover", function(d){tooltip.text(d); return
 tooltip.style("visibility", "visible");})
  .on("mousemove", function(){return tooltip.style("top", (d3.event.pageY-
 10)+"px").style("left",(d3.event.pageX+10)+"px");})
  .on("mouseout", function(){return tooltip.style("visibility",
 "hidden");});
</code>```

The var tooltip = block is where we’re creating our tooltip itself, which is just a div that is hidden by default and positioned “above” all the elements on the page (using a high z-index value).

Once that is created, we’ve then added onto the bar chart creation code of d3.js using a number of .on method calls, which accept the appropriate event and the function to fire when that event occurs. The most crucial is in the first mouseover event function, where we specify tooltip.text(d), meaning the text of our tooltip is set to the passed in data value of d.

Here yo will get customizable div tooltips with the data we passed.

Body:
Please find the below. Hope this helps you.

var data = [4, 8, 15, 16, 23, 42];

var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);

var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.style("background", "#000")
.text("a simple tooltip");

d3.select("body")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; })
.on("mouseover", function(d){tooltip.text(d); return
 tooltip.style("visibility", "visible");})
  .on("mousemove", function(){return tooltip.style("top", (d3.event.pageY-
 10)+"px").style("left",(d3.event.pageX+10)+"px");})
  .on("mouseout", function(){return tooltip.style("visibility",
 "hidden");});

The var tooltip = block is where we’re creating our tooltip itself, which is just a div that is hidden by default and positioned “above” all the elements on the page (using a high z-index value).

Once that is created, we’ve then added onto the bar chart creation code of d3.js using a number of .on method calls, which accept the appropriate event and the function to fire when that event occurs. The most crucial is in the first mouseover event function, where we specify tooltip.text(d), meaning the text of our tooltip is set to the passed in data value of d.

Here yo will get customizable div tooltips with the data we passed.


问:
Store traefik let's encrypt certificates not as json
you know traefik is able to do all the Let's Encrypt stuff (request and renew) for your webservices. But traefik stores the requested certificates as a JSON-file, which isn't the common format for certificates.

I want to use the Let's Encrypt certificates also for my mail-server, so I need them in simple format: *.pem or *.crt.

Here my question: Is it possible that traefik stores the Let's Encrypt certificates in a common format?

Thanks for help!

答:
Disclaimer: I'm new to Traefik, so there might be a better solution than this that I'm not aware of.

What I've done is used a Python script by JayH5 to extract the keys files from the acme.json file.

```<code>def read_domain_certs(acme_json_path, domain):
    with open(acme_json_path) as acme_json_file:
        acme_json = json.load(acme_json_file)

    certs_json = acme_json['DomainsCertificate']['Certs']
    domain_certs = [cert['Certificate'] for cert in certs_json
                    if cert['Domains']['Main'] == domain]

    if not domain_certs:
        raise RuntimeError(
            'Unable to find certificate for domain "%s"' % (domain,))
    elif len(domain_certs) > 1:
        raise RuntimeError(
            'More than one (%d) certificates for domain "%s"' % (domain,))

    [domain_cert] = domain_certs
    return (base64.b64decode(domain_cert['PrivateKey']),
            base64.b64decode(domain_cert['Certificate']))
</code>```

Depending on your use case, you could skip saving the files and load the keys directly from the JSON file using that code. However, if you do need the PEM files, the script does also writes the key contents, if you need the files on disk.

```<code>def write_cert(storage_dir, filename, cert_content):
    cert_path = os.path.join(storage_dir, filename)
    with open(cert_path, 'w') as cert_file:
        cert_file.write(cert_content)
    os.chmod(cert_path, 0o600)
</code>```

Body:
Disclaimer: I'm new to Traefik, so there might be a better solution than this that I'm not aware of.

What I've done is used a Python script by JayH5 to extract the keys files from the acme.json file.

def read_domain_certs(acme_json_path, domain):
    with open(acme_json_path) as acme_json_file:
        acme_json = json.load(acme_json_file)

    certs_json = acme_json['DomainsCertificate']['Certs']
    domain_certs = [cert['Certificate'] for cert in certs_json
                    if cert['Domains']['Main'] == domain]

    if not domain_certs:
        raise RuntimeError(
            'Unable to find certificate for domain "%s"' % (domain,))
    elif len(domain_certs) > 1:
        raise RuntimeError(
            'More than one (%d) certificates for domain "%s"' % (domain,))

    [domain_cert] = domain_certs
    return (base64.b64decode(domain_cert['PrivateKey']),
            base64.b64decode(domain_cert['Certificate']))

Depending on your use case, you could skip saving the files and load the keys directly from the JSON file using that code. However, if you do need the PEM files, the script does also writes the key contents, if you need the files on disk.

def write_cert(storage_dir, filename, cert_content):
    cert_path = os.path.join(storage_dir, filename)
    with open(cert_path, 'w') as cert_file:
        cert_file.write(cert_content)
    os.chmod(cert_path, 0o600)


问:
Microsoft Access SQL Joins
List all players and their ages for their associated current team for teams that have a manager.

Here are my 3 Tables and their attributes

```<code>PLAYER
PLAYERNUM Primary Key
PLAYERNAME
PlayerAge

TEAM
TEAMNUM Primary Key
TEAMNAME
TeamCity
MgrNum

AFFILIATION
PLAYERNUM Primary Key/Foreign Key
TEAMNUM Primary Key/Foreign Key
AffilYrs
AffilBatAvg
AffilDateStart Foreign Key
AffilDateEnd
AffilCurrentTeam
</code>```

Here is my SQL:

```<code>    SELECT PLAYERNAME, PlayerAge
    FROM PLAYER INNER JOIN AFFILIATION
    ON PLAYER.PLAYERNUM = AFFILIATION.PLAYERNUM
    INNER JOIN TEAM
    ON AFFILIATION.TEAMNUM = TEAM.TEAMNUM
    WHERE MgrNum IS NOT NULL;
</code>```

I am given the error missing operator in query expression

答:
Perhaps it should be;

```<code>    [NotTested]
    SELECT PLAYERNAME, PlayerAge
        FROM (PLAYER INNER JOIN AFFILIATION
        ON PLAYER.PLAYERNUM = AFFILIATION.PLAYERNUM)
        INNER JOIN TEAM
        ON AFFILIATION.TEAMNUM = TEAM.TEAMNUM
        WHERE MgrNum IS NOT NULL;
        GROUP BY PLAYER.PLAYERNAME, PLAYER.PlayerAge
</code>```

You should use parentheses for multiple joins in access.

Title: Microsoft Access SQL Joins

Body:
List all players and their ages for their associated current team for teams that have a manager.

Here are my 3 Tables and their attributes

PLAYER
PLAYERNUM Primary Key
PLAYERNAME
PlayerAge

TEAM
TEAMNUM Primary Key
TEAMNAME
TeamCity
MgrNum

AFFILIATION
PLAYERNUM Primary Key/Foreign Key
TEAMNUM Primary Key/Foreign Key
AffilYrs
AffilBatAvg
AffilDateStart Foreign Key
AffilDateEnd
AffilCurrentTeam

Here is my SQL:

    SELECT PLAYERNAME, PlayerAge
    FROM PLAYER INNER JOIN AFFILIATION
    ON PLAYER.PLAYERNUM = AFFILIATION.PLAYERNUM
    INNER JOIN TEAM
    ON AFFILIATION.TEAMNUM = TEAM.TEAMNUM
    WHERE MgrNum IS NOT NULL;

I am given the error missing operator in query expression

Body:
Perhaps it should be;

    [NotTested]
    SELECT PLAYERNAME, PlayerAge
        FROM (PLAYER INNER JOIN AFFILIATION
        ON PLAYER.PLAYERNUM = AFFILIATION.PLAYERNUM)
        INNER JOIN TEAM
        ON AFFILIATION.TEAMNUM = TEAM.TEAMNUM
        WHERE MgrNum IS NOT NULL;
        GROUP BY PLAYER.PLAYERNAME, PLAYER.PlayerAge

You should use parentheses for multiple joins in access.


问:
Add lines to plot in pyplot
I want to plot a sin-function and show it, then add a cos-function and plot again, so that the output is two plots, the first with only sin and the second with sin AND cos. But show() flushes the plot, how do I prevent the flushing? </p>

```<code>import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

plt.plot(x,y1)
plt.show() #can I avoid flushing here?

plt.plot(x,y2)
plt.show()
</code>```

<p>I need it in a jupyter notebook. </p>

答:
Use subplot i.e.

```<code>import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)
#define 2-plots vertically, 1-plot horizontally, and select 1st plot
plt.subplot(2,1,1)
plt.plot(x,y1)

#As above but select 2nd plot
plt.subplot(2,1,2)
#plot both functions
plt.plot(x,y1)
plt.plot(x,y2)
#show only once for all plots
plt.show()
</code>```

Title: Add lines to plot in pyplot

Body:
I want to plot a sin-function and show it, then add a cos-function and plot again, so that the output is two plots, the first with only sin and the second with sin AND cos. But show() flushes the plot, how do I prevent the flushing?

import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

plt.plot(x,y1)
plt.show() #can I avoid flushing here?

plt.plot(x,y2)
plt.show()

I need it in a jupyter notebook.

Body:
Use subplot i.e.

import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)
#define 2-plots vertically, 1-plot horizontally, and select 1st plot
plt.subplot(2,1,1)
plt.plot(x,y1)

#As above but select 2nd plot
plt.subplot(2,1,2)
#plot both functions
plt.plot(x,y1)
plt.plot(x,y2)
#show only once for all plots
plt.show()


问:
Correctly importing LZString in webpack project
I'm trying import LZString 1.4.4 to my webpack project, however I'm getting this error in chrome console:

```<code>core.es5.js?de3d:1020 ERROR TypeError: Cannot read property 'compress' of undefined
at FileReader.reader.onload (file-upload.ts?e535:117)
at ZoneDelegate.invoke (zone.js?6524:392)
at Object.onInvoke (core.es5.js?de3d:3890)
at ZoneDelegate.invoke (zone.js?6524:391)
at Zone.runGuarded (zone.js?6524:155)
at FileReader.eval (zone.js?6524:133)
</code>```

I'm importing LZString this way:

```<code>import { LZString } from 'lz-string';
</code>```

and the piece of code that is using LZString is this:

```<code>private compressAndChangeModel(file:File){
    let reader:FileReader = new FileReader();
    reader.onload = () => {
        let compressed:string=LZString.compress(reader.result);
        this.modelChange.next(compressed);
    };
    reader.onerror = (error) => {
        console.log('Error when trying to generate base64: ', error);
    };
    reader.readAsDataURL(file);
}
</code>```

How is the correct way of import LZString in my webpack project?

答:
LZString doesn't export a property called LZString. You could use a synthetic default import, import LZString from 'lz-string';.

However, compress is exported, so you can just use import { compress } from 'lz-string' and just use compress().

If you don't like the generic compress name you can also alias it using import { compress as lzStringCompress } from 'lz-string'; instead.

Body:
I'm trying import LZString 1.4.4 to my webpack project, however I'm getting this error in chrome console:

core.es5.js?de3d:1020 ERROR TypeError: Cannot read property 'compress' of undefined
at FileReader.reader.onload (file-upload.ts?e535:117)
at ZoneDelegate.invoke (zone.js?6524:392)
at Object.onInvoke (core.es5.js?de3d:3890)
at ZoneDelegate.invoke (zone.js?6524:391)
at Zone.runGuarded (zone.js?6524:155)
at FileReader.eval (zone.js?6524:133)

I'm importing LZString this way:

import { LZString } from 'lz-string';

and the piece of code that is using LZString is this:

private compressAndChangeModel(file:File){
    let reader:FileReader = new FileReader();
    reader.onload = () => {
        let compressed:string=LZString.compress(reader.result);
        this.modelChange.next(compressed);
    };
    reader.onerror = (error) => {
        console.log('Error when trying to generate base64: ', error);
    };
    reader.readAsDataURL(file);
}

How is the correct way of import LZString in my webpack project?


问:
Angular2 - Unresolved Variables
Complete noob looking for help,
I've been learning Angular2 and attempting to make a basic app but now its broken!

The component.ts file

```<code>import {Component, OnInit} from '@angular/core';
import { Player } from './player.model';

@Component({
 selector : 'app-player',
 templateUrl : '/player.component.html'
})

export class PlayerComponent implements OnInit {

  players: Player[] = [
  new Player('Malus', 'Lina', 'lol', 3000)
];

  constructor() {}
 ngOnInit() {}

}
</code>```

model.ts

```<code>export class Player {
  public playerName: string;
  public favHero: string;
  public heroImage: string;
  public mmr: number;

  constructor( name: string, favHero: string, heroImage: string, mmr: number) {
    this.playerName = name;
    this.favHero = favHero;
    this.heroImage = heroImage;
    this.mmr =  mmr;
  }
}
</code>```

lastly where the error is in the HTML

I am trying to use {{ players.playerName }} etc but they are unresolved? I think this is why my app is broken now

apparently, the variables of my array are unresolved?. I don't get it and cant work out why.
Appreciate any help thanks

答:
You are trying to access an object key of an array (players.playerName), which you can't do. You either need to access a particular index players[0].playerName or loop through your players and create a DOM block for each player

```<code><div *ngFor="let player of players">
    {{player.playerName}}
</div>
</code>```

Title: Angular2 - Unresolved Variables

Body:
Complete noob looking for help,
I've been learning Angular2 and attempting to make a basic app but now its broken!

The component.ts file

import {Component, OnInit} from '@angular/core';
import { Player } from './player.model';

@Component({
 selector : 'app-player',
 templateUrl : '/player.component.html'
})

export class PlayerComponent implements OnInit {

  players: Player[] = [
  new Player('Malus', 'Lina', 'lol', 3000)
];

  constructor() {}
 ngOnInit() {}

}

model.ts

export class Player {
  public playerName: string;
  public favHero: string;
  public heroImage: string;
  public mmr: number;

  constructor( name: string, favHero: string, heroImage: string, mmr: number) {
    this.playerName = name;
    this.favHero = favHero;
    this.heroImage = heroImage;
    this.mmr =  mmr;
  }
}

lastly where the error is in the HTML

I am trying to use {{ players.playerName }} etc but they are unresolved? I think this is why my app is broken now

apparently, the variables of my array are unresolved?. I don't get it and cant work out why.
Appreciate any help thanks

Body:
You are trying to access an object key of an array (players.playerName), which you can't do. You either need to access a particular index players[0].playerName or loop through your players and create a DOM block for each player

<div *ngFor="let player of players">
    {{player.playerName}}
</div>


问:
Vuforia + Three.js
I'm facing an issue integrating three.js and Vuforia and I really don't know how to solve this cause I really don't know anything about OpenGl.

We are developing a small AR app and we would like to do that using Vuforia for tracking and recognition and three.js for rendering.

We placed a Vuforia view which render the camera and get the target info, on top of that we placed a WkWebView to render the augmentations using three.js.

We already set up a communication channel between the views and we send target position matrix and camera info from Vuforia to three.js.

What we are unable to do is to correctly make use of that information in three.js  and align models position to target position.

From Vuforia we grab modelViewMatrix, modelViewProjection.

Any help we'll be really appreciated!!!

答:
it seems that you can not do both things a the same time in a web browser (i.e. chrome), last year I tried several days what you say, using opencv + three.js.
In case of emergency for a client, you can use 2d sprite animations instead of 3d rendering</p>

Title: Vuforia + Three.js


问:
Append element to QueryList Angular
Is there a way to append a new element to a QueryList?

For example, i have a QueryList like this:

```<code>@ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>;
</code>```

And i need to append another SysColumn after the view init. Is it poossible on Angular? I try to append but it says that is not a function of a QueryList.

答:
You can use reset method

```<code>this.syscolumns.reset([...this.syscolumns.toArray(), this.additionalColumn])
</code>```

Stackblitz Example

Title: Append element to QueryList Angular

Body:
Is there a way to append a new element to a QueryList?

For example, i have a QueryList like this:

@ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>;

And i need to append another SysColumn after the view init. Is it poossible on Angular? I try to append but it says that is not a function of a QueryList.

Body:
You can use reset method

this.syscolumns.reset([...this.syscolumns.toArray(), this.additionalColumn])

Stackblitz Example


问:
Using room as singleton in kotlin
I'm trying to use Room as singleton so I didn't have to invoke Room.databaseBuilder() -which is expensive- more than once.

```<code>@Database(entities = arrayOf(
        Price::class,
        StationOrder::class,
        TicketPrice::class,
        Train::class,
        TrainCategory::class
), version = 2)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun dao(): TrainDao

companion object {
        fun createDatabase(context: Context): AppDatabase
                = Room.databaseBuilder(context, AppDatabase::class.java, "trains.db").build()
    }
}
</code>```

Note:

Can't use Object because Room requires using abstract class.

singleton must be thread safe because multiple threads might access it at the same time.

must be able to take Context as an argument.

I have looked at all similar StackOverflow questions and none of them satisfy my requirements

Singleton with argument in Kotlin isn't thread-safe

Kotlin - Best way to convert Singleton DatabaseController in Android isn't thread-safe

Kotlin thread save native lazy singleton with parameter uses object

答:
In this particular case I would resort to using Dagger 2, or some other dependency injection library like Koin or Toothpick. All three libraries allow to provide dependancies as singletons.

Here's the code for Dagger 2 module:

```<code>@Module
class AppModule constructor(private val context: Context) {
    @Provides
    @Singleton
    fun providesDatabase(): AppDatabase {
        return Room.databaseBuilder(
                context,
                AppDatabase::class.java,
                "train.db")
                .build()
    }
}
</code>```

AppComponent:

```<code>@Singleton
@Component(modules = arrayOf(
        AppModule::class
))
interface AppComponent {
    fun inject(viewModel: YourViewModel)
    fun inject(repository: YourRepository)
}
</code>```

Application class to provide injection:

```<code>class App : Application() {
    companion object {
        private lateinit var appComponent: AppComponent
        val component: AppComponent get() = appComponent
    }

    override fun onCreate() {
        super.onCreate()
        initializeDagger()
    }

    private fun initializeDagger() {
        component = DaggerAppComponent.builder()
                .appModule(AppModule(this))
                .build()
    }
}
</code>```

And then inject your database as singleton to wherever you need it (for example in your app's repository):

```<code>@Inject lateinit var appDatabase: AppDatabase

init {
    App.component.inject(this)
}
</code>```

Title: Using room as singleton in kotlin

Body:
I'm trying to use Room as singleton so I didn't have to invoke Room.databaseBuilder() -which is expensive- more than once.

@Database(entities = arrayOf(
        Price::class,
        StationOrder::class,
        TicketPrice::class,
        Train::class,
        TrainCategory::class
), version = 2)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun dao(): TrainDao

companion object {
        fun createDatabase(context: Context): AppDatabase
                = Room.databaseBuilder(context, AppDatabase::class.java, "trains.db").build()
    }
}

Note:

Can't use Object because Room requires using abstract class.

singleton must be thread safe because multiple threads might access it at the same time.

must be able to take Context as an argument.

I have looked at all similar StackOverflow questions and none of them satisfy my requirements

Singleton with argument in Kotlin isn't thread-safe

Kotlin - Best way to convert Singleton DatabaseController in Android isn't thread-safe

Kotlin thread save native lazy singleton with parameter uses object

Body:
In this particular case I would resort to using Dagger 2, or some other dependency injection library like Koin or Toothpick. All three libraries allow to provide dependancies as singletons.

Here's the code for Dagger 2 module:

@Module
class AppModule constructor(private val context: Context) {
    @Provides
    @Singleton
    fun providesDatabase(): AppDatabase {
        return Room.databaseBuilder(
                context,
                AppDatabase::class.java,
                "train.db")
                .build()
    }
}

AppComponent:

@Singleton
@Component(modules = arrayOf(
        AppModule::class
))
interface AppComponent {
    fun inject(viewModel: YourViewModel)
    fun inject(repository: YourRepository)
}

Application class to provide injection:

class App : Application() {
    companion object {
        private lateinit var appComponent: AppComponent
        val component: AppComponent get() = appComponent
    }

    override fun onCreate() {
        super.onCreate()
        initializeDagger()
    }

    private fun initializeDagger() {
        component = DaggerAppComponent.builder()
                .appModule(AppModule(this))
                .build()
    }
}

And then inject your database as singleton to wherever you need it (for example in your app's repository):

@Inject lateinit var appDatabase: AppDatabase

init {
    App.component.inject(this)
}


问:
ssh: connect to host git.ionicjs.com port 22: Connection timed out
I'm working on an Ionic application, I started by creating a new project via Ionic Dashboard. Later I connected my apllication using this command : ionic start --pro-id my-id.

But when I try to push my code up to the dashboard using the following command : git push ionic master I Recieved this error :

```<code>ssh: connect to host git.ionicjs.com port 22: Connection timed out
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I tried to use http protocol instead of ssh in the config file, following th steps below :

git config --local -e

url = git@git.ionicjs.com/usename/myproject.git

url = https://git.ionicjs.com/usename/myproject.git

But stil have this issue : fatal: unable to access 'https://git.ionicjs.com:username/myproject.git/': Port number ended with 'b'

Any idea to resolve this problem? Thank you.

答:
The problem with ssh is that git.ionicjs.com has 2 different IP addresses. One of them (35.162.243.99) has port 22 open and the other (35.162.243.97) doesn't. I recommend to report the problem to ionicjs.com.

The correct syntax for HTTP URL is https://git.ionicjs.com/username/myproject.git, not https://git.ionicjs.com:username/myproject.git/.

Body:
I'm working on an Ionic application, I started by creating a new project via Ionic Dashboard. Later I connected my apllication using this command : ionic start --pro-id my-id.

But when I try to push my code up to the dashboard using the following command : git push ionic master I Recieved this error :

ssh: connect to host git.ionicjs.com port 22: Connection timed out
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I tried to use http protocol instead of ssh in the config file, following th steps below :

git config --local -e

url = git@git.ionicjs.com/usename/myproject.git

url = https://git.ionicjs.com/usename/myproject.git

But stil have this issue : fatal: unable to access 'https://git.ionicjs.com:username/myproject.git/': Port number ended with 'b'

Any idea to resolve this problem? Thank you.


问:
Post request in VueJs with undefined response
I am a beginner in VueJs and Expressjs. I am trying to make frontend side by Vuejs and backend by ExpressJs. I send a post request to the backend (expressJs) and :

1- Response is undefined
2- At the same time I can see 2 requests in chrome development tools. One is Option and another one is Post.
3- With postman there is no problem at all.

Here is the code of app.js in express

console.log('Server is running')

const express = require('express'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    morgan = require('morgan');

app = new express();

//Setup middleware
app.use(cors());
app.use(morgan('combined'))
app.use(bodyParser.json())

app.post('/register', (req, res, next) => {
    res.send({
        message: `Hello ${req.body.email}! your user was registered!`
    })
});

app.listen(8081);```
</div>
</div>
</p>

<p>And here is the code in VueJs :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Api Setting

import axios from 'axios'

export const HTTP = axios.create({
    baseURL: `http://localhost:8081`
  });

// AuthenticationService

import { HTTP } from '../services/Api'

export default {

  register(credentials) {
     HTTP.post('register', credentials);
  }
}

// Register Component
export default {
  data() {
    return {
      email: '',
      password: ''
    };
  },
  methods: {

   async register() {
        const response = await AuthenticationService.register({
        email: this.email,
        password: this.password
      });

      console.log(response);  // the value is undefined
    }
  }
};</code>```

I really don't know what I missed here that I get an undefined response and 2 requests at the same time. I appreciate any hint.

Whole code on github repo  : here

答:
I use JSON.stringify to send the data, you are sending the objects directly, so

```<code>register(credentials) {
    HTTP.post('register', credentials);
}
</code>```

becomes

```<code>register(credentials) {
    HTTP.post('register', JSON.stringify(credentials));
}
</code>```

Body:
I am a beginner in VueJs and Expressjs. I am trying to make frontend side by Vuejs and backend by ExpressJs. I send a post request to the backend (expressJs) and :

1- Response is undefined
2- At the same time I can see 2 requests in chrome development tools. One is Option and another one is Post.
3- With postman there is no problem at all.

Here is the code of app.js in express

console.log('Server is running')

const express = require('express'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    morgan = require('morgan');

app = new express();

//Setup middleware
app.use(cors());
app.use(morgan('combined'))
app.use(bodyParser.json())

app.post('/register', (req, res, next) => {
    res.send({
        message: `Hello ${req.body.email}! your user was registered!`
    })
});

app.listen(8081);

And here is the code in VueJs :

// Api Setting

import axios from 'axios'

export const HTTP = axios.create({
    baseURL: `http://localhost:8081`
  });

// AuthenticationService

import { HTTP } from '../services/Api'

export default {

  register(credentials) {
     HTTP.post('register', credentials);
  }
}

// Register Component
export default {
  data() {
    return {
      email: '',
      password: ''
    };
  },
  methods: {

   async register() {
        const response = await AuthenticationService.register({
        email: this.email,
        password: this.password
      });

      console.log(response);  // the value is undefined
    }
  }
};

I really don't know what I missed here that I get an undefined response and 2 requests at the same time. I appreciate any hint.

Whole code on github repo  : here

Body:
I use JSON.stringify to send the data, you are sending the objects directly, so

register(credentials) {
    HTTP.post('register', credentials);
}

becomes

register(credentials) {
    HTTP.post('register', JSON.stringify(credentials));
}


问:
Launching composed task built by DSL from stream application
Every example I've seen (task-launcher sink and triggertask source ) shows how to launch  the task defined by uri attribute.
My tasks definitions look like this :

```<code>sampleTask  <t2: timestamp || t1: timestamp>
sampleTask-t1   timestamp
sampleTask-t2   timestamp
sampleTaskRunner    composed-task-runner --graph=sampleTask
</code>```

My question is how do I launch the composed task runner (sampleTaskRunner, defined by DSL) from stream application.

Thanks

UPDATE

I ended up with the below solution that triggers task using SCDF REST API :

composedTask definition :

<timestamp || mySampleTask>

Stream definition :

http | httpclient | log

Deployment  properties :

```<code>app.http.port=81
app.httpclient.body=name=composedTask&arguments=--increment-instance-enabled=true
app.httpclient.http-method=POST
app.httpclient.url=http://localhost:9393/tasks/executions
app.httpclient.headers-expression={'Content-Type':'application/x-www-form-urlencoded'}
</code>```

Though it's easy to implement http sink component, would  be great if stream application starters will provide one out of the box.

Another concern I have is about discovering the SCDF REST URL when deployed in distributed environment.

答:
Here's a quick take from one of the SCDF's R&D team members (Glenn Renfro).

stream create foozer --definition "trigger --fixed-delay=5 | tasklaunchrequest-transform --uri=maven://org.springframework.cloud.task.app:composedtaskrunner-task:1.1.0.BUILD-SNAPSHOT --command-line-arguments='--graph=sampleTask-t1||sampleTask-t2 --increment-instance-enabled=true --spring.datasource.url=jdbc:mariadb://localhost:3306/test --spring.datasource.username=root --spring.datasource.password=password --spring.datasource.driverClassName=org.mariadb.jdbc.Driver' | task-launcher-local" --deploy

In the foozer stream definition,

1) "trigger" source happens to trigger an upstream event every 5s

2) "tasklaunchrequest-transform" processor takes a few arguments; more specifically, it uses "composedtaskrunner-task:1.1.0.BUILD-SNAPSHOT" to launch a composed-task graph (i.e., sampleTask-t1||sampleTask-t2)

3) Pay attention to --increment-instance-enabled. This was recently added to CTR application and this provides the ability to re-launch a composed-task in a recurring cadence

4) Since the CTR and SCDF must share the same database, we are also passing datasource properties as command-line args. (SCDF-server is already started with the same datasource credentials)

Hope this helps.

Lastly, we will add a sample to the reference guide via: spring-cloud/spring-cloud-dataflow#1780

Body:
Every example I've seen (task-launcher sink and triggertask source ) shows how to launch  the task defined by uri attribute.
My tasks definitions look like this :

sampleTask  <t2: timestamp || t1: timestamp>
sampleTask-t1   timestamp
sampleTask-t2   timestamp
sampleTaskRunner    composed-task-runner --graph=sampleTask

My question is how do I launch the composed task runner (sampleTaskRunner, defined by DSL) from stream application.

Thanks

UPDATE

I ended up with the below solution that triggers task using SCDF REST API :

composedTask definition :

<timestamp || mySampleTask>

Stream definition :

http | httpclient | log

Deployment  properties :

app.http.port=81
app.httpclient.body=name=composedTask&arguments=--increment-instance-enabled=true
app.httpclient.http-method=POST
app.httpclient.url=http://localhost:9393/tasks/executions
app.httpclient.headers-expression={'Content-Type':'application/x-www-form-urlencoded'}

Though it's easy to implement http sink component, would  be great if stream application starters will provide one out of the box.

Another concern I have is about discovering the SCDF REST URL when deployed in distributed environment.


问:
File size in python3 for mac os x not matching command line result
I'm trying to get the size of a file just downloaded by using urllib in python3. I tried to get the filesize with len(response.read()) and the value got was 653856. However when this done I found after checking that the size of the file saved was 0 (did the response.read() consume the data maybe?) so I discarded this option and switched to ckeck the size with os:

```<code>if strFecha in dicc or fecha.year < 2010:
    # Download the file from `url` and save it locally under `nomFichero`:
    with urllib.request.urlopen(url) as response, open(nomFichero, 'wb') as outFile:
        # Following one returns 653856
        size1 = len(response.read())
        shutil.copyfileobj(response, outFile)
        # Following two lines return 524288
        size2 = os.path.getsize(nomFichero)
        size2 = os.stat(nomFichero).st_size
</code>```

I got the same result for both of them (524288), but after doing an 'ls -l' on the command line I got 653856, and I don't know why this value did not match the one got from python.

Can anyone tell me which value is the good one and how to get it with python3?

答:
I would suspect this has to do with block sizing & empty blocks.

If you have say a 2,324,020 byte file there will be two values, size on disk (how much room is being used to store it because of the file system's minimum allowed space usage)

and actual file size OR Logical File Size (2,324,020  byte). for instance on Windows 7, I have a 2,324,020 byte file; it's size on disk is 2,326,528 bytes.

Python's OS commands

```<code>os.path.getsize #Returns real size of file in bytes
</code>```

and

```<code>os.stat #Returns real size of file in bytes
</code>```

Will return the exact size of the file in bytes.

Something like this:

```<code>lSize=os.stat(filename).st_size
bSize=os.statvfs(filename).f_bsize
sizeOnDisk=(lSize/bSize+1)*bSize
</code>```

will return the size on disk but is not supported on Windows at this time.

EDIT

This post says LS does NOT show disk usage size, rather logical size, however notes that  "empty blocks" may alter the file size.

The output of the ls command displays only the size of a file and does
not include indirect blocks used by the file. Any empty blocks of the
file also get included in the output of the command.

It is worth noting if you are looking for Logical File Size, Python stat would be ideal.

Body:
I'm trying to get the size of a file just downloaded by using urllib in python3. I tried to get the filesize with len(response.read()) and the value got was 653856. However when this done I found after checking that the size of the file saved was 0 (did the response.read() consume the data maybe?) so I discarded this option and switched to ckeck the size with os:

if strFecha in dicc or fecha.year < 2010:
    # Download the file from `url` and save it locally under `nomFichero`:
    with urllib.request.urlopen(url) as response, open(nomFichero, 'wb') as outFile:
        # Following one returns 653856
        size1 = len(response.read())
        shutil.copyfileobj(response, outFile)
        # Following two lines return 524288
        size2 = os.path.getsize(nomFichero)
        size2 = os.stat(nomFichero).st_size

I got the same result for both of them (524288), but after doing an 'ls -l' on the command line I got 653856, and I don't know why this value did not match the one got from python.

Can anyone tell me which value is the good one and how to get it with python3?

Body:
I would suspect this has to do with block sizing & empty blocks.

If you have say a 2,324,020 byte file there will be two values, size on disk (how much room is being used to store it because of the file system's minimum allowed space usage)

and actual file size OR Logical File Size (2,324,020  byte). for instance on Windows 7, I have a 2,324,020 byte file; it's size on disk is 2,326,528 bytes.

Python's OS commands

os.path.getsize #Returns real size of file in bytes

and

os.stat #Returns real size of file in bytes

Will return the exact size of the file in bytes.

Something like this:

lSize=os.stat(filename).st_size
bSize=os.statvfs(filename).f_bsize
sizeOnDisk=(lSize/bSize+1)*bSize

will return the size on disk but is not supported on Windows at this time.

EDIT

This post says LS does NOT show disk usage size, rather logical size, however notes that  "empty blocks" may alter the file size.

The output of the ls command displays only the size of a file and does
not include indirect blocks used by the file. Any empty blocks of the
file also get included in the output of the command.

It is worth noting if you are looking for Logical File Size, Python stat would be ideal.


问:
Highchart and "almost regular" time interval data
For a Highchart line chart using datetime on the X Axis, how can the chart be initially rendered using data with one pointInterval, and dynamically updated using another?

For my case, the initially rendering will utilize exactly 200 samples regardless of the time duration.  For instance, say a given chart's duration is 1 week.  The initial page will receive 200 data points which are 3,024 seconds apart (7*24*60*60/200).  Then, it will be dynamically updated via Ajax every 60 seconds.

I've tried multiple approaches, however, either the Ajax 60 second ticks produce the same change as the initial page 3,024 second ticks or the initially created chart scale is changed or some equally other undesired result.  The chart should primarily remain the same but slowly update with the newly received Ajax data.

The following at https://jsbin.com/zuboyeh/edit?html,output shows several of those attempts.

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highcharts</title>

        <button id="addPoint">addPoint</button>
        <button id="updateSeries">updateSeries</button>
        <button id="changePointInterval">changePointInterval</button>

```

答:
Each series can have only one pointInterval defined.

There're 2 easiest solutions for this problem on the top of my head:

1. Add another linked series for new values
linkedTo:previous will cause that legend switch will work for both series. Change the colour of the second series so that it looks exactly the same as the first one. Set pointStart using the last value from the base series:

```<code>  events: {
    load: function() {
      var points = this.series[0].points,
        lastPoint = points[points.length - 1];

      this.series[1].update({
        pointStart: lastPoint.x,
        color: this.series[0].color
      });
    }
  }

(...)

series: [{
  name: 'SeriesName',
  data: data1
}, {
  name: 'SeriesName', // same name as the previous series
  pointInterval: secondsIntervalAjax * 10000, // 10 times bigger to see results faster
  linkedTo: ':previous',
  marker: {
    enabled: false
  }
}]
</code>```

Live demo: http://jsfiddle.net/kkulig/gtsw8t3q/

2. Compute and explicitly assign x value to every point

No pointInterval and pointStart required in this case.

Body:
Each series can have only one pointInterval defined.

There're 2 easiest solutions for this problem on the top of my head:

1. Add another linked series for new values
linkedTo:previous will cause that legend switch will work for both series. Change the colour of the second series so that it looks exactly the same as the first one. Set pointStart using the last value from the base series:

  events: {
    load: function() {
      var points = this.series[0].points,
        lastPoint = points[points.length - 1];

      this.series[1].update({
        pointStart: lastPoint.x,
        color: this.series[0].color
      });
    }
  }

(...)

series: [{
  name: 'SeriesName',
  data: data1
}, {
  name: 'SeriesName', // same name as the previous series
  pointInterval: secondsIntervalAjax * 10000, // 10 times bigger to see results faster
  linkedTo: ':previous',
  marker: {
    enabled: false
  }
}]

Live demo: http://jsfiddle.net/kkulig/gtsw8t3q/

2. Compute and explicitly assign x value to every point

No pointInterval and pointStart required in this case.


问:
MSVC does not respect constexpr if within lambdas
An example of what I'm referring to:

```<code>#include <type_traits>

void voidFunction() {}

template <typename Function>
void lambdaTest(Function func) {
    [func]() -> void {
        int someInt;
        if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
            someInt = std::invoke(func);
        } else {
            std::invoke(func);
        }
    };
}

int main(int argc, char** argv) {
    lambdaTest(&voidFunction);
    return 0;
}
</code>```

This compiles in gcc 7.2. However, with MSVC 19.11.25547 I get this error:

error C2440: '=': cannot convert from 'void' to 'int'

This code compiles fine with both compilers:

```<code>#include <type_traits>

void voidFunction() {}

template <typename Function>
void nonLambdaTest(Function func) {
    int someInt;
    if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
        someInt = std::invoke(func);
    } else {
        std::invoke(func);
    }
}

int main(int argc, char** argv) {
    nonLambdaTest(&voidFunction);
    return 0;
}
</code>```

To me it looks like MSVC just ignores the constexpr if. Is this a bug in MSVC, or are constexpr if officially forbidden in lambdas?

答:
I've simplified this example a bit (or at least made it more obvious):</p>

```<code>#include <type_traits>
#include <utility>

template<typename TPointerToFunction>
void lambdaTest(TPointerToFunction)
{
    []() -> void // comment this line to make it work
    {
        constexpr const bool returns_int
        {
            std::is_same_v
            <
                int
            ,   decltype(::std::declval<TPointerToFunction>()())
            >
        };
        static_assert(!returns_int);
        if constexpr(returns_int)
        {
            static_assert(returns_int, "how did we get here?");
        }
    };
}

void voidFunction(void) {}

int
main()
{
    lambdaTest(&voidFunction);
    return(0);
}
</code>```

Body:
An example of what I'm referring to:

#include <type_traits>

void voidFunction() {}

template <typename Function>
void lambdaTest(Function func) {
    [func]() -> void {
        int someInt;
        if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
            someInt = std::invoke(func);
        } else {
            std::invoke(func);
        }
    };
}

int main(int argc, char** argv) {
    lambdaTest(&voidFunction);
    return 0;
}

This compiles in gcc 7.2. However, with MSVC 19.11.25547 I get this error:

error C2440: '=': cannot convert from 'void' to 'int'

This code compiles fine with both compilers:

#include <type_traits>

void voidFunction() {}

template <typename Function>
void nonLambdaTest(Function func) {
    int someInt;
    if constexpr (std::is_same_v<std::invoke_result_t<Function>, int>) {
        someInt = std::invoke(func);
    } else {
        std::invoke(func);
    }
}

int main(int argc, char** argv) {
    nonLambdaTest(&voidFunction);
    return 0;
}

To me it looks like MSVC just ignores the constexpr if. Is this a bug in MSVC, or are constexpr if officially forbidden in lambdas?

Body:
I've simplified this example a bit (or at least made it more obvious):

#include <type_traits>
#include <utility>

template<typename TPointerToFunction>
void lambdaTest(TPointerToFunction)
{
    []() -> void // comment this line to make it work
    {
        constexpr const bool returns_int
        {
            std::is_same_v
            <
                int
            ,   decltype(::std::declval<TPointerToFunction>()())
            >
        };
        static_assert(!returns_int);
        if constexpr(returns_int)
        {
            static_assert(returns_int, "how did we get here?");
        }
    };
}

void voidFunction(void) {}

int
main()
{
    lambdaTest(&voidFunction);
    return(0);
}


问:
Add new objects after using "new"
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

```<code>int *a;
a = new int;
a = new int;
</code>```

Thank you very much!

答:
It sounds like you are trying to write your own vector class that can grow on demand. You can do this as follows:

```<code>int * a; // original pointer
a = new int[5]; // just five elements
</code>```

Now to grow it to 10 elements (make a new array, copy the old contents, reclaim the old array's memory, and reassign the array pointer):

```<code>int * tmp = new int[10]; // a new array
memcpy (tmp, a, 5 * sizeof(int)); // copy the old items into the new array
delete [] a; // reclaim the memory from the old array
a = tmp; // reassign a to point to the new, bigger array
</code>```

See Cormen, Leiserson, Rivest and Stein, Chapter 17.4, for description and analysis of such a "dynamic table."

Title: Add new objects after using "new"

Body:
after I call new, how can I add more objects to the pointer? (I need it for a class)
this is what I mean:

int *a;
a = new int;
a = new int;

Thank you very much!

Body:
It sounds like you are trying to write your own vector class that can grow on demand. You can do this as follows:

int * a; // original pointer
a = new int[5]; // just five elements

Now to grow it to 10 elements (make a new array, copy the old contents, reclaim the old array's memory, and reassign the array pointer):

int * tmp = new int[10]; // a new array
memcpy (tmp, a, 5 * sizeof(int)); // copy the old items into the new array
delete [] a; // reclaim the memory from the old array
a = tmp; // reassign a to point to the new, bigger array

See Cormen, Leiserson, Rivest and Stein, Chapter 17.4, for description and analysis of such a "dynamic table."


问:
Application terminates on start when including <boost/thread>
In the simple code below, if I include the boost threading library, the program is terminated on execution, the main function is not even reached.

Everything compiles properly with 0 warning, 0 error.

My environment:

Eclipse Kepler

boost_1_65_1

gcc 6.3.0

Mingw (Don't know version, I have the current release on sourceforge)

In Project/C/C++ Build/Settings

GCC C++ Compiler/Includes: c\boost\boost_1_65_1

MinGW C++ Linker/Libraries:

Library search path: C:\boost\boost_1_65_1\stage\lib

Libraries: llibboost_thread-mgw63-mt-1_65_1 , libboost_system-mgw63-mt-1_65_1 , libboost_chrono-mgw63-1_65_1

Code:

```<code>#include <iostream>
#include <boost/thread/thread.hpp>
int main(int argc, char* argv[])
{
std::cout << "StackUnderFlow" << std::endl;
return 0;
}
</code>```

I have no idea what is the source of the issue, is it:

the way I built Boost/Thread

how the project is configured

?

The gdb traces shows this error:

```<code>058,965 25^error,msg="During startup program exited with code 0xc0000135."
058,965 (gdb)
058,965 26^error,msg="Can not fetch data now."
058,965 (gdb)
058,980 27-gdb-exit
058,980 28-data-evaluate-expression $_exitcode
058,996 27^exit
</code>```

答: The code needs to be both compiled and linked with -pthread option. -lpthread linker option is insufficient and unnecessary.

Body:
In the simple code below, if I include the boost threading library, the program is terminated on execution, the main function is not even reached.

Everything compiles properly with 0 warning, 0 error.

My environment:

Eclipse Kepler

boost_1_65_1

gcc 6.3.0

Mingw (Don't know version, I have the current release on sourceforge)

In Project/C/C++ Build/Settings

GCC C++ Compiler/Includes: c\boost\boost_1_65_1

MinGW C++ Linker/Libraries:

Library search path: C:\boost\boost_1_65_1\stage\lib

Libraries: llibboost_thread-mgw63-mt-1_65_1 , libboost_system-mgw63-mt-1_65_1 , libboost_chrono-mgw63-1_65_1

Code:

#include <iostream>
#include <boost/thread/thread.hpp>
int main(int argc, char* argv[])
{
std::cout << "StackUnderFlow" << std::endl;
return 0;
}

I have no idea what is the source of the issue, is it:

the way I built Boost/Thread

how the project is configured

?

The gdb traces shows this error:

058,965 25^error,msg="During startup program exited with code 0xc0000135."
058,965 (gdb)
058,965 26^error,msg="Can not fetch data now."
058,965 (gdb)
058,980 27-gdb-exit
058,980 28-data-evaluate-expression $_exitcode
058,996 27^exit


问:
Login Page in ASP.NET application with FormsAuthentication access denied
I've got a webapp running that needs users to login.
Webconfig:

```<code>    <!--Logging in stuff-->
    <authentication mode="Forms">
        <forms loginUrl="login.aspx" timeout="2880"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

And in the login.aspx page (doubled checked the name) I have the following logic after verifying the user credentials using my own database:

```<code>    if (checkCredentials.searchCredentials(attemptedName, passwordBox.Text) != null)
            {
                FormsAuthentication.RedirectFromLoginPage(attemptedName,false);
            }
</code>```

I know the if statement works, as it did with a previous method I used for logging in.

However, when I run the application, the login page opens up immediately with error 401.2. Help would be much appreciated :)

答:
Since you are using Visual Studio 2017, the first thing you need to check is if Microsoft.AspNet.FriendlyUrls package is included. Go through following steps.

comment the line in Global.asax that says
RouteConfig.RegisterRoutes(RouteTable.Routes); and try your page now. But, make sure to clear the cache in your browser else the old cached version of this URL with 401.2 error will keep showing.

If you still see some issues, then just remove the above package by
selecting Solution node in solution explorer and then going to Tools
=> NuGet Package Manager => Manage Packages for solution; check in Installed list for this package, select it and select the solution
checkboxes on right,then click on uninstall button.

Below are some other things that you need to make sure.

Try changing your forms tag in web config to following. Change the value of defaultUrl and timeout according to your requirements.

```<code><authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="home.aspx"
   slidingExpiration="true" timeout="20" name=".Auth" protection="All">
</forms>
</authentication>
<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>
</code>```

Also, your C# code must be in Login button click event; if it's anywhere else then also you could see issues.

Allow Login.aspx for all unauthenticated users. Add this configuration just before </configuration> at end of web config file. Enter the path for Login.aspx if its not in root like Security/login.aaspx if the page is under Security folder of root.

```<code> <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="?" />
        <deny users="*" />
      </authorization>
    </system.web>
 </location>
</code>```

Open the IIS Management console by going to Control Panel > Administrative Tools > Internet Information Services Manager. Then, expand the websites node and select the website you are using. Now double click Authentication in right pane and make sure Anonymous and Forms authentication are enabled and other options are disabled as shown in following screenshot: Security settings in IIS website

Body:
I've got a webapp running that needs users to login.
Webconfig:

    <authentication mode="Forms">
        <forms loginUrl="login.aspx" timeout="2880"/>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>

And in the login.aspx page (doubled checked the name) I have the following logic after verifying the user credentials using my own database:

    if (checkCredentials.searchCredentials(attemptedName, passwordBox.Text) != null)
            {
                FormsAuthentication.RedirectFromLoginPage(attemptedName,false);
            }

I know the if statement works, as it did with a previous method I used for logging in.

However, when I run the application, the login page opens up immediately with error 401.2. Help would be much appreciated :)

Body:
Since you are using Visual Studio 2017, the first thing you need to check is if Microsoft.AspNet.FriendlyUrls package is included. Go through following steps.

comment the line in Global.asax that says
RouteConfig.RegisterRoutes(RouteTable.Routes); and try your page now. But, make sure to clear the cache in your browser else the old cached version of this URL with 401.2 error will keep showing.

If you still see some issues, then just remove the above package by
selecting Solution node in solution explorer and then going to Tools
=> NuGet Package Manager => Manage Packages for solution; check in Installed list for this package, select it and select the solution
checkboxes on right,then click on uninstall button.

Below are some other things that you need to make sure.

Try changing your forms tag in web config to following. Change the value of defaultUrl and timeout according to your requirements.

<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="home.aspx"
   slidingExpiration="true" timeout="20" name=".Auth" protection="All">
</forms>
</authentication>
<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>

Also, your C# code must be in Login button click event; if it's anywhere else then also you could see issues.

Allow Login.aspx for all unauthenticated users. Add this configuration just before </configuration> at end of web config file. Enter the path for Login.aspx if its not in root like Security/login.aaspx if the page is under Security folder of root.

 <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="?" />
        <deny users="*" />
      </authorization>
    </system.web>
 </location>

Open the IIS Management console by going to Control Panel > Administrative Tools > Internet Information Services Manager. Then, expand the websites node and select the website you are using. Now double click Authentication in right pane and make sure Anonymous and Forms authentication are enabled and other options are disabled as shown in following screenshot: Security settings in IIS website


问:
NSManagedObject Validation and Subclasses
How to implement custom property validation methods for NSManagedObject subclasses in Xcode 8.0 or above? How we can create an NSManagedObject subclasses in Xcode 8.0?

Before Xcode 8.0

Xcode -> File -> New -> File -> Core Data -> NSManagedObject Subclass

答:
For Xcode 8 or higher, NSManagedObject subclasses are created automatically unless you tell Xcode to not do that. With Swift you can let Xcode create a subclass, or create your own subclass and let Xcode add an extension with attribute declarations, or tell Xcode to not automatically generate anything. It's not about Swift 3.0 or 4.0, it's about Xcode.

You choose one of these in the model editor. "Class Definition" is the default.

Validation methods work the same as they ever did. You implement them in a managed object subclass. You can also implement them in an extension on that class.


问:
Django Modelform OneToOneFielld
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model.

Model Code:

```<code>class MyModel(models.Model):
    user = models.OneToOneField(User,related_name="profile",primary_key=True)
    custom_field = models.CharField(...)
</code>```

The model is more elaborate of course, but it shows the setup of the whole thing.

Example form:

```<code>First name: [input]
Last name: [input]
Email: [input]
Password: [pass_input]
Custom Text: [text_input]
</code>```

Is this at all possible using a ModelForm?

答:
Yes. In your forms.py file, add this code:

```<code>class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('customfield1', 'customfield2')
</code>```

EDIT
Here is a great tutorial on to do this: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Title: Django Modelform OneToOneFielld

Body:
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model.

Model Code:

class MyModel(models.Model):
    user = models.OneToOneField(User,related_name="profile",primary_key=True)
    custom_field = models.CharField(...)

The model is more elaborate of course, but it shows the setup of the whole thing.

Example form:

First name: [input]
Last name: [input]
Email: [input]
Password: [pass_input]
Custom Text: [text_input]

Is this at all possible using a ModelForm?

Body:
Yes. In your forms.py file, add this code:

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')

class ProfileForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('customfield1', 'customfield2')

EDIT
Here is a great tutorial on to do this: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html


问:
Getting list of linked libraries form cocoa code
On my application starting I need to get list of libraries that are linked to it.
Unfortunately, I could't find any example in cocoa how can I do it from code. Can anybody help me with this?</p>

答:
So, there's probably a better way than this (and this is completely untested written-into-this-text-field code), but I think this would do the trick:

```<code>uint32_t imageCount = _dyld_image_count();
char **names = calloc(sizeof(char *), imageCount);
int32_t *versions = calloc(sizeof(int32_t), imageCount);
for (uint32_t idx = 0; idx < imageCount; idx++) {
    names[idx] = _dyld_get_image_name(idx);
    versions[idx] = NSVersionOfLinkTimeLibrary(names[idx]);
}
</code>```

If I'm understanding dyld.h properly, this should get you a list of all the currently loaded mach-o images and their link-time versions. Any mach-o image with a link-time version of -1 wasn't linked against from the main executable.

Body:
So, there's probably a better way than this (and this is completely untested written-into-this-text-field code), but I think this would do the trick:

uint32_t imageCount = _dyld_image_count();
char **names = calloc(sizeof(char *), imageCount);
int32_t *versions = calloc(sizeof(int32_t), imageCount);
for (uint32_t idx = 0; idx < imageCount; idx++) {
    names[idx] = _dyld_get_image_name(idx);
    versions[idx] = NSVersionOfLinkTimeLibrary(names[idx]);
}

If I'm understanding dyld.h properly, this should get you a list of all the currently loaded mach-o images and their link-time versions. Any mach-o image with a link-time version of -1 wasn't linked against from the main executable.


问:
Removing stand-alone numbers from string in Python
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

```<code>   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89
</code>```

However, I want to achieve the effect:

```<code>   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA
</code>```

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

答:
We could create a function that tries to convert to float. If it fails we return True (not_float)

```<code>import pandas as pd

df = pd.DataFrame({"col_1" : ["BULKA TARTA 500G KAJO 1",
                              "CUKIER KRYSZTAL 1KG KSC 4",
                              "KASZA JĘCZMIENNA 4*100G 2 0.92",
                              "LEWIATAN MAKARON WSTĄŻKA 1 0.89"]})

def is_not_float(string):
    try:
        float(string)
        return False
    except ValueError:  # String is not a number
        return True

df["col_1"] = df["col_1"].apply(lambda x: [i for i in x.split(" ") if is_not_float(i)])

df
</code>```

Or following the example of my fellow SO:ers. However this would treat 130. as a number.

```<code>df["col_1"] = (df["col_1"].apply(
    lambda x: [i for i in x.split(" ") if not i.replace(".","").isnumeric()]))
</code>```

Returns

```<code>                          col_1
0    [BULKA, TARTA, 500G, KAJO]
1  [CUKIER, KRYSZTAL, 1KG, KSC]
2   [KASZA, JĘCZMIENNA, 4*100G]
3  [LEWIATAN, MAKARON, WSTĄŻKA]
</code>```

Body:
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89

However, I want to achieve the effect:

   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

Body:
We could create a function that tries to convert to float. If it fails we return True (not_float)

import pandas as pd

df = pd.DataFrame({"col_1" : ["BULKA TARTA 500G KAJO 1",
                              "CUKIER KRYSZTAL 1KG KSC 4",
                              "KASZA JĘCZMIENNA 4*100G 2 0.92",
                              "LEWIATAN MAKARON WSTĄŻKA 1 0.89"]})

def is_not_float(string):
    try:
        float(string)
        return False
    except ValueError:  # String is not a number
        return True

df["col_1"] = df["col_1"].apply(lambda x: [i for i in x.split(" ") if is_not_float(i)])

df

Or following the example of my fellow SO:ers. However this would treat 130. as a number.

df["col_1"] = (df["col_1"].apply(
    lambda x: [i for i in x.split(" ") if not i.replace(".","").isnumeric()]))

Returns

                          col_1
0    [BULKA, TARTA, 500G, KAJO]
1  [CUKIER, KRYSZTAL, 1KG, KSC]
2   [KASZA, JĘCZMIENNA, 4*100G]
3  [LEWIATAN, MAKARON, WSTĄŻKA]


问:
How to extract response data in Gatling
I'm new with gatling and I have problem that I can't resolve by myself. I have to send request and after that I have to catch data from response. I can send request using get method, but I don't have idea how to extract data from response. Do you have any ideas how to do this? Thanks for your help.</p>

答:
I did this using check clause

```<code>          http("Poll")
                .get(Configuration.URL )
                .queryParam("applicationId", Configuration.APPLICATION_ID)
                .check(status.is(200))
                .check(status.saveAs("statusCode"))
                .check(xpath("//myRunTimeInfo").saveAs("runtimeInfoStatus"))
                .check(xpath("//status").saveAs("responseStatus")))
              .pause(Configuration.THINK_TIME second)
</code>```

xpath : will do a search in your response using xpath specifications

Title: How to extract response data in Gatling

Body:
I did this using check clause

          http("Poll")
                .get(Configuration.URL )
                .queryParam("applicationId", Configuration.APPLICATION_ID)
                .check(status.is(200))
                .check(status.saveAs("statusCode"))
                .check(xpath("//myRunTimeInfo").saveAs("runtimeInfoStatus"))
                .check(xpath("//status").saveAs("responseStatus")))
              .pause(Configuration.THINK_TIME second)

xpath : will do a search in your response using xpath specifications