问:
Android Listview search filter (list empty after first search)
I am doing a search filter using filterable. I manage to get the search result when I search by keyword but the listview is empty after the first search. I want it to show all the data when the user input is null.

This is the code I edited. Now I cannot get any search result. Any idea which part still wrong?

```<code>  public class ProductListAdapter extends BaseAdapter implements Filterable {

    private Context context;
    private int layout;
    private ArrayList<Booth> productList= new ArrayList<>();
    private ArrayList<Booth> tempList = new ArrayList<>();
    private ValueFilter mFilter = new ValueFilter();

    public ProductListAdapter(Context context, int layout, ArrayList<Booth> productList) {
        this.context = context;
        this.layout = layout;
        this.productList = productList;
        this.tempList = productList;

    }

    @Override
    public int getCount() {

        return tempList.size();
    }

    public void addItems(ArrayList<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {

        return tempList.get(position);
    }

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

    @Override
    public View getView(
            int position, View view, ViewGroup viewGroup) {
        Typeface face_02 = Typeface.createFromAsset(context.getAssets(), "customfont/grb.otf");
        ViewHolder holder = new ViewHolder();

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(layout, null);
            holder.Boothname = (TextView) view.findViewById(R.id.Boothname);
            holder.Rating = (TextView) view.findViewById(R.id.Rating);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        Booth product = productList.get(position);

        holder.Boothname.setText(product.getBoothName());
        holder.Rating.setText(product.getRating());
        holder.Rating.setTypeface(face_02);
        holder.Boothname.setTypeface(face_02);

        return view;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ValueFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                    if ((productList.get(i).getBoothName().toLowerCase())
                            .contains(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList.get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;

            } else {
                results.count = productList.size();
                results.values = productList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tempList = (ArrayList<Booth>) results.values;
            notifyDataSetChanged();
        }
    }
        class ViewHolder {
            TextView Boothname, Rating;

        }
}
</code>```

答:
This is happened because you are updating your original list when user search anything.You have to use tempList which is hold temporary data and used to show search result,it is also used to shows list initially.And ProductList contains original list and it is used to compare with the search string.

Initialize variable

```<code>private List<Booth> productList=new ArrayList<>(); //you have already done this,this contains original list
private List<Booth> tempList=new ArrayList<>(); //add this one is to show search result
</code>```

Method for the add data should be like this:

```<code>public void addItems(List<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
}
</code>```

Method for the remove data should be like this:

```<code>  public void removeItems(){
        productList.clear();
        tempList.clear();
    }
</code>```

getItem and getCount method should be like this:

```<code>  @Override
    public int getCount() {
        return tempList.size();
    }
    @Override
    public Booth getItem(int position) {
        return tempList.get(position);
}
</code>```

ValueFilter should be like this:

```<code>        private class ValueFilter extends Filter {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                //filter list as a local variable
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                      if ((productList.get(i).getBoothName().toLowerCase())
                            .startsWith(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList .get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;
                Log.e("VALUES", results.values.toString());
            } else {

                results.count = productList.size();
                results.values = productList;
            }
return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                tempList = (ArrayList<Booth>) results.values;
                notifyDataSetChanged();
            }
    }
</code>```

Body:
I am doing a search filter using filterable. I manage to get the search result when I search by keyword but the listview is empty after the first search. I want it to show all the data when the user input is null.

This is the code I edited. Now I cannot get any search result. Any idea which part still wrong?

  public class ProductListAdapter extends BaseAdapter implements Filterable {

    private Context context;
    private int layout;
    private ArrayList<Booth> productList= new ArrayList<>();
    private ArrayList<Booth> tempList = new ArrayList<>();
    private ValueFilter mFilter = new ValueFilter();

    public ProductListAdapter(Context context, int layout, ArrayList<Booth> productList) {
        this.context = context;
        this.layout = layout;
        this.productList = productList;
        this.tempList = productList;

    }

    @Override
    public int getCount() {

        return tempList.size();
    }

    public void addItems(ArrayList<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {

        return tempList.get(position);
    }

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

    @Override
    public View getView(
            int position, View view, ViewGroup viewGroup) {
        Typeface face_02 = Typeface.createFromAsset(context.getAssets(), "customfont/grb.otf");
        ViewHolder holder = new ViewHolder();

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(layout, null);
            holder.Boothname = (TextView) view.findViewById(R.id.Boothname);
            holder.Rating = (TextView) view.findViewById(R.id.Rating);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        Booth product = productList.get(position);

        holder.Boothname.setText(product.getBoothName());
        holder.Rating.setText(product.getRating());
        holder.Rating.setTypeface(face_02);
        holder.Boothname.setTypeface(face_02);

        return view;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ValueFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                    if ((productList.get(i).getBoothName().toLowerCase())
                            .contains(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList.get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;

            } else {
                results.count = productList.size();
                results.values = productList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tempList = (ArrayList<Booth>) results.values;
            notifyDataSetChanged();
        }
    }
        class ViewHolder {
            TextView Boothname, Rating;

        }
}

Body:
This is happened because you are updating your original list when user search anything.You have to use tempList which is hold temporary data and used to show search result,it is also used to shows list initially.And ProductList contains original list and it is used to compare with the search string.

Initialize variable

private List<Booth> productList=new ArrayList<>(); //you have already done this,this contains original list
private List<Booth> tempList=new ArrayList<>(); //add this one is to show search result

Method for the add data should be like this:

public void addItems(List<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
}

Method for the remove data should be like this:

  public void removeItems(){
        productList.clear();
        tempList.clear();
    }

getItem and getCount method should be like this:

  @Override
    public int getCount() {
        return tempList.size();
    }
    @Override
    public Booth getItem(int position) {
        return tempList.get(position);
}

ValueFilter should be like this:

        private class ValueFilter extends Filter {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                //filter list as a local variable
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                      if ((productList.get(i).getBoothName().toLowerCase())
                            .startsWith(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList .get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;
                Log.e("VALUES", results.values.toString());
            } else {

                results.count = productList.size();
                results.values = productList;
            }
return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                tempList = (ArrayList<Booth>) results.values;
                notifyDataSetChanged();
            }
    }


来源: stackexchange

问:
How to enable subversion merge tracking
How do I enable svn client to start saving svn:mergeinfo property.

My client is v1.6.5 and the server runs 1.5.2.

答:
Server version 1.5 should be able to save mergeinfo data.

Perhaps your repository was created with much older version. Try:

```<code>svnadmin upgrade /path/to/repository
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to enable subversion merge tracking

Body:
Server version 1.5 should be able to save mergeinfo data.

Perhaps your repository was created with much older version. Try:

svnadmin upgrade /path/to/repository


问:
How to Add Content Page to Segment Control in IOS Xamarin.Forms
I have used Segmented Control in my application. I don't know how to add two content pages to Segment control like a tabbed page. I have attached the sample file. Please give any suggestion Link for Sample Application

Sample Code:

```<code>public partial class SamplePage : ContentPage
{

    SegmentedControl segControl;
    SegmentedControlOption optionOne;
    SegmentedControlOption optionTwo;

    public SamplePage()
    {
        segControl = new SegmentedControl();
        optionOne = new SegmentedControlOption();
        optionTwo = new SegmentedControlOption();

        optionOne.Text = "One";
        optionTwo.Text = "Two";

        segControl.Children.Add(optionOne);
        segControl.Children.Add(optionTwo);

        var stack = new StackLayout()
        {
            VerticalOptions = LayoutOptions.StartAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Children = { segControl }
        };

        this.Content = stack;

    }
}
</code>```

ScreenShot Attached

答:
Just some suggestions and explanations.

We can't put a ContentPage inside another ContentPage

It's better to use ContentView instead of ContentPage

Grid is more recommended in this scenario , since it fills with the whole Screen.

Use ValueChanged event to change the view dynamically.

Code :

Page

```<code>public partial class SegmentedAppPage : ContentPage
{
    SegmentedControl segControl;
    SegmentedControlOption scOptionOne;
    SegmentedControlOption scOptionTwo;

    Grid grid;

    View1 view1 = new View1();
    View2 view2 = new View2();

    public SegmentedAppPage()
    {
        InitializeComponent();

        segControl = new SegmentedControl();
        segControl.SelectedValue = "One";
        scOptionOne = new SegmentedControlOption();
        scOptionTwo = new SegmentedControlOption();

        scOptionOne.Text = "One";
        scOptionTwo.Text = "Two";

        segControl.Children.Add(scOptionOne);
        segControl.Children.Add(scOptionTwo);

        grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

        grid.Children.Add(segControl, 0, 0);
        grid.Children.Add(view1, 0, 1);

        this.Content = grid;

        segControl.ValueChanged += SegControl_ValueChanged;
    }

    private void SegControl_ValueChanged(object sender, EventArgs e)
    {
        SegmentedControl control = sender as SegmentedControl;
        if(control.SelectedValue is "One")
        {
            grid.Children.Remove(view2);
            grid.Children.Add(view1,0,1);  //This line
        }
        else if (control.SelectedValue is "Two")
        {
            grid.Children.Remove(view1);
            grid.Children.Add(view2, 0, 1); //This line
        }
        this.Content = grid;
    }
}
</code>```

ContentView

```<code>public class View1 : ContentView
{
    public View1()
    {
        Content = new StackLayout
        {
            BackgroundColor = Color.Green,
            Children = {
                new Label { Text = "View1" }
            }
        };
    }
}
</code>```

To set default value on segmentedControl , modify code in SegmentedControlRenderers

```<code>protected override void OnElementChanged(ElementChangedEventArgs<SegmentedControl> e)
{
    base.OnElementChanged(e);

    var segmentedControl = new UISegmentedControl();

    for (var i = 0; i < e.NewElement.Children.Count; i++)
    {
        segmentedControl.InsertSegment(e.NewElement.Children[i].Text, i, false);
    }

    segmentedControl.ValueChanged += (sender, eventArgs) => {
        e.NewElement.SelectedValue = segmentedControl.TitleAt(segmentedControl.SelectedSegment);
    };
    segmentedControl.SelectedSegment = 0; // add this line
    SetNativeControl(segmentedControl);
}
</code>```

Test

ContentLicense: CC BY-SA 3.0

Body:
I have used Segmented Control in my application. I don't know how to add two content pages to Segment control like a tabbed page. I have attached the sample file. Please give any suggestion Link for Sample Application

Sample Code:

public partial class SamplePage : ContentPage
{

    SegmentedControl segControl;
    SegmentedControlOption optionOne;
    SegmentedControlOption optionTwo;

    public SamplePage()
    {
        segControl = new SegmentedControl();
        optionOne = new SegmentedControlOption();
        optionTwo = new SegmentedControlOption();

        optionOne.Text = "One";
        optionTwo.Text = "Two";

        segControl.Children.Add(optionOne);
        segControl.Children.Add(optionTwo);

        var stack = new StackLayout()
        {
            VerticalOptions = LayoutOptions.StartAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Children = { segControl }
        };

        this.Content = stack;

    }
}

ScreenShot Attached

Body:
Just some suggestions and explanations.

We can't put a ContentPage inside another ContentPage

It's better to use ContentView instead of ContentPage

Grid is more recommended in this scenario , since it fills with the whole Screen.

Use ValueChanged event to change the view dynamically.

Code :

Page

public partial class SegmentedAppPage : ContentPage
{
    SegmentedControl segControl;
    SegmentedControlOption scOptionOne;
    SegmentedControlOption scOptionTwo;

    Grid grid;

    View1 view1 = new View1();
    View2 view2 = new View2();

    public SegmentedAppPage()
    {
        InitializeComponent();

        segControl = new SegmentedControl();
        segControl.SelectedValue = "One";
        scOptionOne = new SegmentedControlOption();
        scOptionTwo = new SegmentedControlOption();

        scOptionOne.Text = "One";
        scOptionTwo.Text = "Two";

        segControl.Children.Add(scOptionOne);
        segControl.Children.Add(scOptionTwo);

        grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

        grid.Children.Add(segControl, 0, 0);
        grid.Children.Add(view1, 0, 1);

        this.Content = grid;

        segControl.ValueChanged += SegControl_ValueChanged;
    }

    private void SegControl_ValueChanged(object sender, EventArgs e)
    {
        SegmentedControl control = sender as SegmentedControl;
        if(control.SelectedValue is "One")
        {
            grid.Children.Remove(view2);
            grid.Children.Add(view1,0,1);  //This line
        }
        else if (control.SelectedValue is "Two")
        {
            grid.Children.Remove(view1);
            grid.Children.Add(view2, 0, 1); //This line
        }
        this.Content = grid;
    }
}

ContentView

public class View1 : ContentView
{
    public View1()
    {
        Content = new StackLayout
        {
            BackgroundColor = Color.Green,
            Children = {
                new Label { Text = "View1" }
            }
        };
    }
}

To set default value on segmentedControl , modify code in SegmentedControlRenderers

protected override void OnElementChanged(ElementChangedEventArgs<SegmentedControl> e)
{
    base.OnElementChanged(e);

    var segmentedControl = new UISegmentedControl();

    for (var i = 0; i < e.NewElement.Children.Count; i++)
    {
        segmentedControl.InsertSegment(e.NewElement.Children[i].Text, i, false);
    }

    segmentedControl.ValueChanged += (sender, eventArgs) => {
        e.NewElement.SelectedValue = segmentedControl.TitleAt(segmentedControl.SelectedSegment);
    };
    segmentedControl.SelectedSegment = 0; // add this line
    SetNativeControl(segmentedControl);
}

Test


问:
Bash-shell grammar issue about Ternary operator and printf function
```<code>cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10
</code>```

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file
</code>```

The output as below:

```<code>E2.*$

E2.*$
</code>```

but I want to print E20128 & E20138, So I verified my code with deleting " "

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file
</code>```

Then it comes the error:

```<code>awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error
</code>```

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

答:
After think for a while ,below works:     </p>

```<code>awk '{printf("%s\n",($NF~/E2[0-9]*$/? $NF : NULL))}' file
</code>```

Body:
cat file
chenghuanghuijia jidianzhong 100 E20128
pannybudaqiu gujihuihenwan -1
shuijiao buxihuan 20 E20138
huijiakan babamama 10

I want get the result that when the line contains E2[0-9]*$ , the end of the line will be printed, if the line not contain E2[0-9]*$, the end of the line will be printed NULL or \n.

Here is my code:

awk '{printf("%s\n",($NF~/E2[0-9]*$/? "E2.*$" : NULL))}' file

The output as below:

E2.*$

E2.*$

but I want to print E20128 & E20138, So I verified my code with deleting " "

awk '{printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}' file

Then it comes the error:

awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                    ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                               ^ syntax error
awk: cmd. line:1: {printf("%s\n",($NF~/E2[0-9]*$/? E2.*$ : NULL))}
awk: cmd. line:1:                                                ^ syntax error

So I think is the grammar issue of Ternary operator( _?x:y) or printf function.
please support me .

Body:
After think for a while ,below works:

awk '{printf("%s\n",($NF~/E2[0-9]*$/? $NF : NULL))}' file


问:
How to remove some character from string using PHP
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);
</code>```

Expected Output

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);
</code>```

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
<?php
$datArr=array(array("name"=>"Ram","id"=>1,"date"=>"12/04/2017 05:31:57 AM"),array("name"=>"Rahim","id"=>5,"date"=>"12/03/2017 12:31:57 PM"),array("name"=>"Raj","id"=>4,"date"=>"12/04/2017 05:31:57 PM"));
echo "<pre>";
print_r($datArr);

$a = array();
foreach ($datArr as &$str) {
    $str = str_replace('PM', ' ', $str);
    $str = str_replace('AM', ' ', $str);
    $a[]=$str;
}
print_r($a);
?>

check fiddle


问:
how to count number values' frequency using python pandas

I want to count the frequency of number values of csv data in my computer.
I tried this code:

```<code>import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)
</code>```

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

答:
groupby together with count does not give the frequency of unique values.

Try using size, with group, to get unique values with their frequencies

```<code>Dataframe.groupby('column_name').size()
</code>```

For faster computation and if your dataframe has values with same type,
You can use;

```<code>index, counts = np.unique(df.values,return_counts=True)
</code>```

If your values are all integers, then try using np.bincount()

Body:
I want to count the frequency of number values of csv data in my computer.
I tried this code:

import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

Body:
groupby together with count does not give the frequency of unique values.

Try using size, with group, to get unique values with their frequencies

Dataframe.groupby('column_name').size()

For faster computation and if your dataframe has values with same type,
You can use;

index, counts = np.unique(df.values,return_counts=True)

If your values are all integers, then try using np.bincount()


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
Off topic, do you know where you got that phrase, "the a-ha moment": is it from a book, from someone else, or is it original? Because I think I remember someone's using that same phrase, when I was studying OOP and C++, online in about 1994.

Anyway: your question.

Like yours, my programming experience predates OOP: I did some Basic programming too, and, C.

It was, in a way, as you said, "a very linear approach to coding".

I was programmng professionally, in C, when I started to learn C++. So in terms of being able to "sit down, open up VS2008, and start coding", I was kind of already doing that, every day: I was sitting down and coding, in C.

It was event-driven programming: the software was reacting to events, to input: from the network, from various devices, from the UI ... so in that way, even this C code wasn't at all as linear as the kind of imperative Basic code ("read a keystroke, write to the screen") that we'd use to write.

So that's one thing: event-driven programming. Event-driven programming is not linear, it can be kind of difficult to conceptualize: a bunch of event-handlers, some independent, some interacting with each in a non-fixed sequence. Event-driven programming is not OOP (you can write event-driven programs in C), but one of the things that OOP is known to be good at is GUIs and event-driven programming. I suggest that OOP doesn't necessarily make it easy: the problem can be inherently difficult, and OOP makes it easier, not easy.

So that's another thing: if you can do it at all, then you're doing something right. Don't expect that everything will always be easy. A good solution might make the solution look easy and obvious, but developing a good solutions to large, difficult problems isn't easy, and we might thank OOP for making it possible to do at all.

Anyway, back to my story: I was coding in C. I learned incrementally to use C++, for example:

I have a bunch of data (structs), and a bunch of functions which operate on that data ... put the functions in the same structs as the data which they operate on, and "functions" become "methods"

Now that data has associated methods which are supposed to act on that data, make the data private so that other methods can't touch it directly ... encapsulation and/or information hiding

Now that I have well-defined classes (some of which already contain each other as data members), start using inheritance to implement similarities and dissimilarities between different types

For me, one of the "a-ha" moments was that we were driving drivers for different kinds of fax device, which each had different low-level APIs. Using OOP we could write ...

A simple, abstract class, which declared the simple, high-level API (like, sendFax, receiveFax, cancel, etc.) which we wanted all devices to support

Subclasses, which used the API of the specific hardware to implement the abstract API inherited from the abstract base class.

I've just remembered something else. When I was learning C++, I read various books:

Thinking in C++ to learn to read the syntax of C++

Effective C++ to learn various canonical tactical mistakes to avoid when writing C++

Having read these, and with about 6 months' practice, I could use C++ as a better C.

One of the next books I read though was Design Patterns by the Gang of Four: and reading that book was an "a-ha" moment for me, it made me think, "if those other books showed me how to write in an object-oriented programming language, this book is showing me why I would want to."

So, there's a recommendation: read Design Patterns.

I've been talking about C++ and so on because that was the era in which I had my first a-has. I think it's relevent ... knowing OOP and C++ well, it took me less than a week to "sit down, open up VS2008, and start coding" in C# when that came along.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: ChrisW


问:
Loop synchronization deadlock
I've got the following classes in Java

```<code>public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}
</code>```

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help

答:
Your code can deadlock because you're not making any guarantee that the Cell threads will actually be in the wait() block at the time that notifyAll occurs.  The following is one sequence of events that could cause this problem:

Simulation starts all threads, and blocks waiting for a 0 value.

Each thread in sequence calls decrement, then counter.notifyAll, and then loses its time slice

The main thread has been notified, wakes up, finds the counter is at 0, calls sync.notifyAll, loops to the top, and waits indefinitely.

Each thread in sequence is given a time slice, advances to the wait(), and waits indefinitely.

Title: Loop synchronization deadlock

Body:
I've got the following classes in Java

public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help


问:
Multiple flexbox row with multiple scrollview in react native
I am trying to build a view with two rows in an iPhone using react native. I want to have two rows with equal height with scroll view. I am not able to find much documentation on this. I am the below code but it just renders on top of each other.</p>

```<code>      <View style={Styles.splitView}>
        <View style={Styles.splitViewLeft}>
          <ScrollView>
              <Text>Test1</Text>}
          </ScrollView>
        </View>
        <View style={Styles.splitViewRight}>
          <ScrollView>
            {
              <Text>Test2</Text>
            }
          </ScrollView>
        </View>
      </View>

      splitView: {
        flexDirection: 'row'
      },

      splitViewLeft: {
        flex: 3
      },

      splitViewRight: {
        flex: 2
      },
</code>```

答:
This does the work:

<View style={{flex: 1}}>
  <ScrollView style={{flex: 1, backgroundColor: 'red'}}>
    <Text>Test1</Text>
  </ScrollView>
  <ScrollView style={{flex: 1, backgroundColor: 'yellow'}}>
    <Text>Test2</Text>
  </ScrollView>
</View>
```

Apply style flex: 1 on both <ScrollView /> to make them equal height.

If you wrap it inside parent <View />, you have to apply flex: 1 to <ScrollView /> too.

Body:
I am trying to build a view with two rows in an iPhone using react native. I want to have two rows with equal height with scroll view. I am not able to find much documentation on this. I am the below code but it just renders on top of each other.

      <View style={Styles.splitView}>
        <View style={Styles.splitViewLeft}>
          <ScrollView>
              <Text>Test1</Text>}
          </ScrollView>
        </View>
        <View style={Styles.splitViewRight}>
          <ScrollView>
            {
              <Text>Test2</Text>
            }
          </ScrollView>
        </View>
      </View>

      splitView: {
        flexDirection: 'row'
      },

      splitViewLeft: {
        flex: 3
      },

      splitViewRight: {
        flex: 2
      },

Body:
This does the work:

<View style={{flex: 1}}>
  <ScrollView style={{flex: 1, backgroundColor: 'red'}}>
    <Text>Test1</Text>
  </ScrollView>
  <ScrollView style={{flex: 1, backgroundColor: 'yellow'}}>
    <Text>Test2</Text>
  </ScrollView>
</View>

Apply style flex: 1 on both <ScrollView /> to make them equal height.

If you wrap it inside parent <View />, you have to apply flex: 1 to <ScrollView /> too.


问:
numpy - matrix multiple 3x3 and 100x100x3 arrays?
I have the following:

```<code>import numpy as np

XYZ_to_sRGB_mat_D50 = np.asarray([
    [3.1338561, -1.6168667, -0.4906146],
    [-0.9787684, 1.9161415, 0.0334540],
    [0.0719453, -0.2289914, 1.4052427],
])

XYZ_1 = np.asarray([0.25, 0.4, 0.1])
XYZ_2 = np.random.rand(100,100,3)

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) # valid operation
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2) # makes no sense mathematically
</code>```

How do I perform the same operation on XYZ_2 that I would on XYZ_2?  Do I somehow reshape the array first?

答:
You probably simply want this:

```<code>XYZ_2.dot(XYZ_to_sRGB_mat_D50.T)
</code>```

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) is equivalent to XYZ_1.dot(XYZ_to_sRGB_mat_D50.T), you can then simply broadcast the operation to a 100 x 100 x 3 matrix.

Body:
I have the following:

import numpy as np

XYZ_to_sRGB_mat_D50 = np.asarray([
    [3.1338561, -1.6168667, -0.4906146],
    [-0.9787684, 1.9161415, 0.0334540],
    [0.0719453, -0.2289914, 1.4052427],
])

XYZ_1 = np.asarray([0.25, 0.4, 0.1])
XYZ_2 = np.random.rand(100,100,3)

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) # valid operation
np.matmul(XYZ_to_sRGB_mat_D50, XYZ_2) # makes no sense mathematically

How do I perform the same operation on XYZ_2 that I would on XYZ_2?  Do I somehow reshape the array first?

Body:
You probably simply want this:

XYZ_2.dot(XYZ_to_sRGB_mat_D50.T)

np.matmul(XYZ_to_sRGB_mat_D50, XYZ_1) is equivalent to XYZ_1.dot(XYZ_to_sRGB_mat_D50.T), you can then simply broadcast the operation to a 100 x 100 x 3 matrix.


问:
Elastic GeoHash Query - Aggregation Filter
I am trying to query an elastic index where the result of the query is a list of the geohashes with only one matching document.

I can get a simple list of all geo hashes and their document counts using the following:

{
    "size" : 0,
    "aggregations" : {
        "boundingbox" : {
            "filter" : {
                "geo_bounding_box" : {
                    "location" : {
                        "top_left" : "34.5, -118.9",
                        "bottom_right" : "33.3, -116."
                    }
                }
            },
            "aggregations":{
                "grid" : {
                    "geohash_grid" : {
                        "field": "location",
                        "precision": 4
                    }
                }
            }
        }
    }
}

However I can't work out the correct syntax to filter the query, the closest I can get are below:

This fails with 503 org.elasticsearch.search.aggregations.bucket.filter.InternalFilter cannot be cast to org.elasticsearch.search.aggregations.InternalMultiBucketAggregation

"aggregations":{
    "grid" : {
        "geohash_grid" : {
            "field": "location",
            "precision": 4
        }
    },
    "grid_bucket_filter" : {
        "bucket_selector" : {
            "buckets_path" :{
                "docCount" : "grid" //Also tried `"docCount" : "doc_count"`
            },
            "script" : "params.docCount == 1"
        }
    }
}

This fails with 400 No aggregation found for path [doc_count]

"aggregations":{
    "grid" : {
        "geohash_grid" : {
            "field": "location",
            "precision": 4
        }
    },
    "grid_bucket_filter" : {
        "bucket_selector" : {
            "buckets_path" :{
                "docCount" : "doc_count"
            },
            "script" : "params.docCount > 1"
        }
    }
}

How can I filter based on the doc_count in a geohash grid?

答:
You need to do it like this, i.e. the bucket selector pipeline shall be specified as a sub-aggregation of the geohash_grid one. Plus you need to use _count instead of doc_count(see here):

```<code>{
  "aggregations": {
    "grid": {
      "geohash_grid": {
        "field": "location",
        "precision": 4
      },
      "aggs": {
        "grid_bucket_filter": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount > 1"
          }
        }
      }
    }
  }
}
</code>```

Body:
You need to do it like this, i.e. the bucket selector pipeline shall be specified as a sub-aggregation of the geohash_grid one. Plus you need to use _count instead of doc_count(see here):

{
  "aggregations": {
    "grid": {
      "geohash_grid": {
        "field": "location",
        "precision": 4
      },
      "aggs": {
        "grid_bucket_filter": {
          "bucket_selector": {
            "buckets_path": {
              "docCount": "_count"
            },
            "script": "params.docCount > 1"
          }
        }
      }
    }
  }
}


问:
UITextField placeholder text: adjust to fit
I have UITextField with longer text in it set as placeholder. What I want is for this placeholder text to adjust its font size when the width of field is too small.

I already tried this solution described in other posts (programmatically and in IB)

```<code>self.fieldTest.adjustsFontSizeToFitWidth = true
self.fieldTest.minimumFontSize = 10.0
</code>```

What am I missing here?

答:
Swift

Feel free to improve the extension - pretty sure there is a more elegant way to iterate over the subviews.

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    tfCountryCode.allSubviewsOfClass(UILabel.self).forEach {
        $0.adjustsFontSizeToFitWidth = true
        $0.minimumScaleFactor = 0.5
    }
}

extension UIView {
    func allSubviewsOfClass<K: UIView>(_ clazz: K.Type) -> [K] {
        var matches = [K]()
        if subviews.isEmpty { return matches }
        matches.append(contentsOf: subviews.filter { $0 is K } as! [K])
        let matchesInSubviews = subviews.flatMap { return $0.allSubviewsOfClass(clazz) }
        matches.append(contentsOf: matchesInSubviews.flatMap { $0 })
        return matches
    }
}
</code>```

Body:
I have UITextField with longer text in it set as placeholder. What I want is for this placeholder text to adjust its font size when the width of field is too small.

I already tried this solution described in other posts (programmatically and in IB)

self.fieldTest.adjustsFontSizeToFitWidth = true
self.fieldTest.minimumFontSize = 10.0

What am I missing here?

Body:
Swift

Feel free to improve the extension - pretty sure there is a more elegant way to iterate over the subviews.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    tfCountryCode.allSubviewsOfClass(UILabel.self).forEach {
        $0.adjustsFontSizeToFitWidth = true
        $0.minimumScaleFactor = 0.5
    }
}

extension UIView {
    func allSubviewsOfClass<K: UIView>(_ clazz: K.Type) -> [K] {
        var matches = [K]()
        if subviews.isEmpty { return matches }
        matches.append(contentsOf: subviews.filter { $0 is K } as! [K])
        let matchesInSubviews = subviews.flatMap { return $0.allSubviewsOfClass(clazz) }
        matches.append(contentsOf: matchesInSubviews.flatMap { $0 })
        return matches
    }
}


问:
Social media integration error?
I have integrated social media in my app, It was working properly but now Im having issues on Facebook, I recieved an error message App not setup:this app is still in development mode

Any Ideas what may have caused this error?

答:
Try this to make it public :

Go to your Facebook app's dashboard at
https://developers.facebook.com/apps/

Select the "Status and Review" tab

Set the toggle to "Yes"

Title: Social media integration error?


问:
Creating dictionary from space separated key=value string in Python
I have string as follows:

```<code>s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
</code>```

I want to convert in to a dictionary as follows:

```
key  | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace
```

How do I do this in Python?

答:
The shlex class makes it easy to write
  lexical analyzers for simple syntaxes
  resembling that of the Unix shell.
  This will often be useful for writing
  minilanguages, (for example, in run
  control files for Python applications)
  or for parsing quoted strings.

```<code>import shlex

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

print dict(token.split('=') for token in shlex.split(s))
</code>```

Body:
I have string as follows:

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

I want to convert in to a dictionary as follows:

key  | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace

How do I do this in Python?

Body:
The shlex class makes it easy to write
  lexical analyzers for simple syntaxes
  resembling that of the Unix shell.
  This will often be useful for writing
  minilanguages, (for example, in run
  control files for Python applications)
  or for parsing quoted strings.

import shlex

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

print dict(token.split('=') for token in shlex.split(s))


问:
Still "Please try running this command again as root/Administrator."
Windows 10, Git Bash (as Administator), trying to: npm install --save-dev webpack-stream and got this:

```<code>npm ERR! path D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall lstat
npm ERR! Error: EPERM: operation not permitted, lstat 'D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules'
npm ERR!  { Error: EPERM: operation not permitted, lstat 'D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules'
npm ERR!   stack: 'Error: EPERM: operation not permitted, lstat \'D:\\Projects\\SomeProject\\frontend\\node_modules\\fsevents\\node_modules\\getpass\\node_modules\'',
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'lstat',
npm ERR!   path: 'D:\\Projects\\SomeProject\\frontend\\node_modules\\fsevents\\node_modules\\getpass\\node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2017-12-05T05_24_31_143Z-debug.log
</code>```

I have trying to:

```<code>npm cache verify
</code>```

and:

```<code>npm cache clean -f
</code>```

No results.

Trying turn off antivirus - not results. Trying to run cmd as administrator and then: cd project-folder -> npm install --save-dev webpack-stream - no results.

```<code>npm -v
5.5.1

node -v
v8.9.1
</code>```

Is it possible to resolve my problem?

答:
Try this

```<code>npm config set unsafe-perm=true
</code>```

source

Body:
Windows 10, Git Bash (as Administator), trying to: npm install --save-dev webpack-stream and got this:

npm ERR! path D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall lstat
npm ERR! Error: EPERM: operation not permitted, lstat 'D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules'
npm ERR!  { Error: EPERM: operation not permitted, lstat 'D:\Projects\SomeProject\frontend\node_modules\fsevents\node_modules\getpass\node_modules'
npm ERR!   stack: 'Error: EPERM: operation not permitted, lstat \'D:\\Projects\\SomeProject\\frontend\\node_modules\\fsevents\\node_modules\\getpass\\node_modules\'',
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'lstat',
npm ERR!   path: 'D:\\Projects\\SomeProject\\frontend\\node_modules\\fsevents\\node_modules\\getpass\\node_modules' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2017-12-05T05_24_31_143Z-debug.log

I have trying to:

npm cache verify

and:

npm cache clean -f

No results.

Trying turn off antivirus - not results. Trying to run cmd as administrator and then: cd project-folder -> npm install --save-dev webpack-stream - no results.

npm -v
5.5.1

node -v
v8.9.1

Is it possible to resolve my problem?

Body:
Try this

npm config set unsafe-perm=true

source


问:
Replacement for GL_SEPARATE_SPECULAR_COLOR and GL_LIGHT_MODEL_COLOR_CONTROL OpenGL
I'm trying to understand some code while I learn OpenGL. I came an across the use of GL_LIGHT_MODEL_COLOR_CONTROL and GL_SEPARATE_SPECULAR_COLOR while trying to compile an open source file but it say's they weren't declared in the scope. I did some searching and found out that they were removed in GL 3.1. I wanted to know what would be a good replacement to use instead of them in this code and what they were meant for.</p>

答:
The replacement for them is called "you have to write shaders now". That is, you write the lighting code yourself that gets executed on the GPU.

In fixed-function lighting model (which again, no longer exists in core profile OpenGL), the diffuse color and the specular color for lights are normally added together per-vertex. So the texture environment only sees a single per-vertex color.

Separating the specular color means that the specular and diffuse colors from the light are separated. So the texture environment sees a pair of colors: one for the diffuse lighting and one for the specular.

The purpose of this is to allow the diffuse lighting to be multiplied by the texture color, then adding the specular color to the result of that. That is, it allows the equation (T * Diffuse) + Specular to work. If you don't separate the specular color, then what you have is T * (Diffuse + Specular). This means that the texture color affects the specular highlight as well as the diffuse value. While this is sometimes what you want, you will more often want them to be separate, for the specular highlight to be tinted based on a separate color from the diffuse lighting.


问:
Python Flask "send_file()" method TypeError
I'm trying to read an image that the user uploads and then display the image back to them. I want to do this without saving the image file that is uploaded.

I have code like this:

```<code>from flask import Flask, redirect, render_template, request, url_for, send_file
from PIL import Image, ImageDraw
from io import BytesIO

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        img = Image.open(request.files['file'].stream)
        byte_io = BytesIO()
        img.save(byte_io, 'PNG')
        byte_io.seek(0)
        return send_file(byte_io, mimetype='image/png')

if __name__ == '__main__':
    app.run(debug=1)
</code>```

It produces this error:

TypeError: send_file() got an unexpected keyword argument 'mimetype'

I've tried replacing mimetype with other valid parameters and it will just give the same error but with the name of the new parameter. So I think the problem is with my bytes_io.

UPDATE:

To clarify, by send_file() I'm referring to the built in flask.send_file() method:

答:
From flask document

The mimetype guessing requires a filename or an attachment_filename to be provided.

...

mimetype – the mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised.

So, you should provide that like this

```<code>return send_file(
    io.BytesIO(obj.logo.read()),
    download_name='logo.png',
    mimetype='image/png'
)
</code>```

This sample code should run normally,

```<code>from flask import Flask, request, send_file
app = Flask(__name__)

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename)

if __name__ == '__main__':
    app.run()
</code>```

If you've still got same error, maybe it's an environment problem. You can check your package version using pip freeze.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to read an image that the user uploads and then display the image back to them. I want to do this without saving the image file that is uploaded.

I have code like this:

from flask import Flask, redirect, render_template, request, url_for, send_file
from PIL import Image, ImageDraw
from io import BytesIO

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        img = Image.open(request.files['file'].stream)
        byte_io = BytesIO()
        img.save(byte_io, 'PNG')
        byte_io.seek(0)
        return send_file(byte_io, mimetype='image/png')

if __name__ == '__main__':
    app.run(debug=1)

It produces this error:

TypeError: send_file() got an unexpected keyword argument 'mimetype'

I've tried replacing mimetype with other valid parameters and it will just give the same error but with the name of the new parameter. So I think the problem is with my bytes_io.

UPDATE:

To clarify, by send_file() I'm referring to the built in flask.send_file() method:

Body:
From flask document

The mimetype guessing requires a filename or an attachment_filename to be provided.

...

mimetype – the mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised.

So, you should provide that like this

return send_file(
    io.BytesIO(obj.logo.read()),
    download_name='logo.png',
    mimetype='image/png'
)

This sample code should run normally,

from flask import Flask, request, send_file
app = Flask(__name__)

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename)

if __name__ == '__main__':
    app.run()

If you've still got same error, maybe it's an environment problem. You can check your package version using pip freeze.


问:
Python pandas calculate business days and business hours on 2 date fields of pandas dataframe
I have work hours for 7 AM to 5 PM Mon - Fri. I want to calculate the no of business days and hours from 2 columns start date and end date.

From

```<code>Sno start date      end date
1   4/6/2017 23:18  6/6/2017 21:23
2   4/6/2017 16:40  5/6/2017 2:52
3   5/6/2017 0:10   5/6/2017 4:10
4   5/6/2017 0:37   5/6/2017 7:16
5   5/6/2017 2:02   5/6/2017 10:48
</code>```

To

```<code>Sno start date      end date        Bus Days    Bus hours
1   4/6/2017 23:18  6/6/2017 21:23  1           10:00
2   4/6/2017 16:40  5/6/2017 2:52   0           0:20
3   5/6/2017 0:10   5/6/2017 4:10   0           0
4   5/6/2017 0:37   5/6/2017 7:16   0           0:16
5   5/6/2017 2:02   5/6/2017 10:48  0           3:48
</code>```

I tried the below but got several errors

```<code>from BusinessHours import BusinessHours as bh
df['bhours'] = (bh(df['start date'] , df['end date'] , worktiming=[7 , 17] , weekends=[6,7]).gethours()).astype('timedelta64[D]')

AttributeError: 'Series' object has no attribute 'days'
</code>```

Then I tried another solution

```<code>df['bhours'] = len(pd.bdate_range(df['start date'] , df['end date'])).astype('timedelta64[D]')
TypeError: Cannot convert input [0       2017-04-06 18:52:00

df['bdays'] = (np.busday_count(df['start date'] , df['end date'])).astype('timedelta64[D]')
TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[ns]') to dtype('<M8[D]') according to the rule 'safe'
</code>```

Please help in fixing this issue.

答:
I wrote this method as I found the business hours package to have a syntax error. it should work fine.</p>

```<code>import pandas as pd
import datetime
import numpy as np

df = pd.read_excel("/home/yasin/Documents/SametimeFileTransfers/final.xlsx")

df['sys_created_on'] = pd.to_datetime(df['sys_created_on'] )
df['resolved_at'] = pd.to_datetime(df['resolved_at'])

x = pd.to_datetime('2017-06-15 17:39')
y = pd.to_datetime('2017-06-15 18:00')

weekend = [6 ,7] # --> This is just for referral
time = [7 , 17] # --> This is just for referral
weekdays = [1 ,2, 3, 4 ,5]

def gethours(sdate , edate):
    #Setting the start date
    if sdate.isoweekday() == 6:
        sdate += datetime.timedelta(days=2)
        sdate = sdate.replace(hour = 7 , minute=0)
    elif sdate.isoweekday() == 7:
        sdate += datetime.timedelta(days=1)
        sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour > 17)):
        sdate += datetime.timedelta(days=1)
        if sdate.isoweekday() == 6:
            sdate += datetime.timedelta(days=2)
            sdate = sdate.replace(hour = 7 , minute=0)
        else:
            sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour == 17) & (sdate.minute > 0)):
        sdate += datetime.timedelta(days=1)
        if sdate.isoweekday() == 6:
            sdate += datetime.timedelta(days=2)
            sdate = sdate.replace(hour = 7 , minute=0)
        else:
            sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour < 7)):
        sdate = sdate.replace(hour = 7 , minute=0)
    else:
        sdate
    #Setting the end date
    if edate.isoweekday() == 6:
        edate += datetime.timedelta(days=2)
        edate = edate.replace(hour = 7 , minute=0)
    elif edate.isoweekday() == 7:
        edate += datetime.timedelta(days=1)
        edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour > 17)):
        edate += datetime.timedelta(days=1)
        if edate.isoweekday() == 6:
            edate += datetime.timedelta(days=2)
            edate = edate.replace(hour = 7 , minute=0)
        else:
            edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour == 17) & (edate.minute > 0) ):
        edate += datetime.timedelta(days=1)
        if edate.isoweekday() == 6:
            edate += datetime.timedelta(days=2)
            edate = edate.replace(hour = 7 , minute=0)
        else:
            edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour < 7)):
        edate = edate.replace(hour = 7 , minute=0)

    else:
        edate
    #Appproximating the bus days
    try:
        days = np.busday_count(sdate , edate)
    #Calculating the hours
        if days == 0:
            sec = (edate - sdate)
            sec = sec.total_seconds()
            hrs = sec // 3600
        elif days > 0:
            days = days - 1
            hrs1 = days * 10
            tdate1 = sdate.replace(hour = 17 , minute=0)
            sec1 = (tdate1 - sdate)
            sec1 = sec1.total_seconds()
            hrss = sec1 // 3600
            tdate2 = edate.replace(hour = 7 , minute=0)
            sec2 = edate - tdate2
            sec2 = sec2.total_seconds()
            hrse = sec2 // 3600
            hrs = hrs1 + hrss + hrse
    except ValueError:
        hrs = None
    if hrs is None:
        hrs = 0
    return hrs
</code>```

Body:
I have work hours for 7 AM to 5 PM Mon - Fri. I want to calculate the no of business days and hours from 2 columns start date and end date.

From

Sno start date      end date
1   4/6/2017 23:18  6/6/2017 21:23
2   4/6/2017 16:40  5/6/2017 2:52
3   5/6/2017 0:10   5/6/2017 4:10
4   5/6/2017 0:37   5/6/2017 7:16
5   5/6/2017 2:02   5/6/2017 10:48

To

Sno start date      end date        Bus Days    Bus hours
1   4/6/2017 23:18  6/6/2017 21:23  1           10:00
2   4/6/2017 16:40  5/6/2017 2:52   0           0:20
3   5/6/2017 0:10   5/6/2017 4:10   0           0
4   5/6/2017 0:37   5/6/2017 7:16   0           0:16
5   5/6/2017 2:02   5/6/2017 10:48  0           3:48

I tried the below but got several errors

from BusinessHours import BusinessHours as bh
df['bhours'] = (bh(df['start date'] , df['end date'] , worktiming=[7 , 17] , weekends=[6,7]).gethours()).astype('timedelta64[D]')

AttributeError: 'Series' object has no attribute 'days'

Then I tried another solution

df['bhours'] = len(pd.bdate_range(df['start date'] , df['end date'])).astype('timedelta64[D]')
TypeError: Cannot convert input [0       2017-04-06 18:52:00

df['bdays'] = (np.busday_count(df['start date'] , df['end date'])).astype('timedelta64[D]')
TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[ns]') to dtype('<M8[D]') according to the rule 'safe'

Please help in fixing this issue.

Body:
I wrote this method as I found the business hours package to have a syntax error. it should work fine.

import pandas as pd
import datetime
import numpy as np

df = pd.read_excel("/home/yasin/Documents/SametimeFileTransfers/final.xlsx")

df['sys_created_on'] = pd.to_datetime(df['sys_created_on'] )
df['resolved_at'] = pd.to_datetime(df['resolved_at'])

x = pd.to_datetime('2017-06-15 17:39')
y = pd.to_datetime('2017-06-15 18:00')

weekend = [6 ,7] # --> This is just for referral
time = [7 , 17] # --> This is just for referral
weekdays = [1 ,2, 3, 4 ,5]

def gethours(sdate , edate):
    #Setting the start date
    if sdate.isoweekday() == 6:
        sdate += datetime.timedelta(days=2)
        sdate = sdate.replace(hour = 7 , minute=0)
    elif sdate.isoweekday() == 7:
        sdate += datetime.timedelta(days=1)
        sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour > 17)):
        sdate += datetime.timedelta(days=1)
        if sdate.isoweekday() == 6:
            sdate += datetime.timedelta(days=2)
            sdate = sdate.replace(hour = 7 , minute=0)
        else:
            sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour == 17) & (sdate.minute > 0)):
        sdate += datetime.timedelta(days=1)
        if sdate.isoweekday() == 6:
            sdate += datetime.timedelta(days=2)
            sdate = sdate.replace(hour = 7 , minute=0)
        else:
            sdate = sdate.replace(hour = 7 , minute=0)
    elif ((sdate.isoweekday() in weekdays) & (sdate.hour < 7)):
        sdate = sdate.replace(hour = 7 , minute=0)
    else:
        sdate
    #Setting the end date
    if edate.isoweekday() == 6:
        edate += datetime.timedelta(days=2)
        edate = edate.replace(hour = 7 , minute=0)
    elif edate.isoweekday() == 7:
        edate += datetime.timedelta(days=1)
        edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour > 17)):
        edate += datetime.timedelta(days=1)
        if edate.isoweekday() == 6:
            edate += datetime.timedelta(days=2)
            edate = edate.replace(hour = 7 , minute=0)
        else:
            edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour == 17) & (edate.minute > 0) ):
        edate += datetime.timedelta(days=1)
        if edate.isoweekday() == 6:
            edate += datetime.timedelta(days=2)
            edate = edate.replace(hour = 7 , minute=0)
        else:
            edate = edate.replace(hour = 7 , minute=0)
    elif ((edate.isoweekday() in weekdays) & (edate.hour < 7)):
        edate = edate.replace(hour = 7 , minute=0)

    else:
        edate
    #Appproximating the bus days
    try:
        days = np.busday_count(sdate , edate)
    #Calculating the hours
        if days == 0:
            sec = (edate - sdate)
            sec = sec.total_seconds()
            hrs = sec // 3600
        elif days > 0:
            days = days - 1
            hrs1 = days * 10
            tdate1 = sdate.replace(hour = 17 , minute=0)
            sec1 = (tdate1 - sdate)
            sec1 = sec1.total_seconds()
            hrss = sec1 // 3600
            tdate2 = edate.replace(hour = 7 , minute=0)
            sec2 = edate - tdate2
            sec2 = sec2.total_seconds()
            hrse = sec2 // 3600
            hrs = hrs1 + hrss + hrse
    except ValueError:
        hrs = None
    if hrs is None:
        hrs = 0
    return hrs


问:
Why execve hang
I have a struct storing file, argv, and envp in C++ STL containers. The struct also has methods that transform them to c-style pointers for execve call.

```<code>struct Foo {
  std::string file;
  std::vector <std::string> argv;
  std::unordered_map <std::string, std::string> envp;

  inline auto c_file() const;
  inline auto c_argv() const;
  inline auto c_envp() const;
}

// Function: c_file
inline auto Foo::c_file() const {
  return file.c_str();
}

// Function: c_argv
inline auto Foo::c_argv() const {

  auto ptr = std::make_unique<char*[]>(argv.size() + 1);
  for(size_t i=0; i<argv.size(); ++i) {
    ptr[i] = const_cast<char*>(argv[i].c_str());
  }
  ptr[argv.size()] = nullptr;

  return ptr;
}

// Function: c_envp
inline auto Foo::c_envp() const {

  std::unique_ptr<char*, std::function<void(char**)>> ptr(
    new char*[envp.size() + 1],
    [sz=envp.size()+1](char** ptr) {
      for(size_t i=0; i<sz; ++i) {
        delete [] ptr[i];
      }
      delete [] ptr;
    }
  );

  auto idx = size_t{0};

  for(const auto& kvp : envp) {
    auto entry = kvp.first + "=" + kvp.second;
    ptr.get()[idx] = new char[entry.size() + 1];
    ::strncpy(ptr.get()[idx], entry.c_str(), entry.size() + 1);
    ++idx;
  }
  ptr.get()[idx] = nullptr;

  return ptr;
}
</code>```

In my program, I use the following way to call execve.

```<code>void in_parent_process(const Foo& foo) {
  char stack[1024*1024];
  ::clone(child_entry, stack + 1024*1024, myflags, &foo)
}

void child_entry(void* ptr) {
  const auto& foo = *static_cast<Foo*>(ptr);
  ::execve(foo.c_file(), foo.c_argv().get(), foo.c_envp().get());
}
</code>```

However, the call to execve sometimes hang without any response. This makes my parent process fail to synchronize with the child process (through a pipe close-on-exec). Is there anything wrong with my idea here of using unique_ptr? Or there is something wrong with my understanding about setting the stack to the clone call?

答:
Or there is something wrong with my understanding about setting the stack to the clone call?

Yes, your code is wrong. You are misusing clone(2) by passing as the stack zone some automatic variable which sits in your current call stack (so gets invalidated as soon as the calling function returns; this is typical undefined behavior). But that stack zone should generally be the result of some mmap(2) (or at least, some malloc(3)) and should not be part of the calling thread's call stack.

And I think you should not use clone since it is already used by pthreads(7) (which is also used by C++11 threads on Linux)

As I commented, you should use strace(1) for debugging (notably to understand what happens when "the call to execve sometimes hang"). Also, when execve(2) fails, it returns and continues, so you should use perror (or something better, logging errno...) after it. Otherwise execve was successful and reinitialize your process (including its entire virtual address space) to run the new program.  At last, why don't you use existing containerization machinery (e.g. Docker) or at least study carefully their source code (they are free software)?

the call to execve sometimes hang without any response

BTW, execve is a system call. So it either succeeds without returning (by reinitializing your process to start a new program) or it fails quickly (and execve returns only on failure).  In either case, execve is done by the kernel in a few milliseconds at most. so I can't imagine how it could "hang". Hence, execve cannot hang by itself.

(in other words, it is not execve which hangs but something else)

You need to add error handling after execve, at least with

```<code>void child_entry(void* ptr) {
 const auto& foo = *static_cast<Foo*>(ptr);
 ::execve(foo.c_file(), foo.c_argv().get(), foo.c_envp().get());
 perror("execve");
 exit(EXIT_FAILURE);
}
</code>```

and you might replace the perror("execve"); with something more verbose like perror((std::string{"execve of "}+foo.c_file()).c_str());; you could also consider using _exit(2) instead of exit(3) but then you probably should flush your buffered IO (e.g. using fflush(3)...)

You may also want to use logging facilities, see syslog(3).

Be aware of the PATH variable (you could query it in your environ(7) using getenv(3) as getenv("PATH")...); maybe you want execvp(3) instead of execve.

Title: Why execve hang

Body:
I have a struct storing file, argv, and envp in C++ STL containers. The struct also has methods that transform them to c-style pointers for execve call.

struct Foo {
  std::string file;
  std::vector <std::string> argv;
  std::unordered_map <std::string, std::string> envp;

  inline auto c_file() const;
  inline auto c_argv() const;
  inline auto c_envp() const;
}

// Function: c_file
inline auto Foo::c_file() const {
  return file.c_str();
}

// Function: c_argv
inline auto Foo::c_argv() const {

  auto ptr = std::make_unique<char*[]>(argv.size() + 1);
  for(size_t i=0; i<argv.size(); ++i) {
    ptr[i] = const_cast<char*>(argv[i].c_str());
  }
  ptr[argv.size()] = nullptr;

  return ptr;
}

// Function: c_envp
inline auto Foo::c_envp() const {

  std::unique_ptr<char*, std::function<void(char**)>> ptr(
    new char*[envp.size() + 1],
    [sz=envp.size()+1](char** ptr) {
      for(size_t i=0; i<sz; ++i) {
        delete [] ptr[i];
      }
      delete [] ptr;
    }
  );

  auto idx = size_t{0};

  for(const auto& kvp : envp) {
    auto entry = kvp.first + "=" + kvp.second;
    ptr.get()[idx] = new char[entry.size() + 1];
    ::strncpy(ptr.get()[idx], entry.c_str(), entry.size() + 1);
    ++idx;
  }
  ptr.get()[idx] = nullptr;

  return ptr;
}

In my program, I use the following way to call execve.

void in_parent_process(const Foo& foo) {
  char stack[1024*1024];
  ::clone(child_entry, stack + 1024*1024, myflags, &foo)
}

void child_entry(void* ptr) {
  const auto& foo = *static_cast<Foo*>(ptr);
  ::execve(foo.c_file(), foo.c_argv().get(), foo.c_envp().get());
}

However, the call to execve sometimes hang without any response. This makes my parent process fail to synchronize with the child process (through a pipe close-on-exec). Is there anything wrong with my idea here of using unique_ptr? Or there is something wrong with my understanding about setting the stack to the clone call?

Body:
Or there is something wrong with my understanding about setting the stack to the clone call?

Yes, your code is wrong. You are misusing clone(2) by passing as the stack zone some automatic variable which sits in your current call stack (so gets invalidated as soon as the calling function returns; this is typical undefined behavior). But that stack zone should generally be the result of some mmap(2) (or at least, some malloc(3)) and should not be part of the calling thread's call stack.

And I think you should not use clone since it is already used by pthreads(7) (which is also used by C++11 threads on Linux)

As I commented, you should use strace(1) for debugging (notably to understand what happens when "the call to execve sometimes hang"). Also, when execve(2) fails, it returns and continues, so you should use perror (or something better, logging errno...) after it. Otherwise execve was successful and reinitialize your process (including its entire virtual address space) to run the new program.  At last, why don't you use existing containerization machinery (e.g. Docker) or at least study carefully their source code (they are free software)?

the call to execve sometimes hang without any response

BTW, execve is a system call. So it either succeeds without returning (by reinitializing your process to start a new program) or it fails quickly (and execve returns only on failure).  In either case, execve is done by the kernel in a few milliseconds at most. so I can't imagine how it could "hang". Hence, execve cannot hang by itself.

(in other words, it is not execve which hangs but something else)

You need to add error handling after execve, at least with

void child_entry(void* ptr) {
 const auto& foo = *static_cast<Foo*>(ptr);
 ::execve(foo.c_file(), foo.c_argv().get(), foo.c_envp().get());
 perror("execve");
 exit(EXIT_FAILURE);
}

and you might replace the perror("execve"); with something more verbose like perror((std::string{"execve of "}+foo.c_file()).c_str());; you could also consider using _exit(2) instead of exit(3) but then you probably should flush your buffered IO (e.g. using fflush(3)...)

You may also want to use logging facilities, see syslog(3).

Be aware of the PATH variable (you could query it in your environ(7) using getenv(3) as getenv("PATH")...); maybe you want execvp(3) instead of execve.


问:
Is okay to use so much NEW statement?
I have this code that handles my commands:

```<code>public class CommandHandler {

    public static final CommandParser parser = new CommandParser();
    public static HashMap<String, Command> commands = new HashMap<>();

    public static void handleCommand(CommandParser.CommandContainer cmd) {

        if (commands.containsKey(cmd.invoke)) {
            commands.get(cmd.invoke).action(cmd.event, cmd.args);
            commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
        }
        /* else
            System.err.println("CMD NOT EXIST!"); */
    }
}

public static HashMap<String, Command> commands = new HashMap<>();

private static void addCommands() {
    commands.put(new cmdConfig().getCommand(), new cmdConfig());
    commands.put(new cmdHelp().getCommand(), new cmdHelp());
    commands.put(new cmdPing().getCommand(), new cmdPing());
}
</code>```

This is a short code, but I have 157 commands.
Each command extends from an interface who has this methods:

```<code>public interface Command {
    public String getCommand();
    public String help();
    public void action(String[] args);
    public void postAction(String[] args);
}
</code>```

Also, I use this code too:

```<code>String input = "random";

if (new cmdPing().getCommand().equals(input)) {
    new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
    new cmdConfig().help();
}
else {
    printError(input + " is not a valid command");
}
</code>```

and  I want to know if is okay to use to many NEW statements when i use commands.putand inside of if() statements too.

答:
Delete the interface and all implementing classes.

Instead, make Command an enum with final fields for command and help, a getter for help, and the action() method.

No need to have a getter for the command name, as only the class itself needs to use it.

If you need to get the enum instance for a given String, use the valueOf() method that all enums have.

Title: Is okay to use so much NEW statement?

Body:
I have this code that handles my commands:

public class CommandHandler {

    public static final CommandParser parser = new CommandParser();
    public static HashMap<String, Command> commands = new HashMap<>();

    public static void handleCommand(CommandParser.CommandContainer cmd) {

        if (commands.containsKey(cmd.invoke)) {
            commands.get(cmd.invoke).action(cmd.event, cmd.args);
            commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
        }
        /* else
            System.err.println("CMD NOT EXIST!"); */
    }
}

public static HashMap<String, Command> commands = new HashMap<>();

private static void addCommands() {
    commands.put(new cmdConfig().getCommand(), new cmdConfig());
    commands.put(new cmdHelp().getCommand(), new cmdHelp());
    commands.put(new cmdPing().getCommand(), new cmdPing());
}

This is a short code, but I have 157 commands.
Each command extends from an interface who has this methods:

public interface Command {
    public String getCommand();
    public String help();
    public void action(String[] args);
    public void postAction(String[] args);
}

Also, I use this code too:

String input = "random";

if (new cmdPing().getCommand().equals(input)) {
    new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
    new cmdConfig().help();
}
else {
    printError(input + " is not a valid command");
}

and  I want to know if is okay to use to many NEW statements when i use commands.putand inside of if() statements too.


问:
Creating carousel card in AWS Lex
I am trying to build a ecommerce chatbot using lex.

Is there any solution to use a carousel card or multi response cards in Lex?

For example:

Thanks..

答:
You can display multiple response cards in the response and it will display like carousel.
Follow this example to generate response card through console (you can also do it dynamically in code).

Console method:

In the below image, in Prompt response cards section, see in the rightmost part, there is little + button, click on that and you can add more cards.

Dynamic method (using Lambda):

```<code>'dialogAction': {
    'type': 'Close',
    'fulfillmentState': 'Fulfilled',
    'message': {
        'contentType': 'PlainText',
        'content': message
    },
    'responseCard': {
    'version': '0',
    'contentType': 'application/vnd.amazonaws.card.generic',
    'genericAttachments': [
        {
        'title': 'title1',
        'subTitle': 'subtitle1',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        },
        {
        'title': 'title2',
        'subTitle': 'subtitle2',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        },
        {
        'title': 'title3',
        'subTitle': 'subtitle3',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        }
    ]

    }
}
</code>```

NOTE 1: You can have maximum of 10 response cards in the carousel, and maximum of 3 buttons in a single carousel.
If you have more than 10 cards, you will get error.
If you have more than 3 buttons, you won't get error but only first 3 will be shown.

NOTE 2: You need to check messaging_postbacks events in the Webhooks in messenger settings in the Facebook app to make buttons of carousel work.

I have implemented response cards in below manner:

See cards are coming like carousel, you can swipe to see more cards.

Hope it helps.

Title: Creating carousel card in AWS Lex

Body:
You can display multiple response cards in the response and it will display like carousel.
Follow this example to generate response card through console (you can also do it dynamically in code).

Console method:

In the below image, in Prompt response cards section, see in the rightmost part, there is little + button, click on that and you can add more cards.

Dynamic method (using Lambda):

'dialogAction': {
    'type': 'Close',
    'fulfillmentState': 'Fulfilled',
    'message': {
        'contentType': 'PlainText',
        'content': message
    },
    'responseCard': {
    'version': '0',
    'contentType': 'application/vnd.amazonaws.card.generic',
    'genericAttachments': [
        {
        'title': 'title1',
        'subTitle': 'subtitle1',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        },
        {
        'title': 'title2',
        'subTitle': 'subtitle2',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        },
        {
        'title': 'title3',
        'subTitle': 'subtitle3',
        'attachmentLinkUrl': 'link_that_will_open_on_click',
        'imageUrl': 'link_of_image_to_display',
        "buttons":[
             {
                "text":"button_1",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_2",
                "value":"value_to_be_sent_to_server_on_click"
             },
             {
                "text":"button_3",
                "value":"value_to_be_sent_to_server_on_click"
             }
            ]
        }
    ]

    }
}

NOTE 1: You can have maximum of 10 response cards in the carousel, and maximum of 3 buttons in a single carousel.
If you have more than 10 cards, you will get error.
If you have more than 3 buttons, you won't get error but only first 3 will be shown.

NOTE 2: You need to check messaging_postbacks events in the Webhooks in messenger settings in the Facebook app to make buttons of carousel work.

I have implemented response cards in below manner:

See cards are coming like carousel, you can swipe to see more cards.

Hope it helps.


问:
Laravel Eloquent with the max in second table?
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

```<code>$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}
</code>```

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )
```

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

答:
Use DB::raw in your join query to get the Max bid_amount as bid_amount. I have made some changes in your query and it should work now.

```<code>$listings = Listing::join(DB::raw('(select listing_id, Max(bid_amount) as bid_amount from bids GROUP BY listing_id) bids'),'bids.listing_id','listings.id');

    if( !empty($request->keyword) ) {
        $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
    }

    if( !empty($request->category) ) {

        $listings = $listings->where('listings.category_id','=',$request->category);

    }

    if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {

        $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);

    } else {

        if( !empty($request->minimum_bid) ) {

            $listings = $listings->where('bid_amount', '>', $request->minimum_bid);

        }

        if( !empty($request->maximum_bid) ) {

            $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
        }

    }

    return $listings->get();
</code>```

Hope it helps :)

Body:
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

Body:
Use DB::raw in your join query to get the Max bid_amount as bid_amount. I have made some changes in your query and it should work now.

$listings = Listing::join(DB::raw('(select listing_id, Max(bid_amount) as bid_amount from bids GROUP BY listing_id) bids'),'bids.listing_id','listings.id');

    if( !empty($request->keyword) ) {
        $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
            ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
    }

    if( !empty($request->category) ) {

        $listings = $listings->where('listings.category_id','=',$request->category);

    }

    if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {

        $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);

    } else {

        if( !empty($request->minimum_bid) ) {

            $listings = $listings->where('bid_amount', '>', $request->minimum_bid);

        }

        if( !empty($request->maximum_bid) ) {

            $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
        }

    }

    return $listings->get();

Hope it helps :)


问:
Javascript create zip file
I am developing a website using react.js and admin-on-rest. One feature is allowing users to upload a pdf file.

I get the file as type FILE and want to get the file from FILE, compress it to zip, and then make it to type FILE.

So it should be FILE -> origin file -> zip file -> FILE from zip file.

I tried JSZip but still can not figure it out.

Any help is appreciated. Thanks

答:
Hi Garrick following are the steps you need to take.

1) handle fileupload in a rest wrapper
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

the above example is for image upload. But you will essentially be doing the same thing.

2)

```<code>const addUploadCapabilities = requestHandler => (type, resource, params) => {
    if (type === 'UPDATE' && resource === 'posts') {
       //use jszip to zip file here and package it however you need
       // call the API with zipped file
   } return requestHandler(type, resource, params);
};
</code>```

Title: Javascript create zip file

Body:
Hi Garrick following are the steps you need to take.

1) handle fileupload in a rest wrapper
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload

the above example is for image upload. But you will essentially be doing the same thing.

2)

const addUploadCapabilities = requestHandler => (type, resource, params) => {
    if (type === 'UPDATE' && resource === 'posts') {
       //use jszip to zip file here and package it however you need
       // call the API with zipped file
   } return requestHandler(type, resource, params);
};


问:
How can I update widget from CardSection?
I am trying to update widget from CardSection, but I have no ideas to do this task

https://imgur.com/a/fTrkv.

Anyone have an idea how can I do this?

答: It's not possible.  I was trying to find the reference to this, but I cannot find it.  I remember reading it though.  You cannot update any part of a card that you have already rendered.  You can only push a new card onto the stack or update the card in place with another card.</p>


问:
Displaying list of array in drop down in jsp
I have array populated with elements and I want to display elements of that array in drop down list.

Here is relevant piece of code.

```<code> Party[] Parties = party.getAllParties;
</code>```

In my jsp page, i have

```<code> <td nowrap>
    <select label="Party List" array="Parties" name="Party List">
        <option value=<%= (Parties) %>></option>
    </select>
</td>
</code>```

Now when i go and check view source of jsp page, i have

```<code><td nowrap>
  <select label="Party List" array="Parties" name="Party List">
     <option value=[Lcom.areil.pdo.party.Party;@1404de3></option>
  </select>
</td>
</code>```

I know, way option value is set is not correct and am not sure what is right way of doing it.

答:
```<code><select name="party">
    <option value="">SELECT</option>
    <% for(int i=0;i<Parties.size();i++){
        String party= (String)Parties.get(i); %>
        <option value="<%=party%>" > <%=party%>
        </option>
    <%}%>
</select>
</code>```

Body:
I have array populated with elements and I want to display elements of that array in drop down list.

Here is relevant piece of code.

 Party[] Parties = party.getAllParties;

In my jsp page, i have

    <select label="Party List" array="Parties" name="Party List">
        <option value=<%= (Parties) %>></option>
    </select>

Now when i go and check view source of jsp page, i have

  <select label="Party List" array="Parties" name="Party List">
     <option value=[Lcom.areil.pdo.party.Party;@1404de3></option>
  </select>

I know, way option value is set is not correct and am not sure what is right way of doing it.