问:
Functions defined inside functions spawned as processes in Erlang
How does a function(A) defined inside another function(B) in which function(B) is a registered process, access the mailbox of function(B)?

Can i define multiple functions in function(B), the function in which the registered process is defined, which can have receive clauses that will access messages sent to function(B) by other processes?

答:
In the second paragraph you have answered the first one. The way you get messages (if A and B are in the same process) it's by the receive clause. As long as they are in the same process, they will access the same mailbox.

In function(B) you can certainly have any number of function calls with  any number of receive clauses. Now, if you want them to have the same mailbox, they are to be in the same process and therefore they will be executed in sequence. Also note that the ´receive` clause suspends the execution until something it's received (or the timeout it's reached, if defined).

So in this hypothetical scenario, these many functions will  be executed one after another and each one will block the whole process until something it's received (or the timeout it's reached, if defined). Then continue.


来源: stackexchange

问:
How to hide views for always
Can somebody tell me how to hide views for always?

I'm hiding a view with view.setVisibility(view.GONE); but when reopen the app I have to re-hide the view. I want a view hide for always when button is clicked until clearing app data or uninstalling. Thanks!

答: You need to save state by creating flag for hide and unhide view in SharedPreference and basis of that flag you need to GONE or VISIBLE View.

ContentLicense: CC BY-SA 3.0

Title: How to hide views for always


问:
VBA chart updating returning "object support" error
Hey I'm trying to update this chart via macro from monthly pulled data but keep running into issues after it had worked once. Syntax error?

```<code>With Sheets("data").ChartObjects("Chart 3")
    .SeriesCollection(1).XValues = ActiveSheet.Range(Range("b55"), Range("b55").End(xlDown))
    .SeriesCollection(1).Values = Range(Range("u55"), Range("u55").End(xlDown))
    .SeriesCollection(1).Name = "Hi" 'Range("u54")
End With
</code>```

Could I add the SeriesCollection statement to the With block to clean it up a bit as well?

答:
```<code>With Sheets("data").ChartObjects("Chart 3")
</code>```

should be

```<code>With Sheets("data").ChartObjects("Chart 3").Chart
</code>```

The chartobject is just a container for the actual chart itself

Body:
Hey I'm trying to update this chart via macro from monthly pulled data but keep running into issues after it had worked once. Syntax error?

With Sheets("data").ChartObjects("Chart 3")
    .SeriesCollection(1).XValues = ActiveSheet.Range(Range("b55"), Range("b55").End(xlDown))
    .SeriesCollection(1).Values = Range(Range("u55"), Range("u55").End(xlDown))
    .SeriesCollection(1).Name = "Hi" 'Range("u54")
End With

Could I add the SeriesCollection statement to the With block to clean it up a bit as well?

Body:
With Sheets("data").ChartObjects("Chart 3")

should be

With Sheets("data").ChartObjects("Chart 3").Chart

The chartobject is just a container for the actual chart itself


问:
gzip - questions about performance
Firstly, I'm using Django. Django provides gzip middleware which works just fine. Nginx also provides a gzip module. Would it make more sense to just use Nginx's gzip module because it is implemented purely in C, or are there other performance considerations I'm missing.

Secondly, Django doesn't gzip anything under 200 bytes. Is this because gzipping is too expensive to have any value when compressing output smaller than that?

Thirdly, the API I'm building will be almost purely dynamic with very little caching. Is gzipping expensive enough to make it unpractical to use in this situation (vs a situation where I could cache the gzipped output on the webserver)?

答:
1) I imagine that one gzip compression is enough and nginx is faster, although I haven't benchmarked it yet. GzipMiddleware utilizes a few built-ins, which might be well optimized, too.

```<code># From http://www.xhaus.com/alan/python/httpcomp.html#gzip
# Used with permission.
def compress_string(s):
    import cStringIO, gzip
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
    zfile.write(s)
    zfile.close()
    return zbuf.getvalue()
</code>```

2) Small gzip'd files just can't take advantage from compression (in fact small files might be bigger, when processed), so one can save time by just skipping this step.

3) You could design a test suite including sample data. Then decide on that data, what works best for your application.

ContentLicense: CC BY-SA 2.5

Title: gzip - questions about performance

Body:
1) I imagine that one gzip compression is enough and nginx is faster, although I haven't benchmarked it yet. GzipMiddleware utilizes a few built-ins, which might be well optimized, too.

# From http://www.xhaus.com/alan/python/httpcomp.html#gzip
# Used with permission.
def compress_string(s):
    import cStringIO, gzip
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
    zfile.write(s)
    zfile.close()
    return zbuf.getvalue()

2) Small gzip'd files just can't take advantage from compression (in fact small files might be bigger, when processed), so one can save time by just skipping this step.

3) You could design a test suite including sample data. Then decide on that data, what works best for your application.


问:
Can't seem to add git commit and push unless I'm in the folder directly above where the file is
So I'm trying to make my life easier and use the command line to do a git add . and then do a git commit -m which works when I'm in the folder that houses the file. But when I'm above it in the master folder which houses all of the files it says something like this

```<code>Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
(commit or discard the untracked or modified content in submodules)

    modified:   wp-content/themes/FoundationPress (modified content)"
</code>```

I can go in and then add the file and then cd all the way up to the top of the folder and add it, but I would like to be able to add everything in one go from the top folder.

Does anyone know what I'm doing wrong and how to fix this issue?

答:
```<code>(modified content)
</code>```

That is because wp-content/themes/FoundationPress is a gitlink, that is: special entry in the index of the parent repo.

It indicated that the submodule wp-content/themes/FoundationPress has changed, meaning its tree SHA1 has changed.

You can list that SHA1 with:

```<code>git rev-parse @:./wp-content/themes/FoundationPress
</code>```

You need to add and commit that new SHA1 in order for anyone cloning your repo to be able to checkout the submodule at the right state.

Body:
So I'm trying to make my life easier and use the command line to do a git add . and then do a git commit -m which works when I'm in the folder that houses the file. But when I'm above it in the master folder which houses all of the files it says something like this

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
(commit or discard the untracked or modified content in submodules)

    modified:   wp-content/themes/FoundationPress (modified content)"

I can go in and then add the file and then cd all the way up to the top of the folder and add it, but I would like to be able to add everything in one go from the top folder.

Does anyone know what I'm doing wrong and how to fix this issue?

Body:
(modified content)

That is because wp-content/themes/FoundationPress is a gitlink, that is: special entry in the index of the parent repo.

It indicated that the submodule wp-content/themes/FoundationPress has changed, meaning its tree SHA1 has changed.

You can list that SHA1 with:

git rev-parse @:./wp-content/themes/FoundationPress

You need to add and commit that new SHA1 in order for anyone cloning your repo to be able to checkout the submodule at the right state.


答:
There is not option to permanent hide but you can achieve by this way

1.Remove the specific view by

```<code>parent.removeViewAt(index);

parent.removeView(view);
</code>```

you have to save the state to show/hide the view on permanent storage like

Share preference / databases

Shared Preference Example

1.store value in sharedPrefernces:

```<code>SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("storevalue", false);
editor.commit();
</code>```

2.get value from sharedPreferences:

```<code>SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
preferences.getBoolean("storevalue", false);

if(preferences.getBoolean("storevalue", false))
{
view.setVisibility(View.VISIBLE);
}
else
view.setVisibility(View.GONE);
</code>```

Title: How to hide views for always

Body:
Can somebody tell me how to hide views for always?

I'm hiding a view with view.setVisibility(view.GONE); but when reopen the app I have to re-hide the view. I want a view hide for always when button is clicked until clearing app data or uninstalling. Thanks!

Body:
There is not option to permanent hide but you can achieve by this way

1.Remove the specific view by

parent.removeViewAt(index);

parent.removeView(view);

you have to save the state to show/hide the view on permanent storage like

Share preference / databases

Shared Preference Example

1.store value in sharedPrefernces:

SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("storevalue", false);
editor.commit();

2.get value from sharedPreferences:

SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
preferences.getBoolean("storevalue", false);

if(preferences.getBoolean("storevalue", false))
{
view.setVisibility(View.VISIBLE);
}
else
view.setVisibility(View.GONE);


答:
Your current approach is the programmatic one and is probably what you will have to use if you want a button to toggle the visibility of a view.  The only other option of which I am aware would be to disable visibility from the XML layout file:</p>

```<code><TextView
    android:visibility="gone"
    ... />
</code>```

Title: How to hide views for always

Body:
Your current approach is the programmatic one and is probably what you will have to use if you want a button to toggle the visibility of a view.  The only other option of which I am aware would be to disable visibility from the XML layout file:

<TextView
    android:visibility="gone"
    ... />


问:
How can I manually initialize an angular 2/4 app
I need to initialize an angular app with the component my-app,
the problem is that this component exists on a html template that is not loaded on page start so I have to manually initialize, otherwise it gives me an error showing this message:
Error: The selector "my-app" did not match any elements

Is that possible?

答:
Here is how you can do that. First create a root app module and declare your root component in declarations and entryComponents. Do not add it to bootstrap components. Then define ngDoBootstrap method on the module class to let Angular know you will be bootstrapping the application yourself. Inside this method obtain the reference to the ApplicationRef and then when the time comes simply call bootstrap on it passing the AppComponent class reference. Here is the code:

```<code>@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  entryComponents: [AppComponent]
})
export class AppModule {
  ngDoBootstrap(app: ApplicationRef) {
    // delay bootstrap by 3 seconds
    setTimeout(() => {
      app.bootstrap(AppComponent)
    }, 3000);
  }
}
</code>```

Essentially this is what Angular does under the hood when you call bootstrapModule(AppModule); with boostrapComponents specified.

Read How to manually bootstrap an Angular application for more details.

Body:
Here is how you can do that. First create a root app module and declare your root component in declarations and entryComponents. Do not add it to bootstrap components. Then define ngDoBootstrap method on the module class to let Angular know you will be bootstrapping the application yourself. Inside this method obtain the reference to the ApplicationRef and then when the time comes simply call bootstrap on it passing the AppComponent class reference. Here is the code:

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  entryComponents: [AppComponent]
})
export class AppModule {
  ngDoBootstrap(app: ApplicationRef) {
    // delay bootstrap by 3 seconds
    setTimeout(() => {
      app.bootstrap(AppComponent)
    }, 3000);
  }
}

Essentially this is what Angular does under the hood when you call bootstrapModule(AppModule); with boostrapComponents specified.

Read How to manually bootstrap an Angular application for more details.


问:
How to resize and display images from another domain using php?
I want to resize images using php. with out losing its quality. Currently I have two domains. I have to display images from portfolio section of my old site to new website. How to resize the images and display in my new portfolio section. how can I do that? </p>

答:
There are many functions for creating images, all of which do not have a problem with external domains. For instance, imagecreatefromjpeg(). http://php.net/manual/en/function.imagecreatefromjpeg.php If you go to that link, and check out all the functions on the left, you will find ones that crop, resize, etc., and most of them have examples.

For your question, I believe the best way to go about it is create one image from your existing image, and create a blank new image, then use the imagecopyresized() function to copy from your portfolio image to the blank one.


问:
Handle click events of both Recyclerview and CardView in same time
I have requirement to create nested recyclerView like

RecyclerView Contains-> CardView contains-> RecyclerView.

If I click on card I'm getting child position only but I also need parent card position. How can I handle click events of both Recyclerview and CardView at same time?

MainActivity.java:

```<code>public class MainActivity extends Activity {
LinearLayout linView;
private RecyclerView main_view;
RootAdapter adapter2;
private RelativeLayout mRelativeLayout;
private Context mContext;
private Activity mActivity;

int pos = 0;
int main_pos;

private static RecyclerView.Adapter adapter;
private static RecyclerView.Adapter adapterCo;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<DataModelMain> dataMain;
private static ArrayList<DataModel_CO> dataCo;
static View.OnClickListener myOnClickListener;
static View.OnClickListener onClickListener;
private static ArrayList<Integer> removedItems;
TestMain mainData = new TestMain();

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

    prof = (ImageView) findViewById(R.id.profile);

    main_view = (RecyclerView) findViewById(R.id.recycler_main);

    mRelativeLayout = (RelativeLayout) findViewById(R.id.partners);
    cont = (TextView) findViewById(R.id.mobile);
    iconType = (ImageView) findViewById(R.id.icon_type);
    linView = (LinearLayout) findViewById(R.id.layout_view);

    // Get the application context
    mContext = getApplicationContext();
    // Get the activity
    mActivity = MainActivity.this;

    myOnClickListener = new MyOnClickListener(this);
    onClickListener = new OnClickListener(this);

    main_view.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(
            this,
            LinearLayoutManager.VERTICAL,
            false
    ) {

    };

    main_view.setLayoutManager(layoutManager);
    main_view.setItemAnimator(new DefaultItemAnimator());
    dataMain = new ArrayList<DataModelMain>();

    getMainData();
    setMainView();
}
}

private void getMainData() {

    for (int i = 0; i < mainData.passengers.length; i++) {
        dataMain.add(new DataModelMain(
                mainData.type[i],
                mainData.passengers[i],
                mainData.p_name[i],
                mainData.p_contact[i],
                mainData.p_flight[i],
                mainData.p_pnr[i],
                mainData.air[i],
                mainData.p_time[i]
        ));
    }

    adapter2 = new RootAdapter(this, dataMain);
    main_view.setAdapter(adapter2);
}

private class MyOnClickListener implements View.OnClickListener {

    private final Context context;

    private MyOnClickListener(Context context) {
        this.context = context;
    }

    @Override
    public void onClick(View v) {
        showIcons(v);
    }

    private void showIcons(View v) {
        pos = main_view.getChildPosition(v);
        setMainView();

    }

}
private class OnClickListener implements View.OnClickListener {

    private final Context context1;

    private OnClickListener(Context context0) {
        this.context1 = context0;
    }

    @Override
    public void onClick(View v) {
        showIcons(v);
    }

    private void showIcons(View v) {
        pos = main_view.getChildPosition(v);
        Log.e("CLICKED","pos: "+pos);

    }

}

private class RootAdapter extends RecyclerView.Adapter<RootAdapter.RootViewHolder> {

    private final LayoutInflater inflater;
    String[] _items = new String[]{"GROUP 1", "GROUP 2", "GROUP 3", "GROUP 4"};
    private ArrayList<DataModelMain> dataSet;
    public RootAdapter(Context context,ArrayList<DataModelMain> data) {
        inflater = LayoutInflater.from(context);
        this.dataSet = data;
    }

    @Override
    public RootViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.card_main, viewGroup, false);
        RootViewHolder rvi = new RootViewHolder(view);
        view.setOnClickListener(MainActivity.onClickListener);
        return rvi;
    }

    @Override
    public void onBindViewHolder(RootViewHolder rootViewHolder, int i) {

        rootViewHolder.recyclerViewChild.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        rootViewHolder.recyclerViewChild.setAdapter(new ChildAdapter(inflater,dataSet));
    }

    @Override
    public int getItemCount() {
        return _items.length;
    }

    class RootViewHolder extends RecyclerView.ViewHolder {

        RecyclerView recyclerViewChild;

        public RootViewHolder(View itemView) {
            super(itemView);
            recyclerViewChild = (RecyclerView) itemView.findViewById(R.id.recycler_partners);

        }
    }
}

private class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
    private LayoutInflater _inflater;

    private ArrayList<DataModelMain> dataSet;

    public ChildAdapter(LayoutInflater inflater,ArrayList<DataModelMain> data) {
        _inflater = inflater;
        this.dataSet = data;
    }

    @Override
    public ChildViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = _inflater.inflate(R.layout.card_partner, viewGroup, false);
        ChildViewHolder rvi = new ChildViewHolder(view);
        view.setOnClickListener(MainActivity.myOnClickListener);
        return rvi;
    }

    @Override
    public void onBindViewHolder(ChildViewHolder holder, int listPosition) {
        TextView name = holder.tvName;
        TextView cont = holder.tvCont;
        TextView flight = holder.tvFlight;
        TextView pnr = holder.tvPNR;
        TextView time = holder.tvTime;
        ImageView type = holder.im_type;
        ImageView pic = holder.im_pic;
        ImageView logo = holder.im_logo;
        CardView cardView = holder.card;

        name.setText(dataSet.get(listPosition).getName());
        cont.setText(dataSet.get(listPosition).getContact());
        flight.setText(dataSet.get(listPosition).getFlight());
        pnr.setText(dataSet.get(listPosition).getPnr());
        time.setText(dataSet.get(listPosition).getTime());
        type.setImageResource(dataSet.get(listPosition).getType());
        pic.setImageResource(dataSet.get(listPosition).getImage());
        logo.setImageResource(dataSet.get(listPosition).getLogo());

        switch (dataSet.get(listPosition).getType()){

            case R.mipmap.gov:
                cardView.setCardBackgroundColor(Color.parseColor("#FAFAD2"));
                break;
            case R.mipmap.vip:
                cardView.setCardBackgroundColor(Color.parseColor("#CDFFCD"));
                break;
            case R.mipmap.jail:
                cardView.setCardBackgroundColor(Color.parseColor("#FFE4E1"));
                break;
            case R.mipmap.ban:
                cardView.setCardBackgroundColor(Color.parseColor("#DCDCDC"));
                break;

        }
    }

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

    public class ChildViewHolder extends RecyclerView.ViewHolder {

        ImageView im_type,im_pic,im_logo;
        TextView tvName,tvCont,tvFlight,tvPNR,tvTime;
        CardView card;

        public ChildViewHolder(View itemView) {
            super(itemView);
            this.card = (CardView) itemView.findViewById(R.id.card_view);
            this.im_type = (ImageView) itemView.findViewById(R.id.p_type);
            this.im_pic = (ImageView) itemView.findViewById(R.id.p_profile);
            this.im_logo = (ImageView) itemView.findViewById(R.id.p_air_lines);
            this.tvName = (TextView) itemView.findViewById(R.id.p_name);
            this.tvCont = (TextView) itemView.findViewById(R.id.p_mob);
            this.tvFlight = (TextView) itemView.findViewById(R.id.p_flight);
            this.tvPNR = (TextView) itemView.findViewById(R.id.p_pnr);
            this.tvTime = (TextView) itemView.findViewById(R.id.p_timer);
        }
    }
}
}
</code>```

答:
How about making the root/parent cardView clickable??

Give an id to the cardView item of the parent recyclerView. Place it in your ViewHolderClass and then assign a onCLickListener to the cardView in BindViewHolder like this:

```<code>rootViewHolder.rootCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // keep an track of the selected position of the cardView and store it in a global/local variable
            }
        });
</code>```

you can track the adapter position of the selected cardView using

```<code>rootViewHolder.getAdapterPosition()

Note: rootViewHolder is written as per your ViewHolder class
</code>```

I hope this helps !!

Body:
I have requirement to create nested recyclerView like

RecyclerView Contains-> CardView contains-> RecyclerView.

If I click on card I'm getting child position only but I also need parent card position. How can I handle click events of both Recyclerview and CardView at same time?

MainActivity.java:

public class MainActivity extends Activity {
LinearLayout linView;
private RecyclerView main_view;
RootAdapter adapter2;
private RelativeLayout mRelativeLayout;
private Context mContext;
private Activity mActivity;

int pos = 0;
int main_pos;

private static RecyclerView.Adapter adapter;
private static RecyclerView.Adapter adapterCo;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<DataModelMain> dataMain;
private static ArrayList<DataModel_CO> dataCo;
static View.OnClickListener myOnClickListener;
static View.OnClickListener onClickListener;
private static ArrayList<Integer> removedItems;
TestMain mainData = new TestMain();

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

    prof = (ImageView) findViewById(R.id.profile);

    main_view = (RecyclerView) findViewById(R.id.recycler_main);

    mRelativeLayout = (RelativeLayout) findViewById(R.id.partners);
    cont = (TextView) findViewById(R.id.mobile);
    iconType = (ImageView) findViewById(R.id.icon_type);
    linView = (LinearLayout) findViewById(R.id.layout_view);

    // Get the application context
    mContext = getApplicationContext();
    // Get the activity
    mActivity = MainActivity.this;

    myOnClickListener = new MyOnClickListener(this);
    onClickListener = new OnClickListener(this);

    main_view.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(
            this,
            LinearLayoutManager.VERTICAL,
            false
    ) {

    };

    main_view.setLayoutManager(layoutManager);
    main_view.setItemAnimator(new DefaultItemAnimator());
    dataMain = new ArrayList<DataModelMain>();

    getMainData();
    setMainView();
}
}

private void getMainData() {

    for (int i = 0; i < mainData.passengers.length; i++) {
        dataMain.add(new DataModelMain(
                mainData.type[i],
                mainData.passengers[i],
                mainData.p_name[i],
                mainData.p_contact[i],
                mainData.p_flight[i],
                mainData.p_pnr[i],
                mainData.air[i],
                mainData.p_time[i]
        ));
    }

    adapter2 = new RootAdapter(this, dataMain);
    main_view.setAdapter(adapter2);
}

private class MyOnClickListener implements View.OnClickListener {

    private final Context context;

    private MyOnClickListener(Context context) {
        this.context = context;
    }

    @Override
    public void onClick(View v) {
        showIcons(v);
    }

    private void showIcons(View v) {
        pos = main_view.getChildPosition(v);
        setMainView();

    }

}
private class OnClickListener implements View.OnClickListener {

    private final Context context1;

    private OnClickListener(Context context0) {
        this.context1 = context0;
    }

    @Override
    public void onClick(View v) {
        showIcons(v);
    }

    private void showIcons(View v) {
        pos = main_view.getChildPosition(v);
        Log.e("CLICKED","pos: "+pos);

    }

}

private class RootAdapter extends RecyclerView.Adapter<RootAdapter.RootViewHolder> {

    private final LayoutInflater inflater;
    String[] _items = new String[]{"GROUP 1", "GROUP 2", "GROUP 3", "GROUP 4"};
    private ArrayList<DataModelMain> dataSet;
    public RootAdapter(Context context,ArrayList<DataModelMain> data) {
        inflater = LayoutInflater.from(context);
        this.dataSet = data;
    }

    @Override
    public RootViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.card_main, viewGroup, false);
        RootViewHolder rvi = new RootViewHolder(view);
        view.setOnClickListener(MainActivity.onClickListener);
        return rvi;
    }

    @Override
    public void onBindViewHolder(RootViewHolder rootViewHolder, int i) {

        rootViewHolder.recyclerViewChild.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        rootViewHolder.recyclerViewChild.setAdapter(new ChildAdapter(inflater,dataSet));
    }

    @Override
    public int getItemCount() {
        return _items.length;
    }

    class RootViewHolder extends RecyclerView.ViewHolder {

        RecyclerView recyclerViewChild;

        public RootViewHolder(View itemView) {
            super(itemView);
            recyclerViewChild = (RecyclerView) itemView.findViewById(R.id.recycler_partners);

        }
    }
}

private class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
    private LayoutInflater _inflater;

    private ArrayList<DataModelMain> dataSet;

    public ChildAdapter(LayoutInflater inflater,ArrayList<DataModelMain> data) {
        _inflater = inflater;
        this.dataSet = data;
    }

    @Override
    public ChildViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = _inflater.inflate(R.layout.card_partner, viewGroup, false);
        ChildViewHolder rvi = new ChildViewHolder(view);
        view.setOnClickListener(MainActivity.myOnClickListener);
        return rvi;
    }

    @Override
    public void onBindViewHolder(ChildViewHolder holder, int listPosition) {
        TextView name = holder.tvName;
        TextView cont = holder.tvCont;
        TextView flight = holder.tvFlight;
        TextView pnr = holder.tvPNR;
        TextView time = holder.tvTime;
        ImageView type = holder.im_type;
        ImageView pic = holder.im_pic;
        ImageView logo = holder.im_logo;
        CardView cardView = holder.card;

        name.setText(dataSet.get(listPosition).getName());
        cont.setText(dataSet.get(listPosition).getContact());
        flight.setText(dataSet.get(listPosition).getFlight());
        pnr.setText(dataSet.get(listPosition).getPnr());
        time.setText(dataSet.get(listPosition).getTime());
        type.setImageResource(dataSet.get(listPosition).getType());
        pic.setImageResource(dataSet.get(listPosition).getImage());
        logo.setImageResource(dataSet.get(listPosition).getLogo());

        switch (dataSet.get(listPosition).getType()){

            case R.mipmap.gov:
                cardView.setCardBackgroundColor(Color.parseColor("#FAFAD2"));
                break;
            case R.mipmap.vip:
                cardView.setCardBackgroundColor(Color.parseColor("#CDFFCD"));
                break;
            case R.mipmap.jail:
                cardView.setCardBackgroundColor(Color.parseColor("#FFE4E1"));
                break;
            case R.mipmap.ban:
                cardView.setCardBackgroundColor(Color.parseColor("#DCDCDC"));
                break;

        }
    }

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

    public class ChildViewHolder extends RecyclerView.ViewHolder {

        ImageView im_type,im_pic,im_logo;
        TextView tvName,tvCont,tvFlight,tvPNR,tvTime;
        CardView card;

        public ChildViewHolder(View itemView) {
            super(itemView);
            this.card = (CardView) itemView.findViewById(R.id.card_view);
            this.im_type = (ImageView) itemView.findViewById(R.id.p_type);
            this.im_pic = (ImageView) itemView.findViewById(R.id.p_profile);
            this.im_logo = (ImageView) itemView.findViewById(R.id.p_air_lines);
            this.tvName = (TextView) itemView.findViewById(R.id.p_name);
            this.tvCont = (TextView) itemView.findViewById(R.id.p_mob);
            this.tvFlight = (TextView) itemView.findViewById(R.id.p_flight);
            this.tvPNR = (TextView) itemView.findViewById(R.id.p_pnr);
            this.tvTime = (TextView) itemView.findViewById(R.id.p_timer);
        }
    }
}
}

Body:
How about making the root/parent cardView clickable??

Give an id to the cardView item of the parent recyclerView. Place it in your ViewHolderClass and then assign a onCLickListener to the cardView in BindViewHolder like this:

rootViewHolder.rootCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // keep an track of the selected position of the cardView and store it in a global/local variable
            }
        });

you can track the adapter position of the selected cardView using

rootViewHolder.getAdapterPosition()

Note: rootViewHolder is written as per your ViewHolder class

I hope this helps !!


问:
Dictionary compare between two objects
Assuming I have these objects

```<code>    var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
    var person = new Person("Jane", "Smith", address);
</code>```

I want to check the equality of those object by using dictionary, so it's smiliar like this

```<code>    var dictionary = new Dictionary<object>{ [address] = address, [person] = person};
    Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
    Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));
</code>```

However, it's always return as False. what I'm missing here?

EDIT

Add custom dictionary

```<code>public class Dictionary<T> : Dictionary<T, T> where T : class, new()
{
}
</code>```

Add Classes

```<code>public abstract class BaseModel
{
    public string Id { get; set; }

    public BaseModel()
    {
    }
}

public class Address : BaseModel
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }

    public Address() { }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Address mod = value as Address;

        return (mod != null)
            && (Street == mod.Street)
            && (City == mod.City)
            && (PostalCode == mod.PostalCode)
            && (State == mod.State);
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }

    public Address(string street, string city, string state, string postalCode) {
        this.Street = street;
        this.City = city;
        this.State = state;
        this.PostalCode = postalCode;
    }
}

public class Person : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public Person() { }

    public Person(string firstName, string lastName, Address address)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Person mod = value as Person;

        return (mod != null)
            && (FirstName == mod.FirstName)
            && (LastName == mod.LastName)
            && (Address.Equals(mod.Address));
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }
}
</code>```

答:
You need to pass a instance of an appropriate IEqualityComparer.
If you do not pass any comparer dictionary will use the default comparer. (EqualityComparer.Default). This will only return true if the parameter passed are same instance of the object. You will have to create your own comparer

Or you can override GetHashCode and Equals in all classes that you want to store in the dictionary. Then EqualityComparer.Default calls the appropriate overrides for GetHashCode and Equals and you are set. If you are overriding these two functions you don't need to create or pass a comparer to the dictionary.

Edit based on OP's edit:

Note that your implementation of GetHashCode should be consistent with implementation of Equals:

a.Equals(b) => b.Equals(a) => a.GetHashCode() == b.GetHashCode()

In your case since you are still using the objects default GetHashCode the above condition doesn't holds.

The GetHashCode should be implemented like:

```<code>  public override int GetHashCode(){
        return this.FirstName.GetHashCode() ^
               this.LastName.GetHashCode() ^
               this.Address.GetHashCode();
    }
</code>```

Title: Dictionary compare between two objects

Body:
Assuming I have these objects

    var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
    var person = new Person("Jane", "Smith", address);

I want to check the equality of those object by using dictionary, so it's smiliar like this

    var dictionary = new Dictionary<object>{ [address] = address, [person] = person};
    Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
    Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));

However, it's always return as False. what I'm missing here?

EDIT

Add custom dictionary

public class Dictionary<T> : Dictionary<T, T> where T : class, new()
{
}

Add Classes

public abstract class BaseModel
{
    public string Id { get; set; }

    public BaseModel()
    {
    }
}

public class Address : BaseModel
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string PostalCode { get; set; }

    public Address() { }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Address mod = value as Address;

        return (mod != null)
            && (Street == mod.Street)
            && (City == mod.City)
            && (PostalCode == mod.PostalCode)
            && (State == mod.State);
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }

    public Address(string street, string city, string state, string postalCode) {
        this.Street = street;
        this.City = city;
        this.State = state;
        this.PostalCode = postalCode;
    }
}

public class Person : BaseModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public Person() { }

    public Person(string firstName, string lastName, Address address)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
    }

    public override bool Equals(object value)
    {
        if (value == null)
            return false;

        Person mod = value as Person;

        return (mod != null)
            && (FirstName == mod.FirstName)
            && (LastName == mod.LastName)
            && (Address.Equals(mod.Address));
    }

    public override int GetHashCode(){
        return base.GetHashCode();
    }
}

Body:
You need to pass a instance of an appropriate IEqualityComparer.
If you do not pass any comparer dictionary will use the default comparer. (EqualityComparer.Default). This will only return true if the parameter passed are same instance of the object. You will have to create your own comparer

Or you can override GetHashCode and Equals in all classes that you want to store in the dictionary. Then EqualityComparer.Default calls the appropriate overrides for GetHashCode and Equals and you are set. If you are overriding these two functions you don't need to create or pass a comparer to the dictionary.

Edit based on OP's edit:

Note that your implementation of GetHashCode should be consistent with implementation of Equals:

a.Equals(b) => b.Equals(a) => a.GetHashCode() == b.GetHashCode()

In your case since you are still using the objects default GetHashCode the above condition doesn't holds.

The GetHashCode should be implemented like:

  public override int GetHashCode(){
        return this.FirstName.GetHashCode() ^
               this.LastName.GetHashCode() ^
               this.Address.GetHashCode();
    }


问:
504 Gateway Time-out for backend on docker swarm overlay network
I have a 3 node swarm running on openstack. There are 2 docker services running using the same overlay network. One is the Nexus 3 private repository and the other is a nginx reverse proxy. Only nginx has exposed ports. This setup works fine but intermittently (possibly after many hours of not being accessed) I get a 504.
When I get on the nginx container...

nslookup:

```<code>root@7c7f5b09302f:/# nslookup nexus
Server:     127.0.0.11
Address:    127.0.0.11#53

Non-authoritative answer:
Name:   nexus
Address: 10.0.0.6
</code>```

wget:

```<code>root@7c7f5b09302f:/# wget -O- nexus:8081
--2017-05-09 23:23:18--  http://nexus:8081/
Resolving nexus (nexus)... 10.0.0.6
Connecting to nexus (nexus)|10.0.0.6|:8081... failed: Connection timed out.
Retrying.

--2017-05-09 23:25:26--  (try: 2)  http://nexus:8081/
Connecting to nexus (nexus)|10.0.0.6|:8081... ^C
root@7c7f5b09302f:/#
</code>```

ping:

```<code>root@7c7f5b09302f:/# ping nexus
PING nexus (10.0.0.6): 56 data bytes
64 bytes from 10.0.0.6: icmp_seq=0 ttl=64 time=0.077 ms
64 bytes from 10.0.0.6: icmp_seq=1 ttl=64 time=0.098 ms
64 bytes from 10.0.0.6: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 10.0.0.6: icmp_seq=3 ttl=64 time=0.071 ms
^C--- nexus ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.054/0.075/0.098/0.000 ms
root@7c7f5b09302f:/#
</code>```

So it can find the nexus container address. I can ping it but cannot connect to port 8081.

On the nexus container itself(on a different node on the swarm) the repository URL is accessible but from anywhere else, I get a 504 error:

```<code>bash-4.2$ curl -v http://nexus:8081/
* About to connect() to nexus port 8081 (#0)
*   Trying 10.0.0.6...
* Connected to nexus (10.0.0.6) port 8081 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nexus:8081
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 09 May 2017 23:23:03 GMT
< Server: Nexus/3.1.0-04 (OSS)
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Content-Type: text/html
< Last-Modified: Tue, 09 May 2017 23:23:03 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
< Content-Length: 4659
<

<!DOCTYPE html>
<html>
<head>
  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <!--[if lt IE 9]>
    <script>(new Image).src="http://nexus:8081/static/rapture/resources/favicon.ico?_v=3.1.0-04"</script>
  <![endif]-->
  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nexus:8081/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nexus:8081/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nexus:8081/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

    <script type="text/javascript">
    function progressMessage(msg) {
      if (console && console.log) {
        console.log(msg);
      }
      document.getElementById('loading-msg').innerHTML=msg;
    }
  </script>
  </head>
<body class="x-border-box">

<div id="loading-mask"></div>
<div id="loading">
  <div id="loading-background">
    <img id="loading-logo" src="http://nexus:8081/static/rapture/resources/images/loading-logo.png?_v=3.1.0-04"/>
    <img id="loading-product" src="http://nexus:8081/static/rapture/resources/images/loading-product.png?_v=3.1.0-04"/>
    <div class="loading-indicator">
      <img id="loading-spinner" src="http://nexus:8081/static/rapture/resources/images/loading-spinner.gif?_v=3.1.0-04"/>
      <span id="loading-msg">Loading ...</span>
    </div>
  </div>

    <div id="code-load" class="x-hide-display">

                  <script type="text/javascript">progressMessage('Loading baseapp-prod.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/baseapp-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading extdirect-prod.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/extdirect-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading bootstrap.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/bootstrap.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-rapture-prod.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/nexus-rapture-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-coreui-plugin-prod.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/nexus-coreui-plugin-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-proui-plugin-prod.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/nexus-proui-plugin-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading app.js');</script>
              <script type="text/javascript" src="http://nexus:8081/static/rapture/app.js?_v=3.1.0-04"></script>

            <script type="text/javascript">progressMessage('Initializing ...');</script>
    </div>
</div>

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>
  <iframe id="x-history-frame"></iframe>
</form>

</body>
</html>
* Connection #0 to host nexus left intact
bash-4.2$
</code>```

Here, I can ping the nginx container:

```<code>bash-4.2$ ping nginx_nexus
PING nginx_nexus (10.0.0.8) 56(84) bytes of data.
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=1 ttl=64 time=0.089 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=2 ttl=64 time=0.066 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=3 ttl=64 time=0.047 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=4 ttl=64 time=0.076 ms
^C
--- nginx_nexus ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2999ms
rtt min/avg/max/mdev = 0.047/0.069/0.089/0.017 ms
bash-4.2$
</code>```

Note: Till now, when I try to access nexus through nginx reverse proxy from any external point I get a "504 Gateway Time-out". However, the moment I run the following command on the nexus container, the error vanishes.

```<code>bash-4.2$ curl -v nginx_nexus
* About to connect() to nginx_nexus port 80 (#0)
*   Trying 10.0.0.8...
* Connected to nginx_nexus (10.0.0.8) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nginx_nexus
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.13.0
< Date: Tue, 09 May 2017 23:33:44 GMT
< Content-Type: text/html
< Content-Length: 4681
< Connection: keep-alive
< Keep-Alive: timeout=5
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Last-Modified: Tue, 09 May 2017 23:33:44 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
<

<!DOCTYPE html>
<html>
<head>
  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <!--[if lt IE 9]>
    <script>(new Image).src="http://nginx_nexus/static/rapture/resources/favicon.ico?_v=3.1.0-04"</script>
  <![endif]-->
  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nginx_nexus/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nginx_nexus/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nginx_nexus/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

    <script type="text/javascript">
    function progressMessage(msg) {
      if (console && console.log) {
        console.log(msg);
      }
      document.getElementById('loading-msg').innerHTML=msg;
    }
  </script>
  </head>
<body class="x-border-box">

<div id="loading-mask"></div>
<div id="loading">
  <div id="loading-background">
    <img id="loading-logo" src="http://nginx_nexus/static/rapture/resources/images/loading-logo.png?_v=3.1.0-04"/>
    <img id="loading-product" src="http://nginx_nexus/static/rapture/resources/images/loading-product.png?_v=3.1.0-04"/>
    <div class="loading-indicator">
      <img id="loading-spinner" src="http://nginx_nexus/static/rapture/resources/images/loading-spinner.gif?_v=3.1.0-04"/>
      <span id="loading-msg">Loading ...</span>
    </div>
  </div>

    <div id="code-load" class="x-hide-display">

                  <script type="text/javascript">progressMessage('Loading baseapp-prod.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/baseapp-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading extdirect-prod.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/extdirect-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading bootstrap.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/bootstrap.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-rapture-prod.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/nexus-rapture-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-coreui-plugin-prod.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/nexus-coreui-plugin-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading nexus-proui-plugin-prod.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/nexus-proui-plugin-prod.js?_v=3.1.0-04"></script>
                  <script type="text/javascript">progressMessage('Loading app.js');</script>
              <script type="text/javascript" src="http://nginx_nexus/static/rapture/app.js?_v=3.1.0-04"></script>

            <script type="text/javascript">progressMessage('Initializing ...');</script>
    </div>
</div>

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>
  <iframe id="x-history-frame"></iframe>
</form>

</body>
</html>
* Connection #0 to host nginx_nexus left intact
bash-4.2$
</code>```

This keeps happening intermittently. After few hours when the repository is not in use, I will find the "504 Gateway Time-out" again and have to login to the swarm node and nexus container and run curl again to resolve it. Please help me figure out a solution to the 504 error. This issue does not exist if the containers are running on same host and no overlay network is used.

答: The problem disappeared with openstack upgrade. I no longer have the version details or the setup available to me so I cannot provide more information about that. </p>

Body:
I have a 3 node swarm running on openstack. There are 2 docker services running using the same overlay network. One is the Nexus 3 private repository and the other is a nginx reverse proxy. Only nginx has exposed ports. This setup works fine but intermittently (possibly after many hours of not being accessed) I get a 504.
When I get on the nginx container...

nslookup:

root@7c7f5b09302f:/# nslookup nexus
Server:     127.0.0.11
Address:    127.0.0.11#53

Non-authoritative answer:
Name:   nexus
Address: 10.0.0.6

wget:

root@7c7f5b09302f:/# wget -O- nexus:8081
--2017-05-09 23:23:18--  http://nexus:8081/
Resolving nexus (nexus)... 10.0.0.6
Connecting to nexus (nexus)|10.0.0.6|:8081... failed: Connection timed out.
Retrying.

--2017-05-09 23:25:26--  (try: 2)  http://nexus:8081/
Connecting to nexus (nexus)|10.0.0.6|:8081... ^C
root@7c7f5b09302f:/#

ping:

root@7c7f5b09302f:/# ping nexus
PING nexus (10.0.0.6): 56 data bytes
64 bytes from 10.0.0.6: icmp_seq=0 ttl=64 time=0.077 ms
64 bytes from 10.0.0.6: icmp_seq=1 ttl=64 time=0.098 ms
64 bytes from 10.0.0.6: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 10.0.0.6: icmp_seq=3 ttl=64 time=0.071 ms
^C--- nexus ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.054/0.075/0.098/0.000 ms
root@7c7f5b09302f:/#

So it can find the nexus container address. I can ping it but cannot connect to port 8081.

On the nexus container itself(on a different node on the swarm) the repository URL is accessible but from anywhere else, I get a 504 error:

bash-4.2$ curl -v http://nexus:8081/
* About to connect() to nexus port 8081 (#0)
*   Trying 10.0.0.6...
* Connected to nexus (10.0.0.6) port 8081 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nexus:8081
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 09 May 2017 23:23:03 GMT
< Server: Nexus/3.1.0-04 (OSS)
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Content-Type: text/html
< Last-Modified: Tue, 09 May 2017 23:23:03 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
< Content-Length: 4659
<

<!DOCTYPE html>

  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nexus:8081/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nexus:8081/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nexus:8081/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

      Loading ...

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>

</form>

* Connection #0 to host nexus left intact
bash-4.2$

Here, I can ping the nginx container:

bash-4.2$ ping nginx_nexus
PING nginx_nexus (10.0.0.8) 56(84) bytes of data.
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=1 ttl=64 time=0.089 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=2 ttl=64 time=0.066 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=3 ttl=64 time=0.047 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=4 ttl=64 time=0.076 ms
^C
--- nginx_nexus ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2999ms
rtt min/avg/max/mdev = 0.047/0.069/0.089/0.017 ms
bash-4.2$

Note: Till now, when I try to access nexus through nginx reverse proxy from any external point I get a "504 Gateway Time-out". However, the moment I run the following command on the nexus container, the error vanishes.

bash-4.2$ curl -v nginx_nexus
* About to connect() to nginx_nexus port 80 (#0)
*   Trying 10.0.0.8...
* Connected to nginx_nexus (10.0.0.8) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nginx_nexus
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.13.0
< Date: Tue, 09 May 2017 23:33:44 GMT
< Content-Type: text/html
< Content-Length: 4681
< Connection: keep-alive
< Keep-Alive: timeout=5
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Last-Modified: Tue, 09 May 2017 23:33:44 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
<

<!DOCTYPE html>

  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nginx_nexus/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nginx_nexus/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nginx_nexus/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

      Loading ...

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>

</form>

* Connection #0 to host nginx_nexus left intact
bash-4.2$

This keeps happening intermittently. After few hours when the repository is not in use, I will find the "504 Gateway Time-out" again and have to login to the swarm node and nexus container and run curl again to resolve it. Please help me figure out a solution to the 504 error. This issue does not exist if the containers are running on same host and no overlay network is used.


问:
Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible
Here is the error

Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized.

I am writing a simple console app and the first line of code is this:

```<code>List<MyObjectModel> list = MyObjectModel.GetNonCompletedReturns();
</code>```

and the code for the function is:

```<code>public static List<MyObjectModel> GetNonCompletedReturns()
{
    MyObject service = new MyObject();
    List<MyObject> entities =
                      (from recs in service.Retrieve() where select recs).ToList();

    List<MyObjectModel> models = new List<MyObjectModel>();

    foreach (MyObject entity in entities)
    {
        models.Add(BindModel(entity));
    }

    return models;
}
</code>```

and if I try to step through the code, as soon as I get back to the main of my app and hover over the list, I get the error message that I showed.

Can anyone help?

答:
While it's true that the "Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized" error appears when in release mode, most developers just ensure that their projects are configured to compile as a debug build. BUT to be sure that you have no release-DLL issues, you also must check the references to DLLs that are in your solution and make sure that you don't have a reference to a release-build DLL. If you find that this is the case, delete the DLL reference and then add a project reference rather than a DLL reference. The project reference will ensure that your solution references debug or release versions of the DLL as specified in your build configuration. </p>

<p>Note that the above advice applies, of course, to only those DLLs to which you have source code and which are built from a project in your solution. </p>

Body:
Here is the error

Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized.

I am writing a simple console app and the first line of code is this:

List<MyObjectModel> list = MyObjectModel.GetNonCompletedReturns();

and the code for the function is:

public static List<MyObjectModel> GetNonCompletedReturns()
{
    MyObject service = new MyObject();
    List<MyObject> entities =
                      (from recs in service.Retrieve() where select recs).ToList();

    List<MyObjectModel> models = new List<MyObjectModel>();

    foreach (MyObject entity in entities)
    {
        models.Add(BindModel(entity));
    }

    return models;
}

and if I try to step through the code, as soon as I get back to the main of my app and hover over the list, I get the error message that I showed.

Can anyone help?

Body:
While it's true that the "Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized" error appears when in release mode, most developers just ensure that their projects are configured to compile as a debug build. BUT to be sure that you have no release-DLL issues, you also must check the references to DLLs that are in your solution and make sure that you don't have a reference to a release-build DLL. If you find that this is the case, delete the DLL reference and then add a project reference rather than a DLL reference. The project reference will ensure that your solution references debug or release versions of the DLL as specified in your build configuration.

Note that the above advice applies, of course, to only those DLLs to which you have source code and which are built from a project in your solution.


问:
Geodjango Exception when importing django.contrib.gis.gdal: OSError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name
I have followed the tutorial for installing Geodjango on my Ubuntu 14.04. I am using Django 1.10 and Python 3.5, postgres-9.6 and postgis 2.3.

I have checked here and here, but found no solution.
In a newly installed ubuntu 14.04 Virtual Machine, it worked.

But in my installation, when I tried making migrations, I got:
OSError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name

Investigating a bit further, I tried simply:

```<code>from django.contrib.gis import gdal
</code>```

And got:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/__init__.py", line 49, in <module>
    from django.contrib.gis.gdal.driver import Driver  # NOQA
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module>
    from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 9, in <module>
    from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/libgdal.py", line 48, in <module>
    lgdal = CDLL(lib_path)
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name
</code>```

Is there any suggestions on how I could repair my setup?

UPDATE

It seems to be a problema with my conda environment. When I started using a pip virtualenv, the problem did not arise anymore. I am not answering the question, because I could not find the solution, only a workaround. But rebuilding the environment with pip virtualenv works.

答:
In conda environment: conda install -c conda-forge gdal=2.2.1

In django settings.py:
GDAL_LIBRARY_PATH = '<HOME>/anaconda3/envs/<env_name>/lib/libgdal.so'

Body:
I have followed the tutorial for installing Geodjango on my Ubuntu 14.04. I am using Django 1.10 and Python 3.5, postgres-9.6 and postgis 2.3.

I have checked here and here, but found no solution.
In a newly installed ubuntu 14.04 Virtual Machine, it worked.

But in my installation, when I tried making migrations, I got:
OSError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name

Investigating a bit further, I tried simply:

from django.contrib.gis import gdal

And got:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/__init__.py", line 49, in <module>
    from django.contrib.gis.gdal.driver import Driver  # NOQA
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module>
    from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 9, in <module>
    from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/site-packages/django/contrib/gis/gdal/libgdal.py", line 48, in <module>
    lgdal = CDLL(lib_path)
File "/home/pv/anaconda3/envs/dj110py35/lib/python3.5/ctypes/__init__.py", line 347, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/libgdal.so.1: undefined symbol: sqlite3_column_table_name

Is there any suggestions on how I could repair my setup?

UPDATE

It seems to be a problema with my conda environment. When I started using a pip virtualenv, the problem did not arise anymore. I am not answering the question, because I could not find the solution, only a workaround. But rebuilding the environment with pip virtualenv works.


问:
How to tag a dequeueReusableCell without mess the content?
I have used a dequeueReusableCell in a list, and there are 4 UILabel in the cell. There are screenshots below.

Whichever the label has a prefix of "-", it will be Red, but after scroll it a few pages, the number has become a mess. Wonder if there a way to avoid this?

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
    let currentRecipe = recipes?[indexPath.row]
    let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824

    (cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
    (cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name

    let hungryLabel = cell.viewWithTag(301) as! UILabel
    hungryLabel.text = currentRecipe?.hungry_value
    if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
        hungryLabel.textColor = colorRed
    }

    let healthLabel = (cell.viewWithTag(302) as! UILabel)
    healthLabel.text = currentRecipe?.health_value
    if (currentRecipe?.health_value!.hasPrefix("-"))! {
        healthLabel.textColor = colorRed
    }

    let sanityLabel = (cell.viewWithTag(303) as! UILabel)
    sanityLabel.text = currentRecipe?.sanity_value
    if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
        sanityLabel.textColor = colorRed
    }

    (cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration

    return cell
}
</code>```

Thanks you guys.

I add a Black Color to 'else', it works, thank you

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
    let currentRecipe = recipes?[indexPath.row]
    let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1)    //FE3824
    let colorBlack = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1)        //747474

    (cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
    (cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name

    let hungryLabel = cell.viewWithTag(301) as! UILabel
    hungryLabel.text = currentRecipe?.hungry_value
    if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
        hungryLabel.textColor = colorRed
    } else {
        hungryLabel.textColor = colorBlack
    }

    let healthLabel = (cell.viewWithTag(302) as! UILabel)
    healthLabel.text = currentRecipe?.health_value
    if (currentRecipe?.health_value!.hasPrefix("-"))! {
        healthLabel.textColor = colorRed
    } else {
        healthLabel.textColor = colorBlack
    }

    let sanityLabel = (cell.viewWithTag(303) as! UILabel)
    sanityLabel.text = currentRecipe?.sanity_value
    if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
        sanityLabel.textColor = colorRed
    } else {
        sanityLabel.textColor = colorBlack
    }

    (cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration

    return cell
}
</code>```

答:
in your cellForRowAt method you need to check if value is positive the color is black and if negative the it is red. For example</p>

```<code>label.color = black

if negativeValue {
     lagel.color = red
}
</code>```

Body:
I have used a dequeueReusableCell in a list, and there are 4 UILabel in the cell. There are screenshots below.

Whichever the label has a prefix of "-", it will be Red, but after scroll it a few pages, the number has become a mess. Wonder if there a way to avoid this?

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
    let currentRecipe = recipes?[indexPath.row]
    let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1) //FE3824

    (cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
    (cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name

    let hungryLabel = cell.viewWithTag(301) as! UILabel
    hungryLabel.text = currentRecipe?.hungry_value
    if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
        hungryLabel.textColor = colorRed
    }

    let healthLabel = (cell.viewWithTag(302) as! UILabel)
    healthLabel.text = currentRecipe?.health_value
    if (currentRecipe?.health_value!.hasPrefix("-"))! {
        healthLabel.textColor = colorRed
    }

    let sanityLabel = (cell.viewWithTag(303) as! UILabel)
    sanityLabel.text = currentRecipe?.sanity_value
    if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
        sanityLabel.textColor = colorRed
    }

    (cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration

    return cell
}

Thanks you guys.

I add a Black Color to 'else', it works, thank you

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableCell", for: indexPath)
    let currentRecipe = recipes?[indexPath.row]
    let colorRed = UIColor(red: 0xFE/255, green: 0x38/255, blue: 0x24/255, alpha: 1)    //FE3824
    let colorBlack = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1)        //747474

    (cell.viewWithTag(100) as! UIImageView).image = UIImage(named: currentRecipe?.pic ?? "")
    (cell.viewWithTag(200) as! UILabel).text = currentRecipe?.name

    let hungryLabel = cell.viewWithTag(301) as! UILabel
    hungryLabel.text = currentRecipe?.hungry_value
    if (currentRecipe?.hungry_value!.hasPrefix("-"))! {
        hungryLabel.textColor = colorRed
    } else {
        hungryLabel.textColor = colorBlack
    }

    let healthLabel = (cell.viewWithTag(302) as! UILabel)
    healthLabel.text = currentRecipe?.health_value
    if (currentRecipe?.health_value!.hasPrefix("-"))! {
        healthLabel.textColor = colorRed
    } else {
        healthLabel.textColor = colorBlack
    }

    let sanityLabel = (cell.viewWithTag(303) as! UILabel)
    sanityLabel.text = currentRecipe?.sanity_value
    if (currentRecipe?.sanity_value!.hasPrefix("-"))! {
        sanityLabel.textColor = colorRed
    } else {
        sanityLabel.textColor = colorBlack
    }

    (cell.viewWithTag(304) as! UILabel).text = currentRecipe?.duration

    return cell
}

Body:
in your cellForRowAt method you need to check if value is positive the color is black and if negative the it is red. For example

label.color = black

if negativeValue {
     lagel.color = red
}


问:
What is the proper way to use services in Angular4?
I ask this because I’m new in Angular4, and the thing for me is: Should I use a service inside a model. e.g. a simple class for a type stucture or inside a component? My doubt comes from a stackoverflow answer, that said that a component is similar to the C in MVC.</p>

答:
You can use it in both places. Inside model for (type structure) and inside component using DI. </p>

<p>The difference comes with the usage. Use a Class as a simple class or use it as an Injectable class using DI. Its all about what you need. Nothing wrong in using it in multiple places. </p>

Body:
You can use it in both places. Inside model for (type structure) and inside component using DI.

The difference comes with the usage. Use a Class as a simple class or use it as an Injectable class using DI. Its all about what you need. Nothing wrong in using it in multiple places.


问:
Android / Java find the correct library for a particular class
How can I figure out which class needs to import which library?
For example, I see a sample code like below:

```<code>RequestQueue queue = Volley.newRequestQueue(this);
</code>```

When I try this code Android Studio throws that RequestQueue and Volley cannot resolve.
Is there any documentation, wiki, a website for finding out the correct import library for these classes?

答:
Just do a search for the class on google. So in this case, search for the class 'RequestQueue' on google and the second result itself gives you the package. Here, it is com.android.volley package.

http://afzaln.com/volley/com/android/volley/RequestQueue.html

Body:
How can I figure out which class needs to import which library?
For example, I see a sample code like below:

RequestQueue queue = Volley.newRequestQueue(this);

When I try this code Android Studio throws that RequestQueue and Volley cannot resolve.
Is there any documentation, wiki, a website for finding out the correct import library for these classes?


问:
postgresql group count distinct using fast way
I got table T with 2 column as follow example:

```<code>C1      C2
----------
A       x
A       x
A       y
B       x
B       x
</code>```

I want to count number of distinct C1 for each value in C2. This result should be like:

```<code>C1      distinct count
----------------------
A       2               // count distinct x,x,y = 2
B       1               // count distinct x,x = 1
</code>```

it is easy to come out with a SQL query like this

```<code>select C1, count(distinct C2) from T group by C1
</code>```

however, as discussed in postgresql COUNT(DISTINCT …) very slow, this query yield poor performance.  I would like to use the improved query (count (*) (select distinct ...)) as suggested in that article but I don't know how to form the query with group by.

答:
Try this query if you want avoid DISTINCT keyword

Sample Data:

```<code>stackoverflow=# select * from T;
 c1 | c2
----+----
 A  | x
 A  | x
 A  | y
 B  | x
 B  | x
(5 rows)
</code>```

Query:

```<code>stackoverflow=# WITH count_distinct as (SELECT C1 FROM T GROUP BY c1,c2)
SELECT c1,count(c1) FROM count_distinct GROUP BY C1;  --updated missing group by
</code>```

Output:

```<code> c1 | count
----+-------
 B  |     1
 A  |     2
(2 rows)
</code>```

Same output, but you should try the performance first.

ContentLicense: CC BY-SA 4.0

Body:
I got table T with 2 column as follow example:

C1      C2
----------
A       x
A       x
A       y
B       x
B       x

I want to count number of distinct C1 for each value in C2. This result should be like:

C1      distinct count
----------------------
A       2               // count distinct x,x,y = 2
B       1               // count distinct x,x = 1

it is easy to come out with a SQL query like this

select C1, count(distinct C2) from T group by C1

however, as discussed in postgresql COUNT(DISTINCT …) very slow, this query yield poor performance.  I would like to use the improved query (count (*) (select distinct ...)) as suggested in that article but I don't know how to form the query with group by.

Body:
Try this query if you want avoid DISTINCT keyword

Sample Data:

stackoverflow=# select * from T;
 c1 | c2
----+----
 A  | x
 A  | x
 A  | y
 B  | x
 B  | x
(5 rows)

Query:

stackoverflow=# WITH count_distinct as (SELECT C1 FROM T GROUP BY c1,c2)
SELECT c1,count(c1) FROM count_distinct GROUP BY C1;  --updated missing group by

Output:

 c1 | count
----+-------
 B  |     1
 A  |     2
(2 rows)

Same output, but you should try the performance first.


问:
C global static variable initialization is done by linker?
Let's say we have:

f1.c

```<code>#include <stdio.h>
static int x = 10;

void f1() {
  printf("f1.c : %d\n", x);
}
</code>```

main.c

```<code>extern void f1();
int main(int argc, char **argv) {
  f1();
  return 0;
}
</code>```

we will compile and read the two ELF file symboltables (rel. ELF and exec ELF):

```<code>$> gcc -c *.c
$> readelf -s f1.o | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
        5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
$> gcc *.o
$> readelf -s a.out | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
       38: 0000000000601038     4 OBJECT  LOCAL  DEFAULT   25 x
</code>```

I can see that the Value (also known as address) in which the global static variable x is 0000000000000000 from reading the relocatable object file f1.o.

Which means we haven't initialized it yet since it is still a rel. ELF object file and the linker will take care of this.

So my question is then, if the linker is the one to set x to the value of 10 at known address after linking of 0000000000601038, how does it do so?  Where does the linker get the information to set the value to 10 and who gives this information (f1.o?) ?

答:
The value 0000000000000000 (in object file f1.o) is a relative address (of the static variable), so is an offset, and that file also contains relocation directives related to it. The code for getting the argument x to print has also some relocation on it (on some load machine instruction).

In that object file you probably have a .data section. That section should start with a word  (having the 0 offset you observed in f1.o) containing 10.

Read much more about linkers (I recommend Levine's Linkers and loaders book).  The linking process (to get the ELF executable) is processing relocation directives. Read also more about the ELF format, starting with elf(5) (after having read the ELF wikipage). Study also the ABI specifications (for Linux x86-64 see here from this answer) which details possible relocation directives.

You may want to compile your f1.c with gcc -Wall -S -fverbose-asm -O1 f1.c then look at the emitted assembler file f1.s

You may also want to inspect the object file f1.o and the ELF executable a.out with various tools like readelf(1) and objdump(1). Both accept numerous options (notably the -r option to objdump to show relocation directives).

Dynamic linking (of the C standard library libc.*.so) introduces some additional complexity in the ELF executable. See also ld-linux(8) (which does some linking job at start of runtime) and vdso(7). You may also want to read Drepper's How To Write Shared Libraries paper.

The freely available textbook Operating Systems: Three Easy Pieces could also be worthwhile to read (it explains what a process is and how its execution proceeds).

Body:
Let's say we have:

f1.c

#include <stdio.h>
static int x = 10;

void f1() {
  printf("f1.c : %d\n", x);
}

main.c

extern void f1();
int main(int argc, char **argv) {
  f1();
  return 0;
}

we will compile and read the two ELF file symboltables (rel. ELF and exec ELF):

$> gcc -c *.c
$> readelf -s f1.o | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
        5: 0000000000000000     4 OBJECT  LOCAL  DEFAULT    3 x
$> gcc *.o
$> readelf -s a.out | grep x
      Num:    Value          Size Type    Bind   Vis      Ndx Name
       38: 0000000000601038     4 OBJECT  LOCAL  DEFAULT   25 x

I can see that the Value (also known as address) in which the global static variable x is 0000000000000000 from reading the relocatable object file f1.o.

Which means we haven't initialized it yet since it is still a rel. ELF object file and the linker will take care of this.

So my question is then, if the linker is the one to set x to the value of 10 at known address after linking of 0000000000601038, how does it do so?  Where does the linker get the information to set the value to 10 and who gives this information (f1.o?) ?


问:
Retrieval of all the invoices of particular contact id in xero
In xero, if we create a contact. Using that contact we perform couple of sales invoice and purchase bills and few of them get paid. Now I want to obtain the list of the invoices groupedBy ContactID in php

答:
Xero have recently released functionality that allows this in an easy way.

You can use the ContactIDs query parameter on the invoices endpoint like the following:

```<code>GET ../Invoices?ContactIDs=623e392d-7402-40e4-a54c-fdf29783e9a4
</code>```

You can also do this for more than one ContactID by supplying a comma separated list of ContactIDs.

You can find more information about this in this handy blog post

Body:
Xero have recently released functionality that allows this in an easy way.

You can use the ContactIDs query parameter on the invoices endpoint like the following:

GET ../Invoices?ContactIDs=623e392d-7402-40e4-a54c-fdf29783e9a4

You can also do this for more than one ContactID by supplying a comma separated list of ContactIDs.

You can find more information about this in this handy blog post


问:
How to implement a memory heap
Wasn't exactly sure how to phrase the title, but the question is:

I've heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary. This is, in contrast to simply going to the OS every time memory is needed.
I've heard that this would be faster because it would avoid the cost of asking the OS for contiguous blocks of memory constantly.

I believe the JVM does just this, maintaining its own section of memory and then allocating objects from that.

My question is, how would one actually implement this?

答:
Here is the classic allocator, and one of the best for non-multithreaded use:

http://gee.cs.oswego.edu/dl/html/malloc.html

You can learn a lot from reading the explanation of its design. The link to malloc.c in the article is rotted; it can now be found at http://gee.cs.oswego.edu/pub/misc/malloc.c.

With that said, unless your program has really unusual allocation patterns, it's probably a very bad idea to write your own allocator or use a custom one. Especially if you're trying to replace the system malloc, you risk all kinds of bugs and compatibility issues from different libraries (or standard library functions) getting linked to the "wrong version of malloc".

If you find yourself needing specialized allocation for just a few specific tasks, that can be done without replacing malloc. I would recommend looking up GNU obstack and object pools for fixed-sized objects. These cover a majority of the cases where specialized allocation might have real practical usefulness.

Title: How to implement a memory heap


问:
selecting 2 different option values and sending data to php using ajax
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

```<code>$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});
</code>```

This is my PHP code:

```<code>$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}
</code>```

答:
Your code should be like this

```<code>$(document).ready(function () {
                $("#updateStatus,#updateStatus1").change(function () {

                    var opt = $("#updateStatus").val();
                    var sta = $("#updateStatus1").val();

                    $.ajax({
                        url: 'updatecode.php',
                        type: 'POST',
                        data: {option:opt,status:sta},
                        dataType: 'json',
                        success: function (data) {
                            alert(data + "hello");
                        }
                    });
                });
            })
</code>```

and php code should like this

```<code>$id = $_POST['option'];
$status = $_POST['status'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
   echo json_encode("fail");
 } else {
 echo json_encode("sucess");
}
</code>```

Body:
I am taking two different values from select options and sending it using AJAX, but PHP is not responding to the request.

This is my jQuery code:

$(document).ready(function() {
  $("#updateStatus").change(function() {
    var opt = $("#updateStatus").val();

    $("#updateStatus1").change(function() {
      var sta = $("#updateStatus1").val();

      $.ajax({
        url: 'updatecode.php',
        type: 'POST',
        data: "option=" + opt + "&status=" + sta,
        dataType: 'json',
        success: function(data) {
          alert(data + "hello");
        }
      });
    });
  });
});

This is my PHP code:

$id = $_POST['opt'];
$status = $_POST['sta'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
  echo json_encode("fail");
} else {
  echo json_encode("sucess");
}

Body:
Your code should be like this

$(document).ready(function () {
                $("#updateStatus,#updateStatus1").change(function () {

                    var opt = $("#updateStatus").val();
                    var sta = $("#updateStatus1").val();

                    $.ajax({
                        url: 'updatecode.php',
                        type: 'POST',
                        data: {option:opt,status:sta},
                        dataType: 'json',
                        success: function (data) {
                            alert(data + "hello");
                        }
                    });
                });
            })

and php code should like this

$id = $_POST['option'];
$status = $_POST['status'];
$query = "UPDATE projectstable SET projectStatus='".$status."'WHERE id='".$id."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

if (!$row) {
   echo json_encode("fail");
 } else {
 echo json_encode("sucess");
}


问:
vendor folder not used with 'go build'
I'm using go-1.7 in MacOS Sierra.

My project is inside my $GOPATH/src folder and has a vendor folder inside with all its dependencies.

and I'm using the dependencies like this inside my code:

```<code>import (
"github.com/google/go-github/github"
)
</code>```

Now if I run go build i get the message that all my dependencies I use could not be found inside the $GOROOT and $GOPATH on the other and adding "vendor" to my code is working:

```<code>import (
"vendor/github.com/google/go-github/github"
)
</code>```

But as far as I understood it should be possible to to like in the first code snipped.

ah FYI there are no symlinks etc.

答:
I got this error and struggled for a while; I update to Go 1.8.3 and was using glide version 0.12.3; and my GOPATH was set as $PWD and glide was installing everything in ./vendor folder;

Finally got the error; THERE SHOULD BE a src folder under GOPATH and all your workspace should be under this src folder

It must be in the docs, and in dev machine I set it proper; but missed in Jenkins build

Title: vendor folder not used with 'go build'

Body:
I'm using go-1.7 in MacOS Sierra.

My project is inside my $GOPATH/src folder and has a vendor folder inside with all its dependencies.

and I'm using the dependencies like this inside my code:

import (
"github.com/google/go-github/github"
)

Now if I run go build i get the message that all my dependencies I use could not be found inside the $GOROOT and $GOPATH on the other and adding "vendor" to my code is working:

import (
"vendor/github.com/google/go-github/github"
)

But as far as I understood it should be possible to to like in the first code snipped.

ah FYI there are no symlinks etc.


问:
How can I get rid of "result", "insertedCount", and "insertedIds" from MongoDB callback and node and get only an array of database objects?
I just updated Node after not doing so for a while and had to reinstall MongoDB and other modules.  Where I previously would only get an array of database objects when using the find() function, I'm now getting a JSON object that includes "results", "ops", "insertedCount", and "insertedIds".  I can't remember what I might have done when I initially set it up or maybe this is just an annoying change with Mongo, but I'd like to return to only getting an array of database objects so that I don't have to test my entire server.  I've tried several npm parse modules with no success.

Here's an example:

```<code>{ result: { ok: 1, n: 1 },
  ops:
   [ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ],
  insertedCount: 1,
  insertedIds: [ 595f0fe55e84fa2468b17ce8 ] }
</code>```

Whereas previously, it would have only returned:

```<code>[ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ]
</code>```

答:
You can take the resulting object and strip it down to just the array by accessing the ops attribute.

```<code>runMyQuery().then(function(res) {
    return res.ops;
});
</code>```

The previous example makes a lot of assumptions, so don't expect a copy-paste solution.

Body:
I just updated Node after not doing so for a while and had to reinstall MongoDB and other modules.  Where I previously would only get an array of database objects when using the find() function, I'm now getting a JSON object that includes "results", "ops", "insertedCount", and "insertedIds".  I can't remember what I might have done when I initially set it up or maybe this is just an annoying change with Mongo, but I'd like to return to only getting an array of database objects so that I don't have to test my entire server.  I've tried several npm parse modules with no success.

Here's an example:

{ result: { ok: 1, n: 1 },
  ops:
   [ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ],
  insertedCount: 1,
  insertedIds: [ 595f0fe55e84fa2468b17ce8 ] }

Whereas previously, it would have only returned:

[ { user: '595ee2fec2924e5435dfdd2d'},
       _id: 595f0fe55e84fa2468b17ce8 } ]

Body:
You can take the resulting object and strip it down to just the array by accessing the ops attribute.

runMyQuery().then(function(res) {
    return res.ops;
});

The previous example makes a lot of assumptions, so don't expect a copy-paste solution.


问:
jQuery form serializeObject
I have a form with fields and a list of another object with items. But with jQuery $("form").serializeObject(), it is not creating the right object like here:

```<code>var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})
</code>```

Any ideas?

答:
You can try below solution:</p>

```<code>var myObj = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recEncoded = $.param( myObj);
var recDecoded = decodeURIComponent( $.param( myObj ) );

alert( recEncoded );
</code>```

Title: jQuery form serializeObject

Body:
I have a form with fields and a list of another object with items. But with jQuery $("form").serializeObject(), it is not creating the right object like here:

var functionViewModel = new Object();
functionViewModel.Id = 1;
functionViewModel.Name = "F-I-001";
functionViewModel.Localised = [];
functionViewModel.Localised.push({

  LocalisedId: '1|1',
  Subject: "F-N-001"
});

functionViewModel.CategoryViewModel = new Object();
functionViewModel.CategoryViewModel.CategoryInGroup = [];
functionViewModel.CategoryViewModel.CategoryInGroup.push({
  Id: '1'
})

Any ideas?

Body:
You can try below solution:

var myObj = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recEncoded = $.param( myObj);
var recDecoded = decodeURIComponent( $.param( myObj ) );

alert( recEncoded );


问:
Support for Farsi/Arabic texts in Three.js
I need to show some text in Persian/Arabic language. I loaded a font including characters and I used TextGeometry to create a text on the scene:

var loader = new THREE.FontLoader();
loader.load('B Zar_Regular.js', function (font) {
    var textGeo = new THREE.TextGeometry('سلام!', {
        font: font,
        size: 1,
        height: 0.05,
        curveSegments: 12,
    });
    var material = new THREE.MeshNormalMaterial();
    var textMesh = new THREE.Mesh(textGeo, material);
    textMesh.position.x = 15;
    scene.add(textMesh);
});
```

I was expecting to see سلام! but the output was:

letters are separated and order of characters is reversed mistakenly. After all it seems threejs do not support rtl languages. Am I right or I missed something? Is there any workaround as a quick solution? Thanks.

答:
This is a complex problem. Ligatures, the calligraphic strokes which connect letters, most familiar to western readers as a component of cursive English, is not optional in Arabic. Ligatures are intrinsic to the language, changing the meaning and formality of the text. The font.js class is designed to take each letter (glyph) one by one and convert it to a shape path. This doesn't work in Arabic because joining rules are complex depending on specific letter combinations.

I do not believe there is a fix that can be put in place in three.js. Although I would be anxious to know what the potential solution is as mentioned by O.P.

It may be possible to convert isolated letters to final Arabic ligatured forms via this script, or maybe this one among others. The final presentation forms  might then be sent to Three.js for display so that the ligature joins are handled already and three.js receives the final ligatured forms rather than the isolated glyphs.

It may be a simpler task to convert text to svg paths using a text to path converter and then using the SVGLoader.js in three.js to load the letters as paths for extrusion. But this would have to be tested to ensure the conversion of text to a path handles Arabic at all and then if it does, the ligature joins will also need to be checked for accuracy.

Body:
I need to show some text in Persian/Arabic language. I loaded a font including characters and I used TextGeometry to create a text on the scene:

var loader = new THREE.FontLoader();
loader.load('B Zar_Regular.js', function (font) {
    var textGeo = new THREE.TextGeometry('سلام!', {
        font: font,
        size: 1,
        height: 0.05,
        curveSegments: 12,
    });
    var material = new THREE.MeshNormalMaterial();
    var textMesh = new THREE.Mesh(textGeo, material);
    textMesh.position.x = 15;
    scene.add(textMesh);
});

I was expecting to see سلام! but the output was:

letters are separated and order of characters is reversed mistakenly. After all it seems threejs do not support rtl languages. Am I right or I missed something? Is there any workaround as a quick solution? Thanks.