问:
Rails deep nesting with index of parent
I have the following routes

```<code>  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end
</code>```

To select a country I would have to do

```<code>/continents/:continent_id/countries/:country_id
</code>```

and so on.

My question is how can I get all streets for a specific country or continent. Or all countries for a specific continent.

for example is there a way to do

```<code>/continents/:continent_id/countries/cities
</code>```

which will return all cities under :continent_id

答:
Resources should never be nested more than 1 level deep. Refer to: http://weblog.jamisbuck.org/2007/2/5/nesting-resources

If you really need that deepness then you can solve that with shallow attribute set to true.
Refer to: http://edgeguides.rubyonrails.org/routing.html#shallow-nesting

Update for better explain the use of shallow nesting

```<code>rails new shallow-routes
cd shallow-routes
</code>```

edit config/routes.rb to add your desired routes

```<code>  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end
</code>```

now running rake routes we have this:

```<code>                               Prefix Verb   URI Pattern                                                                  Controller#Action
     continent_country_cities_streets POST   /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#create
 new_continent_country_cities_streets GET    /continent/:continent_id/countries/:country_id/cities/streets/new(.:format)  streets#new
edit_continent_country_cities_streets GET    /continent/:continent_id/countries/:country_id/cities/streets/edit(.:format) streets#edit
                                      GET    /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#show
                                      PATCH  /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#update
                                      PUT    /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#update
                                      DELETE /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#destroy
             continent_country_cities POST   /continent/:continent_id/countries/:country_id/cities(.:format)              cities#create
         new_continent_country_cities GET    /continent/:continent_id/countries/:country_id/cities/new(.:format)          cities#new
        edit_continent_country_cities GET    /continent/:continent_id/countries/:country_id/cities/edit(.:format)         cities#edit
                                      GET    /continent/:continent_id/countries/:country_id/cities(.:format)              cities#show
                                      PATCH  /continent/:continent_id/countries/:country_id/cities(.:format)              cities#update
                                      PUT    /continent/:continent_id/countries/:country_id/cities(.:format)              cities#update
                                      DELETE /continent/:continent_id/countries/:country_id/cities(.:format)              cities#destroy
                  continent_countries GET    /continent/:continent_id/countries(.:format)                                 countries#index
                                      POST   /continent/:continent_id/countries(.:format)                                 countries#create
                new_continent_country GET    /continent/:continent_id/countries/new(.:format)                             countries#new
               edit_continent_country GET    /continent/:continent_id/countries/:id/edit(.:format)                        countries#edit
                    continent_country GET    /continent/:continent_id/countries/:id(.:format)                             countries#show
                                      PATCH  /continent/:continent_id/countries/:id(.:format)                             countries#update
                                      PUT    /continent/:continent_id/countries/:id(.:format)                             countries#update
                                      DELETE /continent/:continent_id/countries/:id(.:format)                             countries#destroy
                      continent_index GET    /continent(.:format)                                                         continent#index
                                      POST   /continent(.:format)                                                         continent#create
                        new_continent GET    /continent/new(.:format)                                                     continent#new
                       edit_continent GET    /continent/:id/edit(.:format)                                                continent#edit
                            continent GET    /continent/:id(.:format)                                                     continent#show
                                      PATCH  /continent/:id(.:format)                                                     continent#update
                                      PUT    /continent/:id(.:format)                                                     continent#update
                                      DELETE /continent/:id(.:format)                                                     continent#destroy
</code>```

Let's change that resources for shallow nesting and look at the result

```<code>  resources :continent, shallow: true do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end
</code>```

It's result

```<code>                     Prefix Verb   URI Pattern                                          Controller#Action
     country_cities_streets POST   /countries/:country_id/cities/streets(.:format)      streets#create
 new_country_cities_streets GET    /countries/:country_id/cities/streets/new(.:format)  streets#new
edit_country_cities_streets GET    /countries/:country_id/cities/streets/edit(.:format) streets#edit
                            GET    /countries/:country_id/cities/streets(.:format)      streets#show
                            PATCH  /countries/:country_id/cities/streets(.:format)      streets#update
                            PUT    /countries/:country_id/cities/streets(.:format)      streets#update
                            DELETE /countries/:country_id/cities/streets(.:format)      streets#destroy
             country_cities POST   /countries/:country_id/cities(.:format)              cities#create
         new_country_cities GET    /countries/:country_id/cities/new(.:format)          cities#new
        edit_country_cities GET    /countries/:country_id/cities/edit(.:format)         cities#edit
                            GET    /countries/:country_id/cities(.:format)              cities#show
                            PATCH  /countries/:country_id/cities(.:format)              cities#update
                            PUT    /countries/:country_id/cities(.:format)              cities#update
                            DELETE /countries/:country_id/cities(.:format)              cities#destroy
        continent_countries GET    /continent/:continent_id/countries(.:format)         countries#index
                            POST   /continent/:continent_id/countries(.:format)         countries#create
      new_continent_country GET    /continent/:continent_id/countries/new(.:format)     countries#new
               edit_country GET    /countries/:id/edit(.:format)                        countries#edit
                    country GET    /countries/:id(.:format)                             countries#show
                            PATCH  /countries/:id(.:format)                             countries#update
                            PUT    /countries/:id(.:format)                             countries#update
                            DELETE /countries/:id(.:format)                             countries#destroy
            continent_index GET    /continent(.:format)                                 continent#index
                            POST   /continent(.:format)                                 continent#create
              new_continent GET    /continent/new(.:format)                             continent#new
             edit_continent GET    /continent/:id/edit(.:format)                        continent#edit
                  continent GET    /continent/:id(.:format)                             continent#show
                            PATCH  /continent/:id(.:format)                             continent#update
                            PUT    /continent/:id(.:format)                             continent#update
                            DELETE /continent/:id(.:format)                             continent#destroy
</code>```

an image of it's difference for better view http://i.imgur.com/21CEM7j.png

what we have here is that now the routes are simpler, a route like /continent/:continent_id/countries now exists only for index, create and new the others are outside of continent scope in routes

Notice that it is really helpful, because you don't need routes to tell you that an street is inside a continent, it's obvious, if your street is inside a city, it's of course inside a country and continent as well.

Direct Answer - Now let's take a look at your goal here

/continents/:continent_id/countries/cities

You want all cities of the continent, why [the hell, sorry for it] do you need countries between them ?

I would just do /continents/:id/cities, much simpler and easy to understand.

To achieve that you just create a new route inside your continents resource

```<code>  resources :continent, shallow: true do
    member do
        get 'cities'
    end

    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end
</code>```

and then you have this new nice route

```<code>cities_continent GET    /continent/:id/cities(.:format)                      continent#cities
</code>```

Title: Rails deep nesting with index of parent

Body:
I have the following routes

  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end

To select a country I would have to do

/continents/:continent_id/countries/:country_id

and so on.

My question is how can I get all streets for a specific country or continent. Or all countries for a specific continent.

for example is there a way to do

/continents/:continent_id/countries/cities

which will return all cities under :continent_id

Body:
Resources should never be nested more than 1 level deep. Refer to: http://weblog.jamisbuck.org/2007/2/5/nesting-resources

If you really need that deepness then you can solve that with shallow attribute set to true.
Refer to: http://edgeguides.rubyonrails.org/routing.html#shallow-nesting

Update for better explain the use of shallow nesting

rails new shallow-routes
cd shallow-routes

edit config/routes.rb to add your desired routes

  resources :continent do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end

now running rake routes we have this:

                               Prefix Verb   URI Pattern                                                                  Controller#Action
     continent_country_cities_streets POST   /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#create
 new_continent_country_cities_streets GET    /continent/:continent_id/countries/:country_id/cities/streets/new(.:format)  streets#new
edit_continent_country_cities_streets GET    /continent/:continent_id/countries/:country_id/cities/streets/edit(.:format) streets#edit
                                      GET    /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#show
                                      PATCH  /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#update
                                      PUT    /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#update
                                      DELETE /continent/:continent_id/countries/:country_id/cities/streets(.:format)      streets#destroy
             continent_country_cities POST   /continent/:continent_id/countries/:country_id/cities(.:format)              cities#create
         new_continent_country_cities GET    /continent/:continent_id/countries/:country_id/cities/new(.:format)          cities#new
        edit_continent_country_cities GET    /continent/:continent_id/countries/:country_id/cities/edit(.:format)         cities#edit
                                      GET    /continent/:continent_id/countries/:country_id/cities(.:format)              cities#show
                                      PATCH  /continent/:continent_id/countries/:country_id/cities(.:format)              cities#update
                                      PUT    /continent/:continent_id/countries/:country_id/cities(.:format)              cities#update
                                      DELETE /continent/:continent_id/countries/:country_id/cities(.:format)              cities#destroy
                  continent_countries GET    /continent/:continent_id/countries(.:format)                                 countries#index
                                      POST   /continent/:continent_id/countries(.:format)                                 countries#create
                new_continent_country GET    /continent/:continent_id/countries/new(.:format)                             countries#new
               edit_continent_country GET    /continent/:continent_id/countries/:id/edit(.:format)                        countries#edit
                    continent_country GET    /continent/:continent_id/countries/:id(.:format)                             countries#show
                                      PATCH  /continent/:continent_id/countries/:id(.:format)                             countries#update
                                      PUT    /continent/:continent_id/countries/:id(.:format)                             countries#update
                                      DELETE /continent/:continent_id/countries/:id(.:format)                             countries#destroy
                      continent_index GET    /continent(.:format)                                                         continent#index
                                      POST   /continent(.:format)                                                         continent#create
                        new_continent GET    /continent/new(.:format)                                                     continent#new
                       edit_continent GET    /continent/:id/edit(.:format)                                                continent#edit
                            continent GET    /continent/:id(.:format)                                                     continent#show
                                      PATCH  /continent/:id(.:format)                                                     continent#update
                                      PUT    /continent/:id(.:format)                                                     continent#update
                                      DELETE /continent/:id(.:format)                                                     continent#destroy

Let's change that resources for shallow nesting and look at the result

  resources :continent, shallow: true do
    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end

It's result

                     Prefix Verb   URI Pattern                                          Controller#Action
     country_cities_streets POST   /countries/:country_id/cities/streets(.:format)      streets#create
 new_country_cities_streets GET    /countries/:country_id/cities/streets/new(.:format)  streets#new
edit_country_cities_streets GET    /countries/:country_id/cities/streets/edit(.:format) streets#edit
                            GET    /countries/:country_id/cities/streets(.:format)      streets#show
                            PATCH  /countries/:country_id/cities/streets(.:format)      streets#update
                            PUT    /countries/:country_id/cities/streets(.:format)      streets#update
                            DELETE /countries/:country_id/cities/streets(.:format)      streets#destroy
             country_cities POST   /countries/:country_id/cities(.:format)              cities#create
         new_country_cities GET    /countries/:country_id/cities/new(.:format)          cities#new
        edit_country_cities GET    /countries/:country_id/cities/edit(.:format)         cities#edit
                            GET    /countries/:country_id/cities(.:format)              cities#show
                            PATCH  /countries/:country_id/cities(.:format)              cities#update
                            PUT    /countries/:country_id/cities(.:format)              cities#update
                            DELETE /countries/:country_id/cities(.:format)              cities#destroy
        continent_countries GET    /continent/:continent_id/countries(.:format)         countries#index
                            POST   /continent/:continent_id/countries(.:format)         countries#create
      new_continent_country GET    /continent/:continent_id/countries/new(.:format)     countries#new
               edit_country GET    /countries/:id/edit(.:format)                        countries#edit
                    country GET    /countries/:id(.:format)                             countries#show
                            PATCH  /countries/:id(.:format)                             countries#update
                            PUT    /countries/:id(.:format)                             countries#update
                            DELETE /countries/:id(.:format)                             countries#destroy
            continent_index GET    /continent(.:format)                                 continent#index
                            POST   /continent(.:format)                                 continent#create
              new_continent GET    /continent/new(.:format)                             continent#new
             edit_continent GET    /continent/:id/edit(.:format)                        continent#edit
                  continent GET    /continent/:id(.:format)                             continent#show
                            PATCH  /continent/:id(.:format)                             continent#update
                            PUT    /continent/:id(.:format)                             continent#update
                            DELETE /continent/:id(.:format)                             continent#destroy

an image of it's difference for better view http://i.imgur.com/21CEM7j.png

what we have here is that now the routes are simpler, a route like /continent/:continent_id/countries now exists only for index, create and new the others are outside of continent scope in routes

Notice that it is really helpful, because you don't need routes to tell you that an street is inside a continent, it's obvious, if your street is inside a city, it's of course inside a country and continent as well.

Direct Answer - Now let's take a look at your goal here

/continents/:continent_id/countries/cities

You want all cities of the continent, why [the hell, sorry for it] do you need countries between them ?

I would just do /continents/:id/cities, much simpler and easy to understand.

To achieve that you just create a new route inside your continents resource

  resources :continent, shallow: true do
    member do
        get 'cities'
    end

    resources :countries do
        resource :cities do
            resource :streets
        end
    end
  end

and then you have this new nice route

cities_continent GET    /continent/:id/cities(.:format)                      continent#cities


来源: stackexchange

问:
How to remove specific space between parent and child in an ExpandableListView
Can you help me identify why there is a space between the group and the child? In my case I want spaces between all groups and the child should be right below the group with no space (but of course space to the next group. My problem looks like this:

I have set the Group divider to this drawable (expandable_list_group_divider):

```<code><?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="10dp"/>
</shape>
</code>```

And the child divider to this (@drawable/expandable_list_child_divider):

```<code><?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="0dp"/>
</shape>
</code>```

I have defined the layout like this in the xml(it is a compund control):

```<code><com.jws.MyExpandableListView
        android:id="@+id/expList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:scrollbars="none"
        android:divider="@drawable/expandable_list_group_divider"
        android:childDivider="@drawable/expandable_list_child_divider"/>
</code>```

The custom view class:

```<code>public class MyExpandableListView extends ExpandableListView {
    protected ArrayList<Departure> departures;

    public MyExpandableListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setGroupIndicator(null);
        setChildIndicator(null);
        setHorizontalFadingEdgeEnabled(true);
        setVerticalFadingEdgeEnabled(true);
        setFadingEdgeLength(60);

        departures = new ArrayList<Departure>();
        this.setAdapter(new MyExpandableListAdapter(context, this, departures));
    }
}
</code>```

And finally the expandable list adapter

```<code>public class DeparturesExpandableListAdapter extends BaseExpandableListAdapter {
    private final int DIVIDER_HEIGHT = 20;
    private LayoutInflater inflater;
    private ArrayList<Departure> departures;
    private Context context;
    private ExpandableListView expListView;

    public DeparturesExpandableListAdapter(Context context, ExpandableListView expListView, ArrayList<Departure> departures)
    {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        this.departures = departures;
        this.expListView = expListView;
    }

    // This Function used to inflate parent rows view
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView)
    {
        final Departure departure = departures.get(groupPosition);

        if(!isExpanded)
            expListView.setDividerHeight(DIVIDER_HEIGHT);
        else
            expListView.setDividerHeight(-4);

        expListView.setFooterDividersEnabled(false);

        // Inflate grouprow.xml file for parent rows
        convertView = inflater.inflate(R.layout.view_departure_overview, parentView, false);

        //Data handling in the view...

        return convertView;
    }

    // This Function used to inflate child rows view
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parentView)
    {
        final Departure departure = departures.get(groupPosition);

        if(isLastChild)
            expListView.setDividerHeight(DIVIDER_HEIGHT);

        // Inflate childrow.xml file for child rows
        convertView = inflater.inflate(R.layout.view_departure_details, parentView, false);

        //Data handling...

        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {
        return departures.get(groupPosition);
    }

    //Call when child row clicked
    @Override
    public long getChildId(int groupPosition, int childPosition)
    {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {
        return 1;
    }

    @Override
    public Object getGroup(int groupPosition)
    {
        return departures.get(groupPosition);
    }

    @Override
    public int getGroupCount()
    {
        if(departures != null)
            return departures.size();

        return 0;
    }

    //Call when parent row clicked
    @Override
    public long getGroupId(int groupPosition)
    {
        return groupPosition;
    }

    @Override
    public void notifyDataSetChanged()
    {
        // Refresh List rows
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isEmpty()
    {
        return ((departures == null) || departures.isEmpty());
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return false;
    }

    @Override
    public boolean hasStableIds()
    {
        return false;
    }

    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }
}
</code>```

Image for comments:

答:
Modify the view's padding in the method public View getChildView() using the setPadding() method of the view.

Example:

```<code>@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parentView){
 final Departure departure = departures.get(groupPosition);

 if(isLastChild)
  expListView.setDividerHeight(DIVIDER_HEIGHT);

 // Inflate childrow.xml file for child rows
 convertView = inflater.inflate(R.layout.view_departure_details, parentView, false);

 //Data handling...

 convertView.setPadding(0, 0, 0, 0);

 return convertView;
}
</code>```

In the same way, if you want modify padding of the group, you will have to modify the padding in the getGroupView() method.

ContentLicense: CC BY-SA 3.0

Body:
Can you help me identify why there is a space between the group and the child? In my case I want spaces between all groups and the child should be right below the group with no space (but of course space to the next group. My problem looks like this:

I have set the Group divider to this drawable (expandable_list_group_divider):

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="10dp"/>
</shape>

And the child divider to this (@drawable/expandable_list_child_divider):

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:height="0dp"/>
</shape>

I have defined the layout like this in the xml(it is a compund control):

<com.jws.MyExpandableListView
        android:id="@+id/expList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:scrollbars="none"
        android:divider="@drawable/expandable_list_group_divider"
        android:childDivider="@drawable/expandable_list_child_divider"/>

The custom view class:

public class MyExpandableListView extends ExpandableListView {
    protected ArrayList<Departure> departures;

    public MyExpandableListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setGroupIndicator(null);
        setChildIndicator(null);
        setHorizontalFadingEdgeEnabled(true);
        setVerticalFadingEdgeEnabled(true);
        setFadingEdgeLength(60);

        departures = new ArrayList<Departure>();
        this.setAdapter(new MyExpandableListAdapter(context, this, departures));
    }
}

And finally the expandable list adapter

public class DeparturesExpandableListAdapter extends BaseExpandableListAdapter {
    private final int DIVIDER_HEIGHT = 20;
    private LayoutInflater inflater;
    private ArrayList<Departure> departures;
    private Context context;
    private ExpandableListView expListView;

    public DeparturesExpandableListAdapter(Context context, ExpandableListView expListView, ArrayList<Departure> departures)
    {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        this.departures = departures;
        this.expListView = expListView;
    }

    // This Function used to inflate parent rows view
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parentView)
    {
        final Departure departure = departures.get(groupPosition);

        if(!isExpanded)
            expListView.setDividerHeight(DIVIDER_HEIGHT);
        else
            expListView.setDividerHeight(-4);

        expListView.setFooterDividersEnabled(false);

        // Inflate grouprow.xml file for parent rows
        convertView = inflater.inflate(R.layout.view_departure_overview, parentView, false);

        //Data handling in the view...

        return convertView;
    }

    // This Function used to inflate child rows view
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parentView)
    {
        final Departure departure = departures.get(groupPosition);

        if(isLastChild)
            expListView.setDividerHeight(DIVIDER_HEIGHT);

        // Inflate childrow.xml file for child rows
        convertView = inflater.inflate(R.layout.view_departure_details, parentView, false);

        //Data handling...

        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {
        return departures.get(groupPosition);
    }

    //Call when child row clicked
    @Override
    public long getChildId(int groupPosition, int childPosition)
    {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {
        return 1;
    }

    @Override
    public Object getGroup(int groupPosition)
    {
        return departures.get(groupPosition);
    }

    @Override
    public int getGroupCount()
    {
        if(departures != null)
            return departures.size();

        return 0;
    }

    //Call when parent row clicked
    @Override
    public long getGroupId(int groupPosition)
    {
        return groupPosition;
    }

    @Override
    public void notifyDataSetChanged()
    {
        // Refresh List rows
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isEmpty()
    {
        return ((departures == null) || departures.isEmpty());
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return false;
    }

    @Override
    public boolean hasStableIds()
    {
        return false;
    }

    @Override
    public boolean areAllItemsEnabled()
    {
        return true;
    }
}

Image for comments:

Body:
Modify the view's padding in the method public View getChildView() using the setPadding() method of the view.

Example:

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parentView){
 final Departure departure = departures.get(groupPosition);

 if(isLastChild)
  expListView.setDividerHeight(DIVIDER_HEIGHT);

 // Inflate childrow.xml file for child rows
 convertView = inflater.inflate(R.layout.view_departure_details, parentView, false);

 //Data handling...

 convertView.setPadding(0, 0, 0, 0);

 return convertView;
}

In the same way, if you want modify padding of the group, you will have to modify the padding in the getGroupView() method.


问:
Structure for an array of bits in C
It has come to my attention that there is no builtin structure for a single bit in C. There is (unsigned) char and int, which are 8 bits (one byte), and long which is 64+ bits, and so on (uint64_t, bool...)

I came across this while coding up a huffman tree, and the encodings for certain characters were not necessarily exactly 8 bits long (like 00101), so there was no efficient way to store the encodings. I had to find makeshift solutions such as strings or boolean arrays, but this takes far more memory.

But anyways, my question is more general: is there a good way to store an array of bits, or some sort of user-defined struct? I scoured the web for one but the smallest structure seems to be 8 bits (one byte). I tried things such as int a : 1 but it didn't work. I read about bit fields but they do not simply achieve exactly what I want to do. I know questions have already been asked about this in C++ and if there is a struct for a single bit, but mostly I want to know specifically what would be the most memory-efficient way to store an encoding such as 00101 in C.

答:
It has come to my attention that there is no builtin structure for a single bit in C.

That is true, and it makes sense because substantially no machines have bit-addressible memory.

But anyways, my question is more general: is there a good way to store
  an array of bits, or some sort of user-defined struct?

One generally uses an unsigned char or another unsigned integer type, or an array of such.  Along with that you need some masking and shifting to set or read the values of individual bits.

I scoured the
  web for one but the smallest structure seems to be 8 bits (one byte).

Technically, the smallest addressible storage unit ([[un]signed] char) could be larger than 8 bits, though you're unlikely ever to see that.

I tried things such as int a : 1 but it didn't work. I read about bit
  fields but they do not simply achieve exactly what I want to do.

Bit fields can appear only as structure members.  A structure object containing such a bitfield will still have a size that is a multiple of the size of a char, so that doesn't map very well onto a bit array or any part of one.

I
  know questions have already been asked about this in C++ and if there
  is a struct for a single bit, but mostly I want to know specifically
  what would be the most memory-efficient way to store an encoding such
  as 00101 in C.

If you need a bit pattern and a separate bit count -- such as if some of the bits available in the bit-storage object are not actually significant -- then you need a separate datum for the significant-bit count.  If you want a data structure for a small but variable number of bits, then you might go with something along these lines:

```<code>struct bit_array_small {
    unsigned char bits;
    unsigned char num_bits;
};
</code>```

Of course, you can make that larger by choosing a different data type for the bits member and, maybe, the num_bits member.  I'm sure you can see how you might extend the concept to handling arbitrary-length bit arrays if you should happen to need that.

Title: Structure for an array of bits in C

Body:
It has come to my attention that there is no builtin structure for a single bit in C.

That is true, and it makes sense because substantially no machines have bit-addressible memory.

But anyways, my question is more general: is there a good way to store
  an array of bits, or some sort of user-defined struct?

One generally uses an unsigned char or another unsigned integer type, or an array of such.  Along with that you need some masking and shifting to set or read the values of individual bits.

I scoured the
  web for one but the smallest structure seems to be 8 bits (one byte).

Technically, the smallest addressible storage unit ([[un]signed] char) could be larger than 8 bits, though you're unlikely ever to see that.

I tried things such as int a : 1 but it didn't work. I read about bit
  fields but they do not simply achieve exactly what I want to do.

Bit fields can appear only as structure members.  A structure object containing such a bitfield will still have a size that is a multiple of the size of a char, so that doesn't map very well onto a bit array or any part of one.

I
  know questions have already been asked about this in C++ and if there
  is a struct for a single bit, but mostly I want to know specifically
  what would be the most memory-efficient way to store an encoding such
  as 00101 in C.

If you need a bit pattern and a separate bit count -- such as if some of the bits available in the bit-storage object are not actually significant -- then you need a separate datum for the significant-bit count.  If you want a data structure for a small but variable number of bits, then you might go with something along these lines:

struct bit_array_small {
    unsigned char bits;
    unsigned char num_bits;
};

Of course, you can make that larger by choosing a different data type for the bits member and, maybe, the num_bits member.  I'm sure you can see how you might extend the concept to handling arbitrary-length bit arrays if you should happen to need that.


问:
struts2 Error while retrieving generic property class for property=parameters
I am getting the below exception. Any input on why is occurs would be helpful

DEBUG [http-8081-1] (CommonsLogger.java:72) - Error while retrieving generic property class for property=parameters
java.lang.NullPointerException
 at com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.getClass(DefaultObjectTypeDeterminer.java:314)
 at com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.getKeyClass(DefaultObjectTypeDeterminer.java:93)
 at com.opensymphony.xwork2.ognl.accessor.XWorkMapPropertyAccessor.getProperty(XWorkMapPropertyAccessor.java:93)
 at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2230)
 at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
 at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
 at ognl.SimpleNode.getValue(SimpleNode.java:258)
 at ognl.ASTChain.getValueBody(ASTChain.java:141)
 at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
 at ognl.SimpleNode.getValue(SimpleNode.java:258)
 at ognl.Ognl.getValue(Ognl.java:494)
 at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:217)
 at com.opensymphony.xwork2.ognl.OgnlValueStack.getValue(OgnlValueStack.java:342)
 at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValue(OgnlValueStack.java:331)
 at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValueWhenExpressionIsNotNull(OgnlValueStack.java:307)
 at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:293)
 at org.apache.struts2.components.Property.start(Property.java:162)
 at org.apache.struts2.views.freemarker.tags.CallbackWriter.onStart(CallbackWriter.java:73)
 at freemarker.core.Environment.visit(Environment.java:296)
 at freemarker.core.UnifiedCall.accept(UnifiedCall.java:130)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.MixedContent.accept(MixedContent.java:92)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.IfBlock.accept(IfBlock.java:82)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.MixedContent.accept(MixedContent.java:92)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.IfBlock.accept(IfBlock.java:82)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.MixedContent.accept(MixedContent.java:92)
 at freemarker.core.Environment.visit(Environment.java:210)
 at freemarker.core.Environment.process(Environment.java:190)
 at freemarker.template.Template.process(Template.java:237)
 at org.apache.struts2.components.template.FreemarkerTemplateEngine.renderTemplate(FreemarkerTemplateEngine.java:157)
 at org.apache.struts2.components.UIBean.mergeTemplate(UIBean.java:559)
 at org.apache.struts2.components.ClosingUIBean.start(ClosingUIBean.java:59)
 at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:53)
 at org.apache.jsp.pages.THDPaymentMethod_jsp._jspx_meth_s_005fsubmit_005f1(THDPaymentMethod_jsp.java:6665)
 at org.apache.jsp.pages.THDPaymentMethod_jsp._jspx_meth_s_005fform_005f0(THDPaymentMethod_jsp.java:2363)
 at org.apache.jsp.pages.THDPaymentMethod_jsp._jspService(THDPaymentMethod_jsp.java:347)
 at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
 at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
 at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

答:
Same issue for me when I use a submit taglib of type image.
Moreover, I downloaded the struts2 samples 2.2.1

I added  to the struts2-showcase-2.2.1/conversion/enterPersonsInfo.jsp form and it generates the error previously describe.

Could you tell me if it's reproducable on your side with the struts2-showcase sample?

Tested with struts2.2.1 on Jonas4.10.3

ContentLicense: CC BY-SA 2.5


问:
Showing a div and keep it show() if i clicked on it

$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    $('#div').hide();

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  display: none;
  position: absolute;
  bottom: 20px;
}</code>```

  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX

<input id='input' type='text'>```

In this jquery code, the #div shows when i type something inside the #input but if i tried to click on the #div it disappears and the link doesn't work,

How can i keep the #div shown if i clicked on #div or #input only, But anything outside will hide it as normal?

The Problem happens because of position: absolute; bottom 20px line in CSS.

Updated the code and suddenly it worked as intended after adding if statement after .focusin function, For previous error solution, remove the position and bottom in the CSS

答:
When you blur out of the input, check if the currently active element is the DIV, and hide it if it isn't.

Also, if you're positioning an element absolutely, you need to give it a z-index so you can click on it. Otherwise, the click is sent to the normally-positioned element at that location.

$(document).ready(function() {
  $('#input').focus(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
  }).blur(function() {
    if (!$("#div").is(":focus,:active")) {
      $("#div").hide();
    }
  });
  $('#input').keyup(function() {
    // If not empty value, show div
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    var search = $('#input').val();
    $.post('search.php', {
      search: search
    }, function(data) {
      $('#div').html(data);
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  display: none;
  position: absolute;
  bottom: 20px;
  z-index: 2;
}</code>```

  HellWorld

<input id='input' type='text'>```

Body:
$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    $('#div').hide();

  });

});

#div {
  display: none;
  position: absolute;
  bottom: 20px;
}

  Link From AJAX
  Link From AJAX
  Link From AJAX

<input id='input' type='text'>

In this jquery code, the #div shows when i type something inside the #input but if i tried to click on the #div it disappears and the link doesn't work,

How can i keep the #div shown if i clicked on #div or #input only, But anything outside will hide it as normal?

The Problem happens because of position: absolute; bottom 20px line in CSS.

Updated the code and suddenly it worked as intended after adding if statement after .focusin function, For previous error solution, remove the position and bottom in the CSS

Body:
When you blur out of the input, check if the currently active element is the DIV, and hide it if it isn't.

Also, if you're positioning an element absolutely, you need to give it a z-index so you can click on it. Otherwise, the click is sent to the normally-positioned element at that location.

$(document).ready(function() {
  $('#input').focus(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
  }).blur(function() {
    if (!$("#div").is(":focus,:active")) {
      $("#div").hide();
    }
  });
  $('#input').keyup(function() {
    // If not empty value, show div
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    var search = $('#input').val();
    $.post('search.php', {
      search: search
    }, function(data) {
      $('#div').html(data);
    });
  });
});

#div {
  display: none;
  position: absolute;
  bottom: 20px;
  z-index: 2;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
  <a href='www.someplace.com'>HellWorld</a>
</div>
<input id='input' type='text'>


问:
Python matrix inner product
I am trying to solve the below question:

```<code>'''
        Take in two matrices as numpy arrays, X and Y. Determine whether they have an inner product.
        If they do not, return False. If they do, return the resultant matrix as a numpy array.
        '''
</code>```

with the following code:

```<code>def mat_inner_product(X,Y):

    if X.shape != Y.shape:
        return False
    else:
        return np.inner(X,Y)
</code>```

I got the following error message:

```<code>.F
======================================================================
FAIL: test_mat_inner_product (test_methods.TestPython1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/src/app/test_methods.py", line 27, in test_mat_inner_product
    self.assertTrue(np.array_equal(result2, correct2))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)
</code>```

What does it mean "False is not true"? Do I have a logic error? Or should I use .dot() rather than .inner()? What is the difference?

答:
One can calculate the inner product given that the last dimension of both matrices are the same. So you should not check whether X.shape is equal to Y.shape, but only the last dimension:

```<code>def mat_inner_product(X,Y):
    if X.shape<b>[-1]</b> != Y.shape<b>[-1]</b>:
        return False
    else:
        return np.inner(X,Y)</code>```

Furthermore the number of dimensions - the .ndim (which is the len(X.shape) - do not have to be the same either: you can calculate the inner product of a 2d matrix with a 3d tensor.

You can however omit the check and use a try-except item:

```<code>def mat_inner_product(X,Y):
    <b>try:</b>
        return np.inner(X,Y)
    <b>except ValueError:</b>
        return False</code>```

Now we only have to rely on the fact that numpy has implemented the logic of the inner matrix correctly, and will raise a ValueError in case the inner product cannot be calculated.

Or should I use .dot() rather than .inner()? What is the difference?

The difference with the dot product is that it works with the second last dimension of Y (instead of the last that is used in np.inner()). So in case you would work with numpy.dot(..) the check would be:

```<code>def mat_<b>dot</b>_product(X,Y):
    if X.shape[-1] != Y.shape<b>[-2]</b>:
        return False
    else:
        return np.<b>dot</b>(X,Y)</code>```

But again, you can make use of a try-except structure here.

Title: Python matrix inner product

Body:
I am trying to solve the below question:

'''
        Take in two matrices as numpy arrays, X and Y. Determine whether they have an inner product.
        If they do not, return False. If they do, return the resultant matrix as a numpy array.
        '''

with the following code:

def mat_inner_product(X,Y):

    if X.shape != Y.shape:
        return False
    else:
        return np.inner(X,Y)

I got the following error message:

.F
======================================================================
FAIL: test_mat_inner_product (test_methods.TestPython1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/src/app/test_methods.py", line 27, in test_mat_inner_product
    self.assertTrue(np.array_equal(result2, correct2))
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

What does it mean "False is not true"? Do I have a logic error? Or should I use .dot() rather than .inner()? What is the difference?

Body:
One can calculate the inner product given that the last dimension of both matrices are the same. So you should not check whether X.shape is equal to Y.shape, but only the last dimension:

def mat_inner_product(X,Y):
    if X.shape[-1] != Y.shape[-1]:
        return False
    else:
        return np.inner(X,Y)

Furthermore the number of dimensions - the .ndim (which is the len(X.shape) - do not have to be the same either: you can calculate the inner product of a 2d matrix with a 3d tensor.

You can however omit the check and use a try-except item:

def mat_inner_product(X,Y):
    try:
        return np.inner(X,Y)
    except ValueError:
        return False

Now we only have to rely on the fact that numpy has implemented the logic of the inner matrix correctly, and will raise a ValueError in case the inner product cannot be calculated.

Or should I use .dot() rather than .inner()? What is the difference?

The difference with the dot product is that it works with the second last dimension of Y (instead of the last that is used in np.inner()). So in case you would work with numpy.dot(..) the check would be:

def mat_dot_product(X,Y):
    if X.shape[-1] != Y.shape[-2]:
        return False
    else:
        return np.dot(X,Y)

But again, you can make use of a try-except structure here.


问:
Why is this python loop containing consecutive duplicate items breaking?
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

```<code>def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False
</code>```

答:
EDIT

I'm leaving this here because I think the explanation and the recursive version are helpful, but @Blckknght's answer is superior in that it does less work (by backing up only one element rather than restarting with each iteration).

Here's some working code. I realize it's a bit of a departure from your code. (You can ignore the cancel_pair implementation; I wrote my own before I saw yours. Yours looks fine.)

```<code>def cancel_pair(dir1, dir2):
    return tuple(sorted((dir1, dir2))) in (("NORTH", "SOUTH"), ("EAST", "WEST"))

def dirReduc(directions):
    did_something = True
    while did_something:
        did_something = False
        for i in range(len(directions) - 1):
            if cancel_pair(directions[i], directions[i + 1]):
                did_something = True
                directions = directions[:i] + directions[i + 2:]
                break
    return directions
</code>```

I think there are a couple issues with your code:

You're modifying the list of directions while you're iterating over it. This is generally a bad idea, and specifically here, I think it may cause you to skip over elements (because the length of the list is changing).

You're only taking one pass through the array. In the problem you linked to on Codewars, you need to repeat the process after removing a canceling pair.

You're using index to figure out the current index, but it will always tell you the index of the first occurrence of the value you're passing in. You need to instead keep track of the index yourself. I chose to just iterate over the indices, since I need to use the index + 1 anyway.

UPDATE

A recursive approach might be easier to understand, depending on your programming background:

```<code>def dirReduc(directions):
    for i in range(len(directions) - 1):
        if cancel_pair(directions[i], directions[i + 1]):
            return dirReduc(directions[:i] + directions[i + 2:])
    return directions
</code>```

Body:
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False

Body:
EDIT

I'm leaving this here because I think the explanation and the recursive version are helpful, but @Blckknght's answer is superior in that it does less work (by backing up only one element rather than restarting with each iteration).

Here's some working code. I realize it's a bit of a departure from your code. (You can ignore the cancel_pair implementation; I wrote my own before I saw yours. Yours looks fine.)

def cancel_pair(dir1, dir2):
    return tuple(sorted((dir1, dir2))) in (("NORTH", "SOUTH"), ("EAST", "WEST"))

def dirReduc(directions):
    did_something = True
    while did_something:
        did_something = False
        for i in range(len(directions) - 1):
            if cancel_pair(directions[i], directions[i + 1]):
                did_something = True
                directions = directions[:i] + directions[i + 2:]
                break
    return directions

I think there are a couple issues with your code:

You're modifying the list of directions while you're iterating over it. This is generally a bad idea, and specifically here, I think it may cause you to skip over elements (because the length of the list is changing).

You're only taking one pass through the array. In the problem you linked to on Codewars, you need to repeat the process after removing a canceling pair.

You're using index to figure out the current index, but it will always tell you the index of the first occurrence of the value you're passing in. You need to instead keep track of the index yourself. I chose to just iterate over the indices, since I need to use the index + 1 anyway.

UPDATE

A recursive approach might be easier to understand, depending on your programming background:

def dirReduc(directions):
    for i in range(len(directions) - 1):
        if cancel_pair(directions[i], directions[i + 1]):
            return dirReduc(directions[:i] + directions[i + 2:])
    return directions


问:
Prevent auto choose which sharing application use
I'm develop an application in Android.

I have a ListView with some image, when I click a row I open ContextMenu and I have two Choise, eliminate the image or sharing with other application.

```<code>    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    Uri r = Util.getImageUri(getActivity().getApplication(), image);
    intent.putExtra(Intent.EXTRA_STREAM, r);
    startActivity(intent);
</code>```

I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

How can I prevent it?
I want that user choose every time sharing application.
Thanks.
t

答:
I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

That was because you indicated, to the chooser, that you wanted to make this choice "always", instead of "just once".

I want that user choose every time sharing application

Use:

```<code>startActivity(Intent.createChooser(intent, "..."));
</code>```

where "..." is your explanation for this.

Body:
I'm develop an application in Android.

I have a ListView with some image, when I click a row I open ContextMenu and I have two Choise, eliminate the image or sharing with other application.

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    Uri r = Util.getImageUri(getActivity().getApplication(), image);
    intent.putExtra(Intent.EXTRA_STREAM, r);
    startActivity(intent);

I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

How can I prevent it?
I want that user choose every time sharing application.
Thanks.
t

Body:
I use this code to sharing the image, but after the first time, every time that I try to share image, the application choose always the first application with wich I send the first image.

That was because you indicated, to the chooser, that you wanted to make this choice "always", instead of "just once".

I want that user choose every time sharing application

Use:

startActivity(Intent.createChooser(intent, "..."));

where "..." is your explanation for this.


问:
Adding time that totals more than 24 hrs in SQL
I am trying to add time from several rows, and when they add up to more than hours I do not get correct results I am looking for. Would like to script TotalTime to allow more than 24 in HH. Does not have to be a datetime datatype.

StartTime and FinishTime are varchar(8) data types.

here is code and output where TotalTime is less than 24 hours and correct results

```<code>SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/5101*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HP' AND OpCode = 'FC'
GROUP BY DeptCode, OpCode
</code>```

Results are correct

```<code>Codes   TotalTime   Units   UPH   Goal%
HP-FC   12:37:00    47200   3741    73%
</code>```

Here is actual breakdown to prove

```<code>ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2409193 HP-FC   00:21:00    2161    6174    121%    NAME
2507191 HP-FC   00:23:00    2000    5217    102%    NAME
90290   HP-FC   00:20:00    1704    5112    100%    NAME
31676   HP-FC   02:35:00    11234   4349    85%     NAME
2372437 HP-FC   01:50:00    7884    4300    84%     NAME
2378337 HP-FC   07:08:00    22217   3115    61%     NAME
</code>```

So when I attempt this on a larger table with more rows of data this is what I get. Out put will show TotalTime as an incorrect time.

```<code>SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/1552*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HS' AND OpCode = 'HY'
GROUP BY DeptCode, OpCode
</code>```

Results from query are below. This can not be true time.

```<code>Codes   TotalTime   Units   UPH     Goal%
HS-HY   14:07:00    69204   1114    72%
</code>```

Breakdown to show you that TotalTime should be more than 14:07:00

```<code>ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2377    HS-HY   11:25:00    20891   1830    118%    NAME
3476    HS-HY   04:50:00    6978    1444    93%     NAME
43864   HS-HY   12:20:00    17628   1429    92%     NAME
2372127 HS-HY   03:20:00    4748    1424    92%     NAME
2372129 HS-HY   07:00:00    9158    1308    84%     NAME
2422946 HS-HY   00:47:00    949     1211    78%     NAME
21437   HS-HY   06:02:00    6530    1082    70%     NAME
2372090 HS-HY   11:00:00    2322    211     14%     NAME
63448   HS-HY   03:43:00    0       0       0%      NAME
2372061 HS-HY   01:40:00    0       0       0%      NAME
</code>```

答:
I think your problem is that the time datatype isn't big enough to hold values greater than 24 hours.

You will need to create other types of variables to keep track of hours, minutes, seconds, etc. - as accurately as you need to.

https://learn.microsoft.com/en-us/sql/t-sql/data-types/time-transact-sql

Body:
I am trying to add time from several rows, and when they add up to more than hours I do not get correct results I am looking for. Would like to script TotalTime to allow more than 24 in HH. Does not have to be a datetime datatype.

StartTime and FinishTime are varchar(8) data types.

here is code and output where TotalTime is less than 24 hours and correct results

SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/5101*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HP' AND OpCode = 'FC'
GROUP BY DeptCode, OpCode

Results are correct

Codes   TotalTime   Units   UPH   Goal%
HP-FC   12:37:00    47200   3741    73%

Here is actual breakdown to prove

ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2409193 HP-FC   00:21:00    2161    6174    121%    NAME
2507191 HP-FC   00:23:00    2000    5217    102%    NAME
90290   HP-FC   00:20:00    1704    5112    100%    NAME
31676   HP-FC   02:35:00    11234   4349    85%     NAME
2372437 HP-FC   01:50:00    7884    4300    84%     NAME
2378337 HP-FC   07:08:00    22217   3115    61%     NAME

So when I attempt this on a larger table with more rows of data this is what I get. Out put will show TotalTime as an incorrect time.

SELECT Codes = (DeptCode + '-' +  OpCode)
,TotalTime = convert(time(0),dateadd(second,sum(datediff(second,StartTime,FinishTime)),0))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
,'Goal%' = (convert(varchar,cast((isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60)/1552*100 as decimal(10,0))) + '%')
FROM PTW.dbo.TimeLog
WHERE DeptCode = 'HS' AND OpCode = 'HY'
GROUP BY DeptCode, OpCode

Results from query are below. This can not be true time.

Codes   TotalTime   Units   UPH     Goal%
HS-HY   14:07:00    69204   1114    72%

Breakdown to show you that TotalTime should be more than 14:07:00

ID#     Codes   TotalTime   Units   UPH     Goal%   AssociateName
---     -----   ---------   -----   ---     -----   -------------
2377    HS-HY   11:25:00    20891   1830    118%    NAME
3476    HS-HY   04:50:00    6978    1444    93%     NAME
43864   HS-HY   12:20:00    17628   1429    92%     NAME
2372127 HS-HY   03:20:00    4748    1424    92%     NAME
2372129 HS-HY   07:00:00    9158    1308    84%     NAME
2422946 HS-HY   00:47:00    949     1211    78%     NAME
21437   HS-HY   06:02:00    6530    1082    70%     NAME
2372090 HS-HY   11:00:00    2322    211     14%     NAME
63448   HS-HY   03:43:00    0       0       0%      NAME
2372061 HS-HY   01:40:00    0       0       0%      NAME


问:
replaceing innerHTML of div with some html code
I have  a  div with id xyz.Now i have avariable which has some html code like follows

```<code>var mycode = "<br>jajaj<b>jjja</b> ";
</code>```

Now i want to replace content of div with this html code by using following

```<code>document.getElementbyid("xyz").innerHTML = mycode
</code>```

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

答:
You had missed semicolon

```<code> document.getElementbyid("xyz").innerHTML = mycode;
</code>```

Body:
I have  a  div with id xyz.Now i have avariable which has some html code like follows

var mycode = "
jajajjjja ";

Now i want to replace content of div with this html code by using following

document.getElementbyid("xyz").innerHTML = mycode

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

Body:
You had missed semicolon

 document.getElementbyid("xyz").innerHTML = mycode;


问:
MySQL query much slower when using join
I have a MySQL database and one query which I'm trying to optimize as well as I can.

I'm not familiar with indexes, so I do not know which indexes I should create. At the moment I do not have any indexes and my query is too slow, I think. In fact, using join has made this all much slower. I believed that it would make this faster, but not. I do not understand why this is much slower now.

Any suggestions for indexes? Is there anything else I could make better to make my query faster?

```<code>            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
                    JOIN ki_il ON ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
                    JOIN ka_il ON ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
                    JOIN ki_ka ON ki_ka.id = ki_ka_ot.kaavio_id
                    JOIN ka_ki_ot ON
                            ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
                            AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id
                    JOIN kaa ON ka_ki_ot.kaaviopohja_id = kaa.id
                    JOIN ka_ki ON ka_ki_ot.kierros_id = ka_ki.id
            WHERE ki_ka_ot.kaavio_id = 107
            ORDER BY ka_ki_ot.ottelunumero ASC
</code>```

Update

Instead of using join, I could use FROM ki_ka_ot, ki_il, ka_il, ki_ka, ka_ki_ot, kaa, ka_ki and add several AND conditions to WHERE section. The result of the query would be 100% same, but it would be faster. Should I do it?

```<code>            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
            , ki_il
            , ka_il
            , kaa
            , ka_ki
            , ka_ki_ot
            , ki_ka
            WHERE ki_ka_ot.kaavio_id = 107
            AND ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
            AND ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
            AND ki_ka.id = ki_ka_ot.kaavio_id
            AND ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
            AND ka_ki_ot.kaaviopohja_id = kaa.id
            AND ka_ki_ot.kierros_id = ka_ki.id
            AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id
            ORDER BY ka_ki_ot.ottelunumero ASC
</code>```

Update 2

Now I have modified my original query which uses join. I think it works better and faster, but maybe there is something to fix.

```<code>            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
                    JOIN ki_il ON ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
                    JOIN ka_il ON ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
                    JOIN ki_ka ON ki_ka.id = ki_ka_ot.kaavio_id
                    JOIN ka_ki_ot ON
                            ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
/* AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id */
                    JOIN kaa ON ka_ki_ot.kaaviopohja_id = kaa.id
                    JOIN ka_ki ON ka_ki_ot.kierros_id = ka_ki.id
            WHERE ki_ka_ot.kaavio_id = 107
AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id /* this was moved here */
            ORDER BY ka_ki_ot.ottelunumero ASC
</code>```

答: JOIN is a high cost operation that though the optimizer attempts to perform efficiently it cannot without some context of your data. I cannot suggest specific indexes you should make since I too have no context of your data, but you should attempt to index in a way that impacts any operations you wish to perform. So if you have a JOIN that joins on column A, you'd want to index on A so the optimizer can efficiently perform that JOIN.

Title: MySQL query much slower when using join

Body:
I have a MySQL database and one query which I'm trying to optimize as well as I can.

I'm not familiar with indexes, so I do not know which indexes I should create. At the moment I do not have any indexes and my query is too slow, I think. In fact, using join has made this all much slower. I believed that it would make this faster, but not. I do not understand why this is much slower now.

Any suggestions for indexes? Is there anything else I could make better to make my query faster?

            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
                    JOIN ki_il ON ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
                    JOIN ka_il ON ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
                    JOIN ki_ka ON ki_ka.id = ki_ka_ot.kaavio_id
                    JOIN ka_ki_ot ON
                            ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
                            AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id
                    JOIN kaa ON ka_ki_ot.kaaviopohja_id = kaa.id
                    JOIN ka_ki ON ka_ki_ot.kierros_id = ka_ki.id
            WHERE ki_ka_ot.kaavio_id = 107
            ORDER BY ka_ki_ot.ottelunumero ASC

Update

Instead of using join, I could use FROM ki_ka_ot, ki_il, ka_il, ki_ka, ka_ki_ot, kaa, ka_ki and add several AND conditions to WHERE section. The result of the query would be 100% same, but it would be faster. Should I do it?

            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
            , ki_il
            , ka_il
            , kaa
            , ka_ki
            , ka_ki_ot
            , ki_ka
            WHERE ki_ka_ot.kaavio_id = 107
            AND ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
            AND ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
            AND ki_ka.id = ki_ka_ot.kaavio_id
            AND ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
            AND ka_ki_ot.kaaviopohja_id = kaa.id
            AND ka_ki_ot.kierros_id = ka_ki.id
            AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id
            ORDER BY ka_ki_ot.ottelunumero ASC

Update 2

Now I have modified my original query which uses join. I think it works better and faster, but maybe there is something to fix.

            SELECT ka_ki.kierrosnumero AS kierrosnumero
            , ka_ki.kierroskoodi AS kierroskoodi
            , ka_ki_ot.ottelunumero AS ottelunumero
            , ka_ki.haviajien_sijat_tekstina AS haviajien_sijat_tekstina
            , ka_ki.voittajien_puolelta_cupiin AS voittajien_puolelta_cupiin
            , ka_ki.haviajien_puolelta_cupiin AS haviajien_puolelta_cupiin
            , ka_ki_ot.paikka_a_ja_b_kaaviokoodi AS paikka_a_ja_b_kaaviokoodi
            , ka_ki_ot.paikka_a_kaaviokoodi AS paikka_a_kaaviokoodi
            , ka_ki_ot.paikka_b_kaaviokoodi AS paikka_b_kaaviokoodi
            , ki_ka_ot.id AS ki_ka_ot_id
            , ki_ka_ot.kaaviopaikka_id
            , ki_ka_ot.peli_monesko_peli_ottelussa
            , ki_ka_ot.peli_pelipaikka_id
            , ki_ka_ot.peli_pelimuoto_id
            , ki_ka_ot.peli_voittopisteet
            , ki_ka_ot.peli_ajankohta_aikataulutus
            , ki_ka_ot.peli_ajankohta_alkamisaika
            , ki_ka_ot.peli_ajankohta_loppumisaika
            , ki_ka_ot.peli_paikka_a_tiimiilmo_id
            , ki_ka_ot.peli_paikka_b_tiimiilmo_id
            , ki_ka_ot.peli_paikka_a_peluri1ilm_id
            , ki_ka_ot.peli_paikka_a_peluri2ilm_id
            , ki_ka_ot.peli_paikka_b_peluri1ilm_id
            , ki_ka_ot.peli_paikka_b_peluri2ilm_id
            , ki_il.pari_joukkue_nimi_txt AS peli_paikka_b_pari_joukkue_nimi_txt
            , ki_il.sijoitusnumero_syotetty AS peli_paikka_b_sijoitusnumero_syotetty
            , ki_il.sijoitusnumero_arvottu AS peli_paikka_b_sijoitusnumero_arvottu
            , ka_il.pelaaja_oma_nimi_txt AS peli_paikka_b_peluri1_oma_nimi_txt
            FROM ki_ka_ot
                    JOIN ki_il ON ki_ka_ot.peli_paikka_b_tiimiilmo_id = ki_il.id
                    JOIN ka_il ON ki_ka_ot.peli_paikka_b_peluri1ilm_id = ka_il.id
                    JOIN ki_ka ON ki_ka.id = ki_ka_ot.kaavio_id
                    JOIN ka_ki_ot ON
                            ki_ka.kaaviopohja_id = ka_ki_ot.kaaviopohja_id
/* AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id */
                    JOIN kaa ON ka_ki_ot.kaaviopohja_id = kaa.id
                    JOIN ka_ki ON ka_ki_ot.kierros_id = ka_ki.id
            WHERE ki_ka_ot.kaavio_id = 107
AND ka_ki_ot.id = ki_ka_ot.kaaviopaikka_id /* this was moved here */
            ORDER BY ka_ki_ot.ottelunumero ASC


答:
That's because you are converting the sum to a time datatype, which means "the time portion of a datetime".  So that will never show a total of more than 24, because even in military time, there is no such thing as 25 o'clock.

To get your correct total, one way is to build a varchar datatype instead of a time type.  You will need to construct the varchar string by taking your seconds and dividing by 60 and 60*60 to generate the minute and hour portions.

Title: Adding time that totals more than 24 hrs in SQL


问:
How to get full Wikipedia revision-history list from some article?
How can I get the full Wikipedia revision-history list? (Don't want to scrape)

```<code>import wapiti
import pdb
import pylab as plt
client = wapiti.WapitiClient('mahmoudrhashemi@gmail.com')
get_revs = client.get_page_revision_infos( 'Coffee', 1000000)
print len(gen_revs)

500
</code>```

Package link: https://github.com/mahmoud/wapiti

答:
If you use pywikibot you can pull a generator that will run through the full revision history for you.  For example, to get a generator that will step through all the revisions (including their content) for the page "pagename" in English Wikipedia, use:

```<code>site = pywikibot.Site("en", "wikipedia")
page = pywikibot.Page(site, "pagename")
revs = page.revisions(content=True)
</code>```

There are a lot more parameters you can apply to the query. You can find the API documentation here

Of note is:

revisions(reverse=False, total=None, content=False, rollback=False, starttime=None, endtime=None)

Generator which loads the version history as Revision instances.

pywikibot appears to be the approach taken by many Wikipedia editors to automate editing.

Body:
How can I get the full Wikipedia revision-history list? (Don't want to scrape)

import wapiti
import pdb
import pylab as plt
client = wapiti.WapitiClient('mahmoudrhashemi@gmail.com')
get_revs = client.get_page_revision_infos( 'Coffee', 1000000)
print len(gen_revs)

500

Package link: https://github.com/mahmoud/wapiti

Body:
If you use pywikibot you can pull a generator that will run through the full revision history for you.  For example, to get a generator that will step through all the revisions (including their content) for the page "pagename" in English Wikipedia, use:

site = pywikibot.Site("en", "wikipedia")
page = pywikibot.Page(site, "pagename")
revs = page.revisions(content=True)

There are a lot more parameters you can apply to the query. You can find the API documentation here

Of note is:

revisions(reverse=False, total=None, content=False, rollback=False, starttime=None, endtime=None)

Generator which loads the version history as Revision instances.

pywikibot appears to be the approach taken by many Wikipedia editors to automate editing.

ContentLicense: CC BY-SA 4.0


问:
R: Estimating weighted quantile by group with assignment
I am trying to calculate the quantile (0 to 100) for each observation for a continuous variable (let's call it 'value') within each group when I have sampling weights and assign each observation to its respective quantile in a new variable.

In other words, each row is an observation and each observation belongs to a single group. All of the groups have more than 2 observations. Within each group, I need to estimate the distribution of value using the sampling weights in my data, determine at which percentile an observation falls within its group's distribution, then add that percentile as a column to the data frame.

As far as I can tell, the survey package has svyby() and svyquantile() but the latter returns values for the specified quantiles rather than the quantile of a  value for a given observation.

```<code># Load survey package
library(survey)

# Set seed for replication
set.seed(123)

# Create data with value, group, weight
dat <- data.frame(value = 1:6,
                  group = rep(1:3,2),
                  weight = abs(rnorm(6))
# Declare survey design
d <- survey::svydesign(id =~1, data = dat, weights = weight)

# Do something to calculate the quantile and add it to the data
????
</code>```

This is similar to this question but is not done by subgroup: Compute quantiles incorporating Sample Design (Survey package)

答:
I put together a solution. The below sequence of statements in mutate() can be modified to convert the sampling weights into whatever quantiles are of interest. While this could be done in base R, I use the dplyr package due to the power of dplyr::bind_rows() to add in NAs when joining two data frames.

```<code># Set seed for replication
set.seed(123)

# Create data with value, group, weight
dat <- data.frame(value = 1:6,
                  group = rep(1:3,2),
                  weight = abs(rnorm(6))

# Initialize list for storing group results
# Setting the length of the list is quicker than
# creating an empty list and growing it
quantile_list <- vector("list", length(unique(dat$group)))

# Initialize variable to indicate initial iteration
iteration <- 0

# estimate the decile of each respondent
# in a large for-loop

for(group in unique(dat$group)) {

# Keep only observations for a given group
  temp <- dat %>% dplyr::filter(group == group)

  # Create subset with missing values
  temp_missing <- temp %>% dplyr::filter(is.na(value))

  # Create subset without missing values
  temp_nonmissing <- temp %>% dplyr::filter(!is.na(value))

  # Sort observations with value on value, calculate cumulative
  # sum of sampling weights, create variable indicating the decile
  # of responses. 1 = lowest, 10 = highest
  temp_nonmissing <- temp_nonmissing %>%
                            dplyr::arrange(value) %>%
                            dplyr::mutate(cumulative_weight = cumsum(weight),
                                          cumulative_weight_prop = cumulative_weight / sum(weight),
                                          decile = dplyr::case_when(cumulative_weight_prop < 0.10 ~ 1,
                                          cumulative_weight_prop >= 0.10 & cumulative_weight_prop < 0.20 ~ 2,
                                          cumulative_weight_prop >= 0.20 & cumulative_weight_prop < 0.30 ~ 3,
                                          cumulative_weight_prop >= 0.30 & cumulative_weight_prop < 0.40 ~ 4,
                                          cumulative_weight_prop >= 0.40 & cumulative_weight_prop < 0.50 ~ 5,
                                          cumulative_weight_prop >= 0.50 & cumulative_weight_prop < 0.60 ~ 6,
                                          cumulative_weight_prop >= 0.60 & cumulative_weight_prop < 0.70 ~ 7,
                                          cumulative_weight_prop >= 0.70 & cumulative_weight_prop < 0.80 ~ 8,
                                          cumulative_weight_prop >= 0.80 & cumulative_weight_prop < 0.90 ~ 9 ,
                                          cumulative_weight_prop >= 0.90 ~ 10))

  # Increment the iteration of the for loop
  iteration <- iteration + 1

  # Join the data with missing values and the data without
  # missing values on the value variable into
  # a single data frame
  quantile_list[[iteration]] <- dplyr::bind_rows(temp_nonmissing, temp_missing)
  }

# Convert the list of data frames into a single dataframe
out <- dplyr::bind_rows(quantile_list)

# Show outcome
head(out)
</code>```

Body:
I am trying to calculate the quantile (0 to 100) for each observation for a continuous variable (let's call it 'value') within each group when I have sampling weights and assign each observation to its respective quantile in a new variable.

In other words, each row is an observation and each observation belongs to a single group. All of the groups have more than 2 observations. Within each group, I need to estimate the distribution of value using the sampling weights in my data, determine at which percentile an observation falls within its group's distribution, then add that percentile as a column to the data frame.

As far as I can tell, the survey package has svyby() and svyquantile() but the latter returns values for the specified quantiles rather than the quantile of a  value for a given observation.

# Load survey package
library(survey)

# Set seed for replication
set.seed(123)

# Create data with value, group, weight
dat <- data.frame(value = 1:6,
                  group = rep(1:3,2),
                  weight = abs(rnorm(6))
# Declare survey design
d <- survey::svydesign(id =~1, data = dat, weights = weight)

# Do something to calculate the quantile and add it to the data
????

This is similar to this question but is not done by subgroup: Compute quantiles incorporating Sample Design (Survey package)

Body:
I put together a solution. The below sequence of statements in mutate() can be modified to convert the sampling weights into whatever quantiles are of interest. While this could be done in base R, I use the dplyr package due to the power of dplyr::bind_rows() to add in NAs when joining two data frames.

# Set seed for replication
set.seed(123)

# Create data with value, group, weight
dat <- data.frame(value = 1:6,
                  group = rep(1:3,2),
                  weight = abs(rnorm(6))

# Initialize list for storing group results
# Setting the length of the list is quicker than
# creating an empty list and growing it
quantile_list <- vector("list", length(unique(dat$group)))

# Initialize variable to indicate initial iteration
iteration <- 0

# estimate the decile of each respondent
# in a large for-loop

for(group in unique(dat$group)) {

# Keep only observations for a given group
  temp <- dat %>% dplyr::filter(group == group)

  # Create subset with missing values
  temp_missing <- temp %>% dplyr::filter(is.na(value))

  # Create subset without missing values
  temp_nonmissing <- temp %>% dplyr::filter(!is.na(value))

  # Sort observations with value on value, calculate cumulative
  # sum of sampling weights, create variable indicating the decile
  # of responses. 1 = lowest, 10 = highest
  temp_nonmissing <- temp_nonmissing %>%
                            dplyr::arrange(value) %>%
                            dplyr::mutate(cumulative_weight = cumsum(weight),
                                          cumulative_weight_prop = cumulative_weight / sum(weight),
                                          decile = dplyr::case_when(cumulative_weight_prop < 0.10 ~ 1,
                                          cumulative_weight_prop >= 0.10 & cumulative_weight_prop < 0.20 ~ 2,
                                          cumulative_weight_prop >= 0.20 & cumulative_weight_prop < 0.30 ~ 3,
                                          cumulative_weight_prop >= 0.30 & cumulative_weight_prop < 0.40 ~ 4,
                                          cumulative_weight_prop >= 0.40 & cumulative_weight_prop < 0.50 ~ 5,
                                          cumulative_weight_prop >= 0.50 & cumulative_weight_prop < 0.60 ~ 6,
                                          cumulative_weight_prop >= 0.60 & cumulative_weight_prop < 0.70 ~ 7,
                                          cumulative_weight_prop >= 0.70 & cumulative_weight_prop < 0.80 ~ 8,
                                          cumulative_weight_prop >= 0.80 & cumulative_weight_prop < 0.90 ~ 9 ,
                                          cumulative_weight_prop >= 0.90 ~ 10))

  # Increment the iteration of the for loop
  iteration <- iteration + 1

  # Join the data with missing values and the data without
  # missing values on the value variable into
  # a single data frame
  quantile_list[[iteration]] <- dplyr::bind_rows(temp_nonmissing, temp_missing)
  }

# Convert the list of data frames into a single dataframe
out <- dplyr::bind_rows(quantile_list)

# Show outcome
head(out)


问:
Python Twisted - How to send the data over the connected socket connections?
I've a server as follow:-

```<code>class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))
</code>```

The above code receives the message and replies back with the same message. However, my use case is different.

I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.

How can I do it? How can I call sendMessage function outside the class?

答:
Are you sure you don't want to just use WAMP instead of raw WebSockets?

This might be a lot easier for your use-case, as "broadcast information to interested clients" is exactly what the Publish/Subscribe pattern is for.

Body:
I've a server as follow:-

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

The above code receives the message and replies back with the same message. However, my use case is different.

I'm processing some data, storing it into the DB and then finally want to send the data to the connected clients, or one type of data to specific set of connected clients and the other type to another.

How can I do it? How can I call sendMessage function outside the class?