问:
Grouping Joined Tables
I am trying to join the products and attributes tables and group them by product id in order to get a list of products with their attributes. So I tried the following Entity Framework query:

```<code>    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                     {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                  group t by t.product.id into g
                                     select new
                                     {
                                         product = g.Select(p => p.product).FirstOrDefault(),
                                         attributes = g.Select(r => new Attr()
                                         {
                                             a1 = r.a1,
                                             a2 = r.a2,
                                             a3 = r.a3,
                                             a4 = r.a4
                                         }).ToList()
                                     }
                                    ).ToList();
</code>```

But this took around 70 minutes and when I looked into the SQL query it produced, I saw tens of subqueries with tens of joins.

Then I tried just to do the grouping on the sql server and did the projection into the desired structure on the application server. And this is the EF code for that:

```<code>    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                      group t by t.product.id

                            ).ToList();
</code>```

This took around 3 minutes. But the SQL prodcued by this query still looked complex with multiple subqueries and joins. I would epect something along the lines of:

```<code>select product.*, attribute.a1, attribute.a2, attribute.a3, attribute.a4
from product
join attribute on product.id = attribute.productId
group by product.id
</code>```

Then I tried just the join without grouping:

```<code>    var productsWithAttributes = (from product in ctx.products
                                      join attribute in ctx.attributes on product.id equals attribute.productId
                                      select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4,

                                      }
                                    ).ToList();
</code>```

This took 1.5 minutes and the SQL code produced by EF was as expected.

In short, adding grouping to the join creates a convoluted SQL query which takes longer but it is still acceptable in terms of performance. But adding the final projection after this grouping produces an increadibly convoluted SQL query that takes and unaccepytable amount of time.

What is the correct way of creating this query with EF?

答:
The recommended way of creating such query in LINQ to Entities is to use collection navigation property, or in case it is missing - Group Join construct (join ... into):

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.

Something like this:

```<code>var productsWithAttributes = (
    from product in ctx.products
    join attribute in ctx.attributes on product.id equals attribute.productId
    into attributes // <-- emulate product.attributes property
    select new
    {
        product = product,
        attributes = attributes.Select(attribute => new Attr()
        {
            a1 = attribute.a1,
            a2 = attribute.a2,
            a3 = attribute.a3,
            a4 = attribute.a4
         }).ToList(),
     }).ToList();
</code>```

Title: Grouping Joined Tables

Body:
I am trying to join the products and attributes tables and group them by product id in order to get a list of products with their attributes. So I tried the following Entity Framework query:

    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                     {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                  group t by t.product.id into g
                                     select new
                                     {
                                         product = g.Select(p => p.product).FirstOrDefault(),
                                         attributes = g.Select(r => new Attr()
                                         {
                                             a1 = r.a1,
                                             a2 = r.a2,
                                             a3 = r.a3,
                                             a4 = r.a4
                                         }).ToList()
                                     }
                                    ).ToList();

But this took around 70 minutes and when I looked into the SQL query it produced, I saw tens of subqueries with tens of joins.

Then I tried just to do the grouping on the sql server and did the projection into the desired structure on the application server. And this is the EF code for that:

    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                      group t by t.product.id

                            ).ToList();

This took around 3 minutes. But the SQL prodcued by this query still looked complex with multiple subqueries and joins. I would epect something along the lines of:

select product.*, attribute.a1, attribute.a2, attribute.a3, attribute.a4
from product
join attribute on product.id = attribute.productId
group by product.id

Then I tried just the join without grouping:

    var productsWithAttributes = (from product in ctx.products
                                      join attribute in ctx.attributes on product.id equals attribute.productId
                                      select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4,

                                      }
                                    ).ToList();

This took 1.5 minutes and the SQL code produced by EF was as expected.

In short, adding grouping to the join creates a convoluted SQL query which takes longer but it is still acceptable in terms of performance. But adding the final projection after this grouping produces an increadibly convoluted SQL query that takes and unaccepytable amount of time.

What is the correct way of creating this query with EF?

Body:
The recommended way of creating such query in LINQ to Entities is to use collection navigation property, or in case it is missing - Group Join construct (join ... into):

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.

Something like this:

var productsWithAttributes = (
    from product in ctx.products
    join attribute in ctx.attributes on product.id equals attribute.productId
    into attributes // <-- emulate product.attributes property
    select new
    {
        product = product,
        attributes = attributes.Select(attribute => new Attr()
        {
            a1 = attribute.a1,
            a2 = attribute.a2,
            a3 = attribute.a3,
            a4 = attribute.a4
         }).ToList(),
     }).ToList();


来源: stackexchange

问:
React Native (Redux) FlatList jumping to top of list when onEndReached called
I have a FlatList in ReactNative which pulls a list of articles from an API. When the end of the list is reached on scrolling, a further page of articles is pulled from the API and appended to the articles list in a Redux reducer.

The FlatList is set up as:

```<code>render() {
    return(
    <FlatList data={this.props.articles.articles} // The initial articles list via Redux state
        renderItem={this.renderArticleListItem} // Just renders the list item.
        onEndReached={this.pageArticles.bind(this)} // Simply calls a Redux Action Creator/API
        onEndReachedThreshold={0}
        keyExtractor={item => item.id.toString()}/>
   )};
</code>```

The Redux 'articles' state object is mapped to the component using the React Redux connect function.  The relevant reducer (some items removed for brevity) looks like:

```<code>/// Initial 'articles' state object
const INITIAL_STATE = {
    articles: [],
    loading: false,
    error: '',
    pageIndex: 0,
    pageSize: 10
};

export default(state = INITIAL_STATE, action) => {
switch(action.type){
    // The relevant part for returning articles from the API
    case ARTICLES_SUCCESS:
        return { ...state, loading: false, articles: state.articles.concat(action.payload.items),
            pageIndex: action.payload.pageIndex, pageSize: action.payload.pageSize}
   default:
       return state;
   }
}
</code>```

The payload is a simple object - the articles are contained in the action.payload.items array, and there is additional paging information as well in the payload (not important to this problem).

Everything is fine with the API returning the correct data.

The problem is that when the end of the FlatList is reached on scrolling, the API is called, the new articles are pulled fine and appended to the this.props.articles state object and to the FlatList, BUT the FlatList jumps/scrolls back to the first item in the list.

I think the problem is probably with how I am returning the state in the Redux reducer but I'm not sure why.

Is using concat the correct way to return the new state with the new articles appended?

答:
It might be too late to answer this but I experienced exact same problem having my data served from redux to the component and managed to fix the jumping effect by making my component a normal Component rather than PureComponent allowing me to use shouldComponentUpdate life-cycle hook method. This how the method should look like for you component:

```<code>shouldComponentUpdate(nextProps) {
   if (this.props.articles === nextProps.articles) {
       return false;
   }

   return true;
}
</code>```

This method (if implemented) should return a boolean value indicating whether the component should update or not. What i did here was to prevent the component from re-rendering in case the contents of articles hasn't changed.

Hope this would be helpful for you or others who might have faced similar problem.

ContentLicense: CC BY-SA 4.0

Body:
I have a FlatList in ReactNative which pulls a list of articles from an API. When the end of the list is reached on scrolling, a further page of articles is pulled from the API and appended to the articles list in a Redux reducer.

The FlatList is set up as:

render() {
    return(
    <FlatList data={this.props.articles.articles} // The initial articles list via Redux state
        renderItem={this.renderArticleListItem} // Just renders the list item.
        onEndReached={this.pageArticles.bind(this)} // Simply calls a Redux Action Creator/API
        onEndReachedThreshold={0}
        keyExtractor={item => item.id.toString()}/>
   )};

The Redux 'articles' state object is mapped to the component using the React Redux connect function.  The relevant reducer (some items removed for brevity) looks like:

/// Initial 'articles' state object
const INITIAL_STATE = {
    articles: [],
    loading: false,
    error: '',
    pageIndex: 0,
    pageSize: 10
};

export default(state = INITIAL_STATE, action) => {
switch(action.type){
    // The relevant part for returning articles from the API
    case ARTICLES_SUCCESS:
        return { ...state, loading: false, articles: state.articles.concat(action.payload.items),
            pageIndex: action.payload.pageIndex, pageSize: action.payload.pageSize}
   default:
       return state;
   }
}

The payload is a simple object - the articles are contained in the action.payload.items array, and there is additional paging information as well in the payload (not important to this problem).

Everything is fine with the API returning the correct data.

The problem is that when the end of the FlatList is reached on scrolling, the API is called, the new articles are pulled fine and appended to the this.props.articles state object and to the FlatList, BUT the FlatList jumps/scrolls back to the first item in the list.

I think the problem is probably with how I am returning the state in the Redux reducer but I'm not sure why.

Is using concat the correct way to return the new state with the new articles appended?

Body:
It might be too late to answer this but I experienced exact same problem having my data served from redux to the component and managed to fix the jumping effect by making my component a normal Component rather than PureComponent allowing me to use shouldComponentUpdate life-cycle hook method. This how the method should look like for you component:

shouldComponentUpdate(nextProps) {
   if (this.props.articles === nextProps.articles) {
       return false;
   }

   return true;
}

This method (if implemented) should return a boolean value indicating whether the component should update or not. What i did here was to prevent the component from re-rendering in case the contents of articles hasn't changed.

Hope this would be helpful for you or others who might have faced similar problem.


问:
Why my state always is default value when call inside Callback?
I don't know exactly what is my problem.
I used some library.
When i use callback and trying to get state of Component, the state always is default value.

Example when i use mui-datatables https://github.com/gregnb/mui-datatables

```<code>import React, { useState } from 'react'
import MUIDataTable from "mui-datatables";

const columns = [
    {
        name: "name",
        label: "Name",
    },
    {
        name: "company",
        label: "Company",
    },
    {
        name: "city",
        label: "City",
    },
    {
        name: "state",
        label: "State",
    },
];

const data = [
    { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
    { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
    { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
    { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const MyComponent = () => {

    const [myState, setMyState] = useState("default value");
    const onRowClick = (rowData, rowMeta) => {
        console.log(myState) //always default value
    }

    const options = {
        onRowClick: onRowClick
    }
    return (
        <div>
            <MUIDataTable
                title={"Employee List"}
                data={data}
                columns={columns}
                options={options}
            />

            <button onClick={ () => setMyState("State changed")}>Change state</button>
            <p>{myState}</p>

        </div>
    )
}

</code>```

First, I click button to change MyState, the state changed in p tag.
Next, I click any row to console MyState. But, it's always is default value.
Why?
Code in CodeSanBox: https://codesandbox.io/s/dreamy-germain-tuylh

答:
It's something with mui-table. Looks like it does not handle if options.rowClickis changed. I've put breakpoint into MUIDataTable.render() and it's called just once. Providing different options does not re-render that.

So if I add key like

```<code><MUIDataTable
  key={myState}
  ...
</code>```

to force it be re-created instead of updating - it works and State changed is displayed in console.

But maybe it'd be better to file issue in their github. Or try most recent version.

Body:
I don't know exactly what is my problem.
I used some library.
When i use callback and trying to get state of Component, the state always is default value.

Example when i use mui-datatables https://github.com/gregnb/mui-datatables

import React, { useState } from 'react'
import MUIDataTable from "mui-datatables";

const columns = [
    {
        name: "name",
        label: "Name",
    },
    {
        name: "company",
        label: "Company",
    },
    {
        name: "city",
        label: "City",
    },
    {
        name: "state",
        label: "State",
    },
];

const data = [
    { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
    { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
    { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
    { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const MyComponent = () => {

    const [myState, setMyState] = useState("default value");
    const onRowClick = (rowData, rowMeta) => {
        console.log(myState) //always default value
    }

    const options = {
        onRowClick: onRowClick
    }
    return (

            <MUIDataTable
                title={"Employee List"}
                data={data}
                columns={columns}
                options={options}
            />

            <button onClick={ () => setMyState("State changed")}>Change state</button>

{myState}

    )
}

First, I click button to change MyState, the state changed in p tag.
Next, I click any row to console MyState. But, it's always is default value.
Why?
Code in CodeSanBox: https://codesandbox.io/s/dreamy-germain-tuylh

Body:
It's something with mui-table. Looks like it does not handle if options.rowClickis changed. I've put breakpoint into MUIDataTable.render() and it's called just once. Providing different options does not re-render that.

So if I add key like

<MUIDataTable
  key={myState}
  ...

to force it be re-created instead of updating - it works and State changed is displayed in console.

But maybe it'd be better to file issue in their github. Or try most recent version.


问:
Subscribing multiple handlers to DOM Events with jQuery
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

```<code>$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});
</code>```

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>
</code>```

This code works correctly, by alerting 'refreshing'

```<code>  <div class="refresh-cart">Refresh Widget</div>
</code>```

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>
</code>```

What am I doing wrong and how can I make both handlers fire?

答: It works fine for me as well. I think you should also consider jquery form plugin here for ajax submit and changing the input type from submit to button</p>

Body:
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>

This code works correctly, by alerting 'refreshing'

Refresh Widget

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>

What am I doing wrong and how can I make both handlers fire?

ContentLicense: CC BY-SA 3.0


问:
Opencv: How to draw a circle contour on an image
I have written a python function, which is supposed to draw a circle on an image, where the center point of the circle has been defined using a mouse call back:

```<code>def draw_circle_contour(frame, pt, radius):
    cv2.circle(frame, center=pt, radius=3, color=(255,0,0), thickness=-1)
    discretized_circle_contour_x = [pt[0] + radius*np.cos(theta) for theta in np.linspace(0, 36, 36)]
    discretized_circle_contour_x = map(int, discretized_circle_contour_x)
    discretized_circle_contour_y = [pt[1] + radius*np.sin(theta) for theta in np.linspace(0, 36, 36)]
    discretized_circle_contour_y = map(int, discretized_circle_contour_y)
    discretized_circle_contour = zip(discretized_circle_contour_x, discretized_circle_contour_y)
    for el in discretized_circle_contour:
        cv2.circle(frame, center=el, radius=2, color=(255,0,0), thickness=-1)
</code>```

Now, this works perfectly when I specify theta to be within np.linspace(0,360,360). However, I only want to draw 1/10 of a circle now. I.e. I want to draw a circle contour where the angle that is being covered is 36°. I figured this code should work, but for some reason when I run it, the result looks like this:

What is going on here? Can anyone tell?

As you have pointed out: Instead of drawing little circles/points I could also use cv2.polylines to draw a circle segment. This simply requires the last two lines to be replaced with:

```<code>for el in discretized_circle_contour:
        help.append(list(el))
    cv2.polylines(frame, [np.asarray(help)], isClosed=False, color=(255,0,0), thickness=1)
</code>```

However, I am still facing the issue that this segment gets drawn multiple times, while I want it to be drawn only once in between [0,36] degrees!

... and I just found the reason for that: the angle theta needs to be given in radians, not in degrees. Whops.

Final result looks like this:

答:
What's happening is, you're drawing a filled circle with radius 2 (which looks like a dot, because the radius is very small) in each point in discretized_circle_contour.

If I understand your question correctly, what you actually want is just an arch spanning 1/10th of the radius.
You already have the points for the arch in [0, 36] degrees, just draw it as a polyline instead:

```<code>cv2.polylines(frame, [discretized_circle_contour], False, 1)
</code>```

Body:
I have written a python function, which is supposed to draw a circle on an image, where the center point of the circle has been defined using a mouse call back:

def draw_circle_contour(frame, pt, radius):
    cv2.circle(frame, center=pt, radius=3, color=(255,0,0), thickness=-1)
    discretized_circle_contour_x = [pt[0] + radius*np.cos(theta) for theta in np.linspace(0, 36, 36)]
    discretized_circle_contour_x = map(int, discretized_circle_contour_x)
    discretized_circle_contour_y = [pt[1] + radius*np.sin(theta) for theta in np.linspace(0, 36, 36)]
    discretized_circle_contour_y = map(int, discretized_circle_contour_y)
    discretized_circle_contour = zip(discretized_circle_contour_x, discretized_circle_contour_y)
    for el in discretized_circle_contour:
        cv2.circle(frame, center=el, radius=2, color=(255,0,0), thickness=-1)

Now, this works perfectly when I specify theta to be within np.linspace(0,360,360). However, I only want to draw 1/10 of a circle now. I.e. I want to draw a circle contour where the angle that is being covered is 36°. I figured this code should work, but for some reason when I run it, the result looks like this:

What is going on here? Can anyone tell?

As you have pointed out: Instead of drawing little circles/points I could also use cv2.polylines to draw a circle segment. This simply requires the last two lines to be replaced with:

for el in discretized_circle_contour:
        help.append(list(el))
    cv2.polylines(frame, [np.asarray(help)], isClosed=False, color=(255,0,0), thickness=1)

However, I am still facing the issue that this segment gets drawn multiple times, while I want it to be drawn only once in between [0,36] degrees!

... and I just found the reason for that: the angle theta needs to be given in radians, not in degrees. Whops.

Final result looks like this:

Body:
What's happening is, you're drawing a filled circle with radius 2 (which looks like a dot, because the radius is very small) in each point in discretized_circle_contour.

If I understand your question correctly, what you actually want is just an arch spanning 1/10th of the radius.
You already have the points for the arch in [0, 36] degrees, just draw it as a polyline instead:

cv2.polylines(frame, [discretized_circle_contour], False, 1)


问:
Hazelcast node not discovering other node when use docker stack deploy
I need to setup a hazelcast for web application with multiple replication factors in docker environment and using docker swarm to deploy the app in multi host using overlay network.

I am facing the problem that service are not able to discover the other node in swarm mode, however working fine in docker compose. I am using below config for hazelcast configuration.

```<code><port auto-increment="true">5701</port>
<join>
  <multicast enabled="false">
    <multicast-group>224.2.2.3</multicast-group>
    <multicast-port>54327</multicast-port>
  </multicast>
  <tcp-ip enabled="true">
    <member>hazelcast-master</member>
  </tcp-ip>

</join>
</code>```

here hazelcast-master is my service name in docker.

Any help would be appreciated

答:
I think that mutlicast may not work (at least out of the box) in Docker Swarm. Read this and this. Docker Compose works only because it's deployed on one single host machine.

What you can do is try to use the Hazelcast Docker Swarm Discovery Plugin. Other than that, the other option is the static TCP-IP configuration, which probably does not make much sense in Docker Swarm.

Body:
I need to setup a hazelcast for web application with multiple replication factors in docker environment and using docker swarm to deploy the app in multi host using overlay network.

I am facing the problem that service are not able to discover the other node in swarm mode, however working fine in docker compose. I am using below config for hazelcast configuration.

<port auto-increment="true">5701</port>
<join>
  <multicast enabled="false">
    <multicast-group>224.2.2.3</multicast-group>
    <multicast-port>54327</multicast-port>
  </multicast>
  <tcp-ip enabled="true">
    <member>hazelcast-master</member>
  </tcp-ip>

</join>

here hazelcast-master is my service name in docker.

Any help would be appreciated


问:
HMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered
Just ran into an issue with a has_many :through association and after/before-destroy callbacks not being triggered.

Say, I have users, groups, and an intermediate relation called membership.
I have a form that allows users to be enrolled into groups by creating a new membership record when they check off associated checkboxes. Basically an array of group_ids.

Looks something like this:

```<code>Which group would you like to join? (check all that apply)
[] Group A
[] Group B
[] Group C
</code>```

And I wish to record actions such as joining a group or leaving a group to activity log table and do some other less important thigns.

I have the following defined:

```<code>class Group < AR::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

class Membership < AR::Base
  belongs_to :user
  belongs_to :group

  after_create :log_event_to_audit_table
  after_destroy :log_event_to_audit_table

end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

  attr_accessible :group_ids   # enables mass-assignment
end
</code>```

When a new membership record is created the after_create is run as expected. However, the after_destroy does not get triggered!

After google-ing and read up the docs I discovered the reason why:

"Automatic deletion of join models is
  direct, no destroy callbacks are
  triggered" - from Ruby Guides.

Hmmmmmm...

So the join model's (in this case Membership's) destroy callbacks are not being triggered. Well that's a downer. Any reason as to why?

So my question what is the best way to work around this issue?
Should I define my own membership_ids= method in User model that calls membership.destroy directly?

Open to any suggestions about the best practices in such a scenario.

Thanks!

答:
adding dependent: :destroy to the has many relationship actually calls the before_destroy and after_destroy methods in the Membership class.

class User < ActiveRecord::Base
  has_many :groups, through: :memberships, dependent: :destroy
end
```

ContentLicense: CC BY-SA 2.5

Body:
Just ran into an issue with a has_many :through association and after/before-destroy callbacks not being triggered.

Say, I have users, groups, and an intermediate relation called membership.
I have a form that allows users to be enrolled into groups by creating a new membership record when they check off associated checkboxes. Basically an array of group_ids.

Looks something like this:

Which group would you like to join? (check all that apply)
[] Group A
[] Group B
[] Group C

And I wish to record actions such as joining a group or leaving a group to activity log table and do some other less important thigns.

I have the following defined:

class Group < AR::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

class Membership < AR::Base
  belongs_to :user
  belongs_to :group

  after_create :log_event_to_audit_table
  after_destroy :log_event_to_audit_table

end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships

  attr_accessible :group_ids   # enables mass-assignment
end

When a new membership record is created the after_create is run as expected. However, the after_destroy does not get triggered!

After google-ing and read up the docs I discovered the reason why:

"Automatic deletion of join models is
  direct, no destroy callbacks are
  triggered" - from Ruby Guides.

Hmmmmmm...

So the join model's (in this case Membership's) destroy callbacks are not being triggered. Well that's a downer. Any reason as to why?

So my question what is the best way to work around this issue?
Should I define my own membership_ids= method in User model that calls membership.destroy directly?

Open to any suggestions about the best practices in such a scenario.

Thanks!


问:
PyCharm see Object Data Type
Currently I am dealing with a lot of code inspection in pycharm. Often I have the problem that I don't know which is the actual data type of a variable in python. Then I have to revisit the code to find the actual definition of the variable, or use some inserted code snippets like type() to get the data format.

What would be the most elegant / most comfortable way to do this task? I though maybe there are some built-in functions in PyCharm.

答:
Welcome to stackoverflow. You can always try to have a look at the Quick documentation to get a documentation hint in the Jetbrains IDEs.

But since Python is dynamically typed this might not help you every time if you are not using Python type hints and the code is getting "complicated". There is a shortcut to look at the definition of a symbol/variable which will allow you to remember what type you intented to use.

You have to be aware though that you can change what you bind to a variable, meaning that at the beginning foo binds an integer (foo = 0) and later you change it to a string (foo = ""). This is totally fine is Python and therefore the code inspection of PyCharm might give you wrong information.

Title: PyCharm see Object Data Type


问:
Android how to reset ImageView layout to original after zooming and drag
I need to implement zooming, panning and then reset the ImageView to original scale/location.  I use view.setImageMatrix(matrix) to perform zooming and moving in FrameLayout. Works perfectly so far.  To restore to original layout, I tried to save the original matrix and reset to it,   It doesn't work and I am kinda stuck. Appreciate any suggestions or tips!

The following are my current code:

a ViewPager contains fragments per Image

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
</code>```

The fragment contains ImageView

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/ivPage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:scaleType="matrix"
        android:src="@drawable/catalogue_test" />
</FrameLayout>
</code>```

The java code does the zooming and panning work just fine, that actually was original from a tutorial page:

```<code>@Override
public boolean onTouch(View v, MotionEvent event) {

      ImageView view = (ImageView) v;

      switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN:
         Log.d(tag, "ACTION_DOWN");
         isDoubleTap = false;

         savedMatrix.set(matrix);
         start.set(event.getX(), event.getY());
         Log.d(tag, "mode=DRAG");
         mode = DRAG;
         break;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_POINTER_UP:
         Log.d(tag, "ACTION_POINTER_UP");
         mode = NONE;
         Log.d(tag, "mode=NONE");
         break;
      case MotionEvent.ACTION_MOVE:
         Log.d(tag, "ACTION_MOVE");
         if (mode == DRAG) {
            matrix.set(savedMatrix);
            matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
         } else if (mode == ZOOM) {
            double newDist = spacing(event);
            Log.d(tag, "newDist=" + newDist);
            if (newDist > 10f) {
               matrix.set(savedMatrix);
               float scale = (float) (newDist / oldDist);
               matrix.postScale(scale, scale, mid.x, mid.y);
            }
         }

         if(isDoubleTap == false) {
            view.setImageMatrix(matrix);
            Log.d(tag, String.format("(%d, %d) - scale(%f, %f) xy(%f, %f)", view.getTop(), view.getLeft(),  view.getScaleX(), view.getScaleY(), view.getX(), view.getY()));
         }

         break;

      case MotionEvent.ACTION_POINTER_DOWN:
         oldDist = spacing(event);
         Log.d(tag, "oldDist=" + oldDist);
         if (oldDist > 10f) {
            savedMatrix.set(matrix);
            midPoint(mid, event);
            mode = ZOOM;
            Log.d(tag, "mode=ZOOM");
         }
         break;
      }

      gestureDetector.onTouchEvent(event);
      return true; // indicate event was handled
   }
</code>```

答:
I know this is old but here is my answer.

1-)get startedMatrix of imageView onCreate method

2-)and changed ACTION_POINTER and ACTION_POINTER_UP method to these

```<code>       --- case MotionEvent.ACTION_UP: // first finger lifted
               mode = NONE;
               break;
           case MotionEvent.ACTION_POINTER_UP:// second finger lifted
               fingerLifted();
               matrix.set(startedMatrix);
               view.setScaleType(ImageView.ScaleType.MATRIX);
               mode = NONE;
               Log.d(TAG, "mode=NONE");
               break;
</code>```

I hope this will help.

Body:
I need to implement zooming, panning and then reset the ImageView to original scale/location.  I use view.setImageMatrix(matrix) to perform zooming and moving in FrameLayout. Works perfectly so far.  To restore to original layout, I tried to save the original matrix and reset to it,   It doesn't work and I am kinda stuck. Appreciate any suggestions or tips!

The following are my current code:

a ViewPager contains fragments per Image

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

The fragment contains ImageView

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/ivPage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:scaleType="matrix"
        android:src="@drawable/catalogue_test" />
</FrameLayout>

The java code does the zooming and panning work just fine, that actually was original from a tutorial page:

@Override
public boolean onTouch(View v, MotionEvent event) {

      ImageView view = (ImageView) v;

      switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN:
         Log.d(tag, "ACTION_DOWN");
         isDoubleTap = false;

         savedMatrix.set(matrix);
         start.set(event.getX(), event.getY());
         Log.d(tag, "mode=DRAG");
         mode = DRAG;
         break;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_POINTER_UP:
         Log.d(tag, "ACTION_POINTER_UP");
         mode = NONE;
         Log.d(tag, "mode=NONE");
         break;
      case MotionEvent.ACTION_MOVE:
         Log.d(tag, "ACTION_MOVE");
         if (mode == DRAG) {
            matrix.set(savedMatrix);
            matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
         } else if (mode == ZOOM) {
            double newDist = spacing(event);
            Log.d(tag, "newDist=" + newDist);
            if (newDist > 10f) {
               matrix.set(savedMatrix);
               float scale = (float) (newDist / oldDist);
               matrix.postScale(scale, scale, mid.x, mid.y);
            }
         }

         if(isDoubleTap == false) {
            view.setImageMatrix(matrix);
            Log.d(tag, String.format("(%d, %d) - scale(%f, %f) xy(%f, %f)", view.getTop(), view.getLeft(),  view.getScaleX(), view.getScaleY(), view.getX(), view.getY()));
         }

         break;

      case MotionEvent.ACTION_POINTER_DOWN:
         oldDist = spacing(event);
         Log.d(tag, "oldDist=" + oldDist);
         if (oldDist > 10f) {
            savedMatrix.set(matrix);
            midPoint(mid, event);
            mode = ZOOM;
            Log.d(tag, "mode=ZOOM");
         }
         break;
      }

      gestureDetector.onTouchEvent(event);
      return true; // indicate event was handled
   }

Body:
I know this is old but here is my answer.

1-)get startedMatrix of imageView onCreate method

2-)and changed ACTION_POINTER and ACTION_POINTER_UP method to these

       --- case MotionEvent.ACTION_UP: // first finger lifted
               mode = NONE;
               break;
           case MotionEvent.ACTION_POINTER_UP:// second finger lifted
               fingerLifted();
               matrix.set(startedMatrix);
               view.setScaleType(ImageView.ScaleType.MATRIX);
               mode = NONE;
               Log.d(TAG, "mode=NONE");
               break;

I hope this will help.


问:
Is it possible to inject shell/python commands from a configuration file?
Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated:

```<code>var1,data1
var2,data2
var3,data3
</code>```

So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that will allow some arbitrary code execution? The only thing I can imagine if you you made the poor choice to make var1 be a shell command that you execute with os.sys(data1) in your own code somewhere. Also, if this were C then you would have to worry about buffers being blown, but I don't think you have to worry about that with python. If your reading in that data as a string is it possible to somehow escape the string "\n os.sys('rm -r /'), this SQL like example totally wont work, but is there similar that is possible?

答:
If you are doing what you say there (plain text, just reading and parsing a simple format), you will be safe. As you indicate, Python is generally safe from the more mundane memory corruption errors that C developers can create if they are not careful. The SQL injection scenario you note is not a concern when simply reading in files in python.

However, if you are concerned about security, which it seems you are (interjection: good for you! A good programmer should be lazy and paranoid), here are some things to consider:

Validate all input. Make sure that each piece of data you read is of the expected size, type, range, etc. Error early, and don't propagate tainted variables elsewhere in your code.

Do you know the expected names of the vars, or at least their format? Make sure the validate that it is the kind of thing you expect before you use it. If it should be just letters, confirm that with a regex or similar.

Do you know the expected range or format of the data? If you're expecting a number, make sure it's a number before you use it. If it's supposed to be a short string, verify the length; you get the idea.

What if you get characters or bytes you don't expect? What if someone throws unicode at you?

If any of these are paths, make sure you canonicalize and know that the path points to an acceptable location before you read or write.

Some specific things not to do:

os.system(attackerControlledString)

eval(attackerControlledString)

__import__(attackerControlledString)

pickle/unpickle attacker controlled content (here's why)

Also, rather than rolling your own config file format, consider ConfigParser or something like JSON. A well understood format (and libraries) helps you get a leg up on proper validation.

OWASP would be my normal go-to for providing a "further reading" link, but their Input Validation page needs help. In lieu, this looks like a reasonably pragmatic read: "Secure Programmer: Validating Input". A slightly dated but more python specific one is "Dealing with User Input in Python"

Body:
Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated:

var1,data1
var2,data2
var3,data3

So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that will allow some arbitrary code execution? The only thing I can imagine if you you made the poor choice to make var1 be a shell command that you execute with os.sys(data1) in your own code somewhere. Also, if this were C then you would have to worry about buffers being blown, but I don't think you have to worry about that with python. If your reading in that data as a string is it possible to somehow escape the string "\n os.sys('rm -r /'), this SQL like example totally wont work, but is there similar that is possible?


问:
Fragment layout and Action Bar is showing repeatedly when it is selected
I have created a listview as a menu that will show you a specific fragment when selected. The problem is, if you select another option from the menu, the fragment will not clear, instead, it will just show another fragment. It's overlapping with other fragments that were previously selected.

How can I fix this?

答:
When you click on a particular item from the list that time replace your fragment and set the white background in xml file.

Please try below code :

```<code>FragmentTransaction ft = null;
HomeFragment fragment = new HomeFragment();
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.flHome, fragment).commit();
</code>```

And clear the menu in onCreateOptionMenu

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
     menu.clear();
     getMenuInflater().inflate(R.menu.game_menu, menu);
     return true;
}
</code>```

Body:
When you click on a particular item from the list that time replace your fragment and set the white background in xml file.

Please try below code :

FragmentTransaction ft = null;
HomeFragment fragment = new HomeFragment();
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.flHome, fragment).commit();

And clear the menu in onCreateOptionMenu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     menu.clear();
     getMenuInflater().inflate(R.menu.game_menu, menu);
     return true;
}


问:
AND statement in "SELECT ... FROM ... WHERE"
I have ListBox in Access form and trying to filter it using TextBox entry. My ListBox consist of 6 columns and I need to filter it by 2 conditions:

I need to find all entries containing entered text in any of first 5
columns

AND in 6th column containing specific text.

Filter more or less works, I get filtered result by my entry, but problem that my code seems to ignore AND statement and shows all results despite 6th column not containing specific text. What I am doing wrong?

My code:

```<code>Sub PaieskaTb_Change()

Dim strSource As String, strSearch As String
strSearch = Replace(PaieskaTb.Text, "'", "''") 'needed to avoid errors if entry contains apostrophes

    strSource = "SELECT [ID], [VP_veiklioji], [VP_invented_Name], [Pareisk_pav], [Par_gavimo_data], [Statusas] " _
        & "FROM qryNewSys_srch " _
        & "WHERE [ID] LIKE '*" & strSearch & "*' " _
        & "Or [VP_veiklioji] LIKE '*" & strSearch & "*' " _
        & "Or [VP_invented_Name] LIKE '*" & strSearch & "*' " _
        & "Or [Pareisk_pav] LIKE '*" & strSearch & "*' " _
        & "Or [Par_gavimo_data] LIKE '*" & strSearch & "*' " _
        & "And [Statusas] = 'Ongoing' " _ 'this line ignored, tried different apostrophes but no result
        & "ORDER BY [ID] DESC"

Me.Paraisku_sarasas.RowSource = strSource

End Sub
</code>```

答:
Add a set of parenthesis:</p>

```<code>strSource = "SELECT [ID], [VP_veiklioji], [VP_invented_Name], [Pareisk_pav], [Par_gavimo_data], [Statusas] " _
    & "FROM qryNewSys_srch " _
    & "WHERE ([ID] LIKE '*" & strSearch & "*' " _
    & "Or [VP_veiklioji] LIKE '*" & strSearch & "*' " _
    & "Or [VP_invented_Name] LIKE '*" & strSearch & "*' " _
    & "Or [Pareisk_pav] LIKE '*" & strSearch & "*' " _
    & "Or [Par_gavimo_data] LIKE '*" & strSearch & "*') " _
    & "And [Statusas] = 'Ongoing' " _
    & "ORDER BY [ID] DESC"
</code>```

Body:
I have ListBox in Access form and trying to filter it using TextBox entry. My ListBox consist of 6 columns and I need to filter it by 2 conditions:

I need to find all entries containing entered text in any of first 5
columns

AND in 6th column containing specific text.

Filter more or less works, I get filtered result by my entry, but problem that my code seems to ignore AND statement and shows all results despite 6th column not containing specific text. What I am doing wrong?

My code:

Sub PaieskaTb_Change()

Dim strSource As String, strSearch As String
strSearch = Replace(PaieskaTb.Text, "'", "''") 'needed to avoid errors if entry contains apostrophes

    strSource = "SELECT [ID], [VP_veiklioji], [VP_invented_Name], [Pareisk_pav], [Par_gavimo_data], [Statusas] " _
        & "FROM qryNewSys_srch " _
        & "WHERE [ID] LIKE '*" & strSearch & "*' " _
        & "Or [VP_veiklioji] LIKE '*" & strSearch & "*' " _
        & "Or [VP_invented_Name] LIKE '*" & strSearch & "*' " _
        & "Or [Pareisk_pav] LIKE '*" & strSearch & "*' " _
        & "Or [Par_gavimo_data] LIKE '*" & strSearch & "*' " _
        & "And [Statusas] = 'Ongoing' " _ 'this line ignored, tried different apostrophes but no result
        & "ORDER BY [ID] DESC"

Me.Paraisku_sarasas.RowSource = strSource

End Sub

Body:
Add a set of parenthesis:

strSource = "SELECT [ID], [VP_veiklioji], [VP_invented_Name], [Pareisk_pav], [Par_gavimo_data], [Statusas] " _
    & "FROM qryNewSys_srch " _
    & "WHERE ([ID] LIKE '*" & strSearch & "*' " _
    & "Or [VP_veiklioji] LIKE '*" & strSearch & "*' " _
    & "Or [VP_invented_Name] LIKE '*" & strSearch & "*' " _
    & "Or [Pareisk_pav] LIKE '*" & strSearch & "*' " _
    & "Or [Par_gavimo_data] LIKE '*" & strSearch & "*') " _
    & "And [Statusas] = 'Ongoing' " _
    & "ORDER BY [ID] DESC"


问:
Export to PDF with Chinese languages
I had a Grid that contain a chinese language. The problem occur when I want to export the data into PDF. It seem appear a weird characters (image below) or something like this . Can anyone help me to solve the issue?

Here I provide a DEMO in dojo

答:
Found a solution, using kendo.pdf.defineFont

I need to download Arial Unicode MS font then place into a folder.

By using defineFont I used this code.

```

Hope this can help.

Title: Export to PDF with Chinese languages

Body:
Found a solution, using kendo.pdf.defineFont

I need to download Arial Unicode MS font then place into a folder.

By using defineFont I used this code.

<script>
    kendo.pdf.defineFont({
        "Arial Unicode MS"  : " +your url path+ / +font folder location+ "
        //eg. "Arial Unicode MS"  : "myUrl/fonts/arialunicodems.ttf"
    });
</script>

Hope this can help.


问:
Configure distribution statistic for http.server.requests in spring-boot
Is there a way to configure distribution statistic expiry and buffer length for http.server.requests metrics?

I need to increase the expiry and couldn't find the proper way of doing this with spring boot actuator. Is it possible to configure these settings?

答:
You should look at DistributionStatisticConfig. The creation of DEFAULT instance shows how to set expiry and bufferLength.

All you have to do in Spring Boot is register a bean MeterRegistryCustomizer in your @SpringBootApplication or @Configuration class.

```<code>import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;

@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
    return registry -> registry.config()
        .commonTags("myTag", myTagValue)
        .meterFilter(new MeterFilter() {

            @Override
            public DistributionStatisticConfig configure(Meter.Id id,
                                                         DistributionStatisticConfig config) {
                if (id.getName().startsWith("http.server.requests")) {
                    return config.merge(DistributionStatisticConfig.builder()
                        .percentilesHistogram(true)
                        .percentiles(0.5, 0.9, 0.99)
                        .percentilePrecision(1)
                        .minimumExpectedValue(1L)
                        .maximumExpectedValue(Long.MAX_VALUE)
                        .expiry(Duration.ofMinutes(1))
                        .bufferLength(2)
                        .build());
                }
                return config;
            }
        });
}
</code>```

You can also ask on Micrometer's Slack channel.

Body:
You should look at DistributionStatisticConfig. The creation of DEFAULT instance shows how to set expiry and bufferLength.

All you have to do in Spring Boot is register a bean MeterRegistryCustomizer in your @SpringBootApplication or @Configuration class.

import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;

@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
    return registry -> registry.config()
        .commonTags("myTag", myTagValue)
        .meterFilter(new MeterFilter() {

            @Override
            public DistributionStatisticConfig configure(Meter.Id id,
                                                         DistributionStatisticConfig config) {
                if (id.getName().startsWith("http.server.requests")) {
                    return config.merge(DistributionStatisticConfig.builder()
                        .percentilesHistogram(true)
                        .percentiles(0.5, 0.9, 0.99)
                        .percentilePrecision(1)
                        .minimumExpectedValue(1L)
                        .maximumExpectedValue(Long.MAX_VALUE)
                        .expiry(Duration.ofMinutes(1))
                        .bufferLength(2)
                        .build());
                }
                return config;
            }
        });
}

You can also ask on Micrometer's Slack channel.


问:
Type mismatch error on custom interface call
I'm redesigning an app I've been working on with Kotlin for the purpose of getting used to the language.  In my RecyclerView adapter, I have created a custom OnLongClickListener interface for long clicks:

```<code>interface OnItemLongClickListener{
    fun onItemLongClick(entry: Entry)
}

fun setOnItemLongClickListener(listener: OnItemLongClickListener){
    this.listener = listener
}
</code>```

And in the onCreate() of my MainActivity.kt, I am calling setOnItemLongClickListener on my adapter object to pass some intent extras:

```<code>    adapter!!.setOnItemLongClickListener { entry ->
        val intent = Intent(this@MainActivity, AddEditEntryActivity::class.java)

        intent.putExtra(AddEditEntryActivity.EXTRA_ID, entry.id)
        intent.putExtra(AddEditEntryActivity.EXTRA_USERNAME, entry.username)
        intent.putExtra(AddEditEntryActivity.EXTRA_HINT, entry.hint)
        intent.putExtra(AddEditEntryActivity.EXTRA_PASSWORD, entry.password)
        startActivityForResult(intent, EDIT_ENTRY_REQUEST)
    }
</code>```

But the whole thing has a red underline and throws a Type Mismatch error.

I can supply more code per request.  I'm just keeping it short for now to avoid unnecessary clutter.

答:
You should always include the complete error message, please. Without it, I can only guess that the issue is related to you supplying a lambda while an object of OnItemLongClickListener is being expected. You can change the code like this:

```<code>adapter!!.setOnItemLongClickListener (object: OnItemLongClickListener {
    override fun onItemLongClick(entry: Entry){
        //code goes here
    }
})
</code>```

What you were trying to do only works for Java interfaces and is called SAM conversion.

Body:
I'm redesigning an app I've been working on with Kotlin for the purpose of getting used to the language.  In my RecyclerView adapter, I have created a custom OnLongClickListener interface for long clicks:

interface OnItemLongClickListener{
    fun onItemLongClick(entry: Entry)
}

fun setOnItemLongClickListener(listener: OnItemLongClickListener){
    this.listener = listener
}

And in the onCreate() of my MainActivity.kt, I am calling setOnItemLongClickListener on my adapter object to pass some intent extras:

    adapter!!.setOnItemLongClickListener { entry ->
        val intent = Intent(this@MainActivity, AddEditEntryActivity::class.java)

        intent.putExtra(AddEditEntryActivity.EXTRA_ID, entry.id)
        intent.putExtra(AddEditEntryActivity.EXTRA_USERNAME, entry.username)
        intent.putExtra(AddEditEntryActivity.EXTRA_HINT, entry.hint)
        intent.putExtra(AddEditEntryActivity.EXTRA_PASSWORD, entry.password)
        startActivityForResult(intent, EDIT_ENTRY_REQUEST)
    }

But the whole thing has a red underline and throws a Type Mismatch error.

I can supply more code per request.  I'm just keeping it short for now to avoid unnecessary clutter.

Body:
You should always include the complete error message, please. Without it, I can only guess that the issue is related to you supplying a lambda while an object of OnItemLongClickListener is being expected. You can change the code like this:

adapter!!.setOnItemLongClickListener (object: OnItemLongClickListener {
    override fun onItemLongClick(entry: Entry){
        //code goes here
    }
})

What you were trying to do only works for Java interfaces and is called SAM conversion.


问:
How to export a docker image to a rootfs without starting a container?
I wanna save a docker image to a rootfs format(like a dir consisting of /etc /var ...), which is just like what docker export does. Also docker save cannot meet my need too because it saves layers of the image other than the dir they mount together. But I do not want to use docker export because it only works when a container using this image is running. Now I have an image list containing about 1000 entries, how can I save every image to rootfs without starting a container first on each of them?

答:
Quoting @tgogos comment:

iterate through your images, use docker create ... to create a container (with create it won't start), then use docker export ... and finally cleanup with docker rm ...


问:
How to make material components work with Karma in unit testing Angular
I have an angular CLI project set up. I've made a form that uses angular material components, like <md-card>.

I'm just starting out with writing my first Karma/Jasmine unit test, following the steps in the angular docs.

This is my component template:

```<code><md-card [ngClass]="'dialog-card'">
<md-card-title [ngClass]="'dialog-title'">
    {{title}}
</md-card-title>
<md-card-content>

    <form (ngSubmit)="login()" #loginForm="ngForm">

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.email"
                name="userEmail" type="email" placeholder="Email"
                ngControl="userEmail"
            required>
        </md-input-container>
        <br>

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.password"
                name="userPassword" type="password" placeholder="Password"
                ngControl="userPassword"
            required>
        </md-input-container>
        <br>

        <tm-message msgText="Wrong username or password" *ngIf="showError"></tm-message>
        <br>

        <button md-button type="submit" [disabled]="!loginForm.form.valid">Login</button>

        <p (click)="openForgotPasswordModal()">Forgot Password?</p>

    </form>

</md-card-content>
</code>```

This is my karma spec:

```<code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { MaterialModule, MdDialogRef, MdDialog  } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import { TmLoginComponent } from './tm-login.component';
import { TmMessageComponent } from '../../shared/components/tm-message.component';
import { UserAuthenticationService } from '../login/user-authentication.service';

describe('TmLoginComponent (inline template)', () => {

let comp: TmLoginComponent;
let fixture: ComponentFixture < TmLoginComponent > ;
let de: DebugElement;
let el: HTMLElement;

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [TmLoginComponent, TmMessageComponent], // declare the test component
        imports: [MaterialModule, FormsModule,
            RouterTestingModule.withRoutes(
                [{
                    path: 'login',
                    component: TmLoginComponent
                }, ])
        ],
        providers: [UserAuthenticationService],

    });

    fixture = TestBed.createComponent(TmLoginComponent);

    comp = fixture.componentInstance; // TmLoginComponent test instance

    // query for the title <h1> by CSS element selector
    de = fixture.debugElement.query(By.css('.title'));
    el = de.nativeElement;
});

    it('should display original title', () => {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.title);
    });
});
</code>```

At this point, I'm just trying to run the basic unit test that the title is being displayed properly.

However, I'm getting a lot of material specific errors. Like

No provider for MdDialog.

I'm opening an md Dialog on clicking a link. THe code is in the (fairly long) .ts file, but that's not the issue here.

Where would I add MdDialog in the testbed? If I add it to providers, I get the error: "no provider for overlay". I don't know how to fix that.

Is there any way I can configure karma to include all material components at start?

Thanks.

答:
I've been struggling with this as well today and you need to mock out the necessary classes yourself by using providers in jasmine. It's a hassle and I wish there was a better way but at least no more errors...

If anyone has a better idea, please enlighten the rest of the community!

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AlertDialogComponent } from './alert-dialog.component';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

describe('AlertDialogComponent', () => {
  let component: AlertDialogComponent;
  let fixture: ComponentFixture<AlertDialogComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [MatDialogModule],
      declarations: [AlertDialogComponent],
      providers: [
        {
          provide: MatDialogRef, useValue: {}
        },
        {
          provide: MAT_DIALOG_DATA, useValue:{}
        }
     ],
    }).compileComponents();
  }));
</code>```

Body:
I have an angular CLI project set up. I've made a form that uses angular material components, like <md-card>.

I'm just starting out with writing my first Karma/Jasmine unit test, following the steps in the angular docs.

This is my component template:

<md-card [ngClass]="'dialog-card'">
<md-card-title [ngClass]="'dialog-title'">
    {{title}}
</md-card-title>
<md-card-content>

    <form (ngSubmit)="login()" #loginForm="ngForm">

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.email"
                name="userEmail" type="email" placeholder="Email"
                ngControl="userEmail"
            required>
        </md-input-container>

        <md-input-container class="md-block">
            <input md-input [(ngModel)]="user.password"
                name="userPassword" type="password" placeholder="Password"
                ngControl="userPassword"
            required>
        </md-input-container>

        <tm-message msgText="Wrong username or password" *ngIf="showError"></tm-message>

        <button md-button type="submit" [disabled]="!loginForm.form.valid">Login</button>

Forgot Password?

    </form>

</md-card-content>

This is my karma spec:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { MaterialModule, MdDialogRef, MdDialog  } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';

import { TmLoginComponent } from './tm-login.component';
import { TmMessageComponent } from '../../shared/components/tm-message.component';
import { UserAuthenticationService } from '../login/user-authentication.service';

describe('TmLoginComponent (inline template)', () => {

let comp: TmLoginComponent;
let fixture: ComponentFixture < TmLoginComponent > ;
let de: DebugElement;
let el: HTMLElement;

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [TmLoginComponent, TmMessageComponent], // declare the test component
        imports: [MaterialModule, FormsModule,
            RouterTestingModule.withRoutes(
                [{
                    path: 'login',
                    component: TmLoginComponent
                }, ])
        ],
        providers: [UserAuthenticationService],

    });

    fixture = TestBed.createComponent(TmLoginComponent);

    comp = fixture.componentInstance; // TmLoginComponent test instance

    // query for the title
 by CSS element selector
    de = fixture.debugElement.query(By.css('.title'));
    el = de.nativeElement;
});

    it('should display original title', () => {
        fixture.detectChanges();
        expect(el.textContent).toContain(comp.title);
    });
});

At this point, I'm just trying to run the basic unit test that the title is being displayed properly.

However, I'm getting a lot of material specific errors. Like

No provider for MdDialog.

I'm opening an md Dialog on clicking a link. THe code is in the (fairly long) .ts file, but that's not the issue here.

Where would I add MdDialog in the testbed? If I add it to providers, I get the error: "no provider for overlay". I don't know how to fix that.

Is there any way I can configure karma to include all material components at start?

Thanks.

Body:
I've been struggling with this as well today and you need to mock out the necessary classes yourself by using providers in jasmine. It's a hassle and I wish there was a better way but at least no more errors...

If anyone has a better idea, please enlighten the rest of the community!

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AlertDialogComponent } from './alert-dialog.component';
import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

describe('AlertDialogComponent', () => {
  let component: AlertDialogComponent;
  let fixture: ComponentFixture<AlertDialogComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [MatDialogModule],
      declarations: [AlertDialogComponent],
      providers: [
        {
          provide: MatDialogRef, useValue: {}
        },
        {
          provide: MAT_DIALOG_DATA, useValue:{}
        }
     ],
    }).compileComponents();
  }));


问:
How to Install Rails on MAC: Error Installing Rails on MAC
I am trying to set Rails on my MAC, but continue to get an error even with all the previous help provided by people that have also faced the same problem.

I downloaded Ruby 2.4.1 using rbenv and now I need to install rails 4.2.1 but I continue to get the following error.

ERROR:  Error installing rails:
    ERROR: Failed to build gem native extension.

```<code>Fetching actionview-4.2.1.gem
Fetching actionpack-4.2.1.gem
Fetching railties-4.2.1.gem
Fetching activejob-4.2.1.gem
Fetching actionmailer-4.2.1.gem
Fetching activemodel-4.2.1.gem
Fetching activerecord-4.2.1.gem
Fetching rails-4.2.1.gem
Building native extensions. This could take a while...
ERROR:  Error installing rails:
    ERROR: Failed to build gem native extension.

    current directory: /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/ext/nokogiri
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -I /Library/Ruby/Site/2.3.0 -r ./siteconf20190527-36261-6oqyvd.rb extconf.rb
checking if the C compiler accepts  -I     /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/libxml2... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no
Building nokogiri using packaged libraries.
Using mini_portile version 2.4.0
checking for iconv.h... yes
checking for gzdopen() in -lz... yes
checking for iconv... yes
************************************************************************
IMPORTANT NOTICE:

Building Nokogiri with a packaged version of libxml2-2.9.9
with the following patches applied:
    - 0001-Revert-Do-not-URI-escape-in-server-side-includes.patch
    - 0002-Remove-script-macro-support.patch
    - 0003-Update-entities-to-remove-handling-of-ssi.patch

Team Nokogiri will keep on doing their best to provide security updates in a timely manner, but if this is a concern for you and want to use the system library instead; abort this installation process and reinstall nokogiri as follows:

    gem install nokogiri -- --use-system-libraries
        [--with-xml2-config=/path/to/xml2-config]
        [--with-xslt-config=/path/to/xslt-config]

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install

Note, however, that nokogiri is not fully compatible with arbitrary versions of libxml2 provided by OS/package vendors.
************************************************************************
Extracting libxml2-2.9.9.tar.gz into tmp/x86_64-apple-darwin17/ports/libxml2/2.9.9... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0001-Revert-Do-not-URI-escape-in-server-side-includes.patch... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0002-Remove-script-macro-support.patch... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0003-Update-entities-to-remove-handling-of-ssi.patch... OK
Running 'configure' for libxml2 2.9.9... OK
Running 'compile' for libxml2 2.9.9... ERROR, review '/Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/ext/nokogiri/tmp/x86_64 apple-darwin17/ports/libxml2/2.9.9/compile.log' to see what happened. Last lines are:
========================================================================
  CC       testdso.lo
  CCLD     testdso.la
  CC       xmllint.o
  CCLD     xmllint
ld: warning: The i386 architecture is deprecated for macOS (remove from the Xcode build setting: ARCHS)
ld: warning: ignoring file /usr/local/Cellar/xz/5.2.4/lib/liblzma.dylib, file was built for x86_64 which is not the architecture being linked (i386): /usr/local/Cellar/xz/5.2.4/lib/liblzma.dylib
Undefined symbols for architecture i386:
  "_lzma_auto_decoder", referenced from:
      _xz_head in libxml2.a(xzlib.o)
  "_lzma_code", referenced from:
      _xz_decomp in libxml2.a(xzlib.o)
  "_lzma_end", referenced from:
      ___libxml2_xzclose in libxml2.a(xzlib.o)
  "_lzma_properties_decode", referenced from:
      _is_format_lzma in libxml2.a(xzlib.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [xmllint] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
========================================================================
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/$(RUBY_BASE_NAME)
    --help
    --clean
    --use-system-libraries
    --enable-static
    --disable-static
    --with-zlib-dir
    --without-zlib-dir
    --with-zlib-include
    --without-zlib-include=${zlib-dir}/include
    --with-zlib-lib
    --without-zlib-lib=${zlib-dir}/lib
    --enable-cross-build
    --disable-cross-build
/Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:402:in `block in execute': Failed to complete compile task (RuntimeError)
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:373:in `chdir'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:373:in `execute'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:115:in `compile'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:154:in `cook'
from extconf.rb:365:in `block (2 levels) in process_recipe'
from extconf.rb:257:in `block in chdir_for_build'
from extconf.rb:256:in `chdir'
from extconf.rb:256:in `chdir_for_build'
from extconf.rb:364:in `block in process_recipe'
from extconf.rb:262:in `tap'
from extconf.rb:262:in `process_recipe'
from extconf.rb:557:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-17/2.3.0/nokogiri-1.10.3/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3 for inspection.
Results logged to /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-17/2.3.0/nokogiri-1.10.3/gem_make.out
</code>```

I have seen:

```<code>gem update --system 3.0.3
</code>```

But don't need this as I already have the latest version of gem.

I have tried:

```<code>sudo gem install rails --version 4.2.1
</code>```

But this is what throws the above error.

答:
You have issues with libxml2

Make sure you have xcodebuild installed:

```<code>sudo xcodebuild -license accept
</code>```

Or try to install libxml2 directly via brew:

```<code>brew install libxml2
</code>```

Also you might try to run

```<code>gem install nokogiri -v 1.10.3 -- --use-system-libraries
</code>```

Because nokogiri is shipping with it's own libxml2 that's incompatible with some systems

Ref nokogiri gem installation error

Body:
I am trying to set Rails on my MAC, but continue to get an error even with all the previous help provided by people that have also faced the same problem.

I downloaded Ruby 2.4.1 using rbenv and now I need to install rails 4.2.1 but I continue to get the following error.

ERROR:  Error installing rails:
    ERROR: Failed to build gem native extension.

Fetching actionview-4.2.1.gem
Fetching actionpack-4.2.1.gem
Fetching railties-4.2.1.gem
Fetching activejob-4.2.1.gem
Fetching actionmailer-4.2.1.gem
Fetching activemodel-4.2.1.gem
Fetching activerecord-4.2.1.gem
Fetching rails-4.2.1.gem
Building native extensions. This could take a while...
ERROR:  Error installing rails:
    ERROR: Failed to build gem native extension.

    current directory: /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/ext/nokogiri
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -I /Library/Ruby/Site/2.3.0 -r ./siteconf20190527-36261-6oqyvd.rb extconf.rb
checking if the C compiler accepts  -I     /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/libxml2... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no
Building nokogiri using packaged libraries.
Using mini_portile version 2.4.0
checking for iconv.h... yes
checking for gzdopen() in -lz... yes
checking for iconv... yes
************************************************************************
IMPORTANT NOTICE:

Building Nokogiri with a packaged version of libxml2-2.9.9
with the following patches applied:
    - 0001-Revert-Do-not-URI-escape-in-server-side-includes.patch
    - 0002-Remove-script-macro-support.patch
    - 0003-Update-entities-to-remove-handling-of-ssi.patch

Team Nokogiri will keep on doing their best to provide security updates in a timely manner, but if this is a concern for you and want to use the system library instead; abort this installation process and reinstall nokogiri as follows:

    gem install nokogiri -- --use-system-libraries
        [--with-xml2-config=/path/to/xml2-config]
        [--with-xslt-config=/path/to/xslt-config]

If you are using Bundler, tell it to use the option:

    bundle config build.nokogiri --use-system-libraries
    bundle install

Note, however, that nokogiri is not fully compatible with arbitrary versions of libxml2 provided by OS/package vendors.
************************************************************************
Extracting libxml2-2.9.9.tar.gz into tmp/x86_64-apple-darwin17/ports/libxml2/2.9.9... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0001-Revert-Do-not-URI-escape-in-server-side-includes.patch... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0002-Remove-script-macro-support.patch... OK
Running git apply with /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/patches/libxml2/0003-Update-entities-to-remove-handling-of-ssi.patch... OK
Running 'configure' for libxml2 2.9.9... OK
Running 'compile' for libxml2 2.9.9... ERROR, review '/Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3/ext/nokogiri/tmp/x86_64 apple-darwin17/ports/libxml2/2.9.9/compile.log' to see what happened. Last lines are:
========================================================================
  CC       testdso.lo
  CCLD     testdso.la
  CC       xmllint.o
  CCLD     xmllint
ld: warning: The i386 architecture is deprecated for macOS (remove from the Xcode build setting: ARCHS)
ld: warning: ignoring file /usr/local/Cellar/xz/5.2.4/lib/liblzma.dylib, file was built for x86_64 which is not the architecture being linked (i386): /usr/local/Cellar/xz/5.2.4/lib/liblzma.dylib
Undefined symbols for architecture i386:
  "_lzma_auto_decoder", referenced from:
      _xz_head in libxml2.a(xzlib.o)
  "_lzma_code", referenced from:
      _xz_decomp in libxml2.a(xzlib.o)
  "_lzma_end", referenced from:
      ___libxml2_xzclose in libxml2.a(xzlib.o)
  "_lzma_properties_decode", referenced from:
      _is_format_lzma in libxml2.a(xzlib.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [xmllint] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
========================================================================
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/$(RUBY_BASE_NAME)
    --help
    --clean
    --use-system-libraries
    --enable-static
    --disable-static
    --with-zlib-dir
    --without-zlib-dir
    --with-zlib-include
    --without-zlib-include=${zlib-dir}/include
    --with-zlib-lib
    --without-zlib-lib=${zlib-dir}/lib
    --enable-cross-build
    --disable-cross-build
/Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:402:in `block in execute': Failed to complete compile task (RuntimeError)
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:373:in `chdir'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:373:in `execute'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:115:in `compile'
from /Library/Ruby/Gems/2.3.0/gems/mini_portile2-2.4.0/lib/mini_portile2/mini_portile.rb:154:in `cook'
from extconf.rb:365:in `block (2 levels) in process_recipe'
from extconf.rb:257:in `block in chdir_for_build'
from extconf.rb:256:in `chdir'
from extconf.rb:256:in `chdir_for_build'
from extconf.rb:364:in `block in process_recipe'
from extconf.rb:262:in `tap'
from extconf.rb:262:in `process_recipe'
from extconf.rb:557:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-17/2.3.0/nokogiri-1.10.3/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.3.0/gems/nokogiri-1.10.3 for inspection.
Results logged to /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-17/2.3.0/nokogiri-1.10.3/gem_make.out

I have seen:

gem update --system 3.0.3

But don't need this as I already have the latest version of gem.

I have tried:

sudo gem install rails --version 4.2.1

But this is what throws the above error.

Body:
You have issues with libxml2

Make sure you have xcodebuild installed:

sudo xcodebuild -license accept

Or try to install libxml2 directly via brew:

brew install libxml2

Also you might try to run

gem install nokogiri -v 1.10.3 -- --use-system-libraries

Because nokogiri is shipping with it's own libxml2 that's incompatible with some systems

Ref nokogiri gem installation error


问:
how to filter array list of collection view which is in accessory view
//  I just want to filter array list which is shown in collection view cell when user enter text in the textfield.
    On textfield editing collection data will be sort and filter according to textfield input. In case of collection view has a data about states, If I input 'A' in textfield, all collection data will be sort and display all state names starting with alphabet 'A'. Please tell me logic for this.

ios iphone

here is the link of my project ---- https://drive.google.com/drive/folders/1d56PWO2j6YcDU2AJyCseZC16dfUeV7Bd?usp=sharing //

ViewController.swift

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
        }
    }
}

class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!

    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]

    override func awakeFromNib() {
        super.awakeFromNib()
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.words.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.words[indexPath.row]
        return cell
    }
}

class CustomCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}
</code>```

答:
Create another array filteredWords in CustomView class and use that array in collection view datasource methods

```<code>class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!
    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]
    var filteredWords = [String]()

    override func awakeFromNib() {
        super.awakeFromNib()
        filteredWords = words
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.filteredWords.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.filteredWords[indexPath.row]
        return cell
    }
}
</code>```

In ViewController add target to textField for .editingChanged.
Then filter, sort the array and reload the collectionView.

```<code>class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
            self.textField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
        }
    }
    @objc func textChanged(_ sender: UITextField) {
        if let customView = textField.inputAccessoryView as? CustomView {
            if textField.text!.isEmpty {
                customView.filteredWords = customView.words
                customView.collectionView.reloadData()
            } else {
                customView.filteredWords = customView.words
                    .filter({ $0.localizedCaseInsensitiveContains(textField.text!) }).sorted(by: {
                        if let range0 = $0.range(of: textField.text!, options: [.caseInsensitive], range: $0.startIndex..<$0.endIndex, locale: nil),
                            let range1 = $1.range(of: textField.text!, options: [.caseInsensitive], range: $1.startIndex..<$1.endIndex, locale: nil) {
                            return range0.lowerBound < range1.lowerBound
                        } else {
                            return false
                        }
                    })
                customView.collectionView.reloadData()
            }
        }
    }
}
</code>```

The sorted array will be sorted based on the index of searched text. Ex. for text "in" the filtered and sorted result will be

["lind", "sind", "tinned", "wind", "skinned", "thin-skinned",
  "twinned", "upwind", "abscind", "rescind", "downwind", "headwind",
  "tailwind", "whirlwind"]

Body:
//  I just want to filter array list which is shown in collection view cell when user enter text in the textfield.
    On textfield editing collection data will be sort and filter according to textfield input. In case of collection view has a data about states, If I input 'A' in textfield, all collection data will be sort and display all state names starting with alphabet 'A'. Please tell me logic for this.

ios iphone

here is the link of my project ---- https://drive.google.com/drive/folders/1d56PWO2j6YcDU2AJyCseZC16dfUeV7Bd?usp=sharing //

ViewController.swift

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
        }
    }
}

class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!

    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]

    override func awakeFromNib() {
        super.awakeFromNib()
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.words.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.words[indexPath.row]
        return cell
    }
}

class CustomCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}

Body:
Create another array filteredWords in CustomView class and use that array in collection view datasource methods

class CustomView: UIView, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!
    let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]
    var filteredWords = [String]()

    override func awakeFromNib() {
        super.awakeFromNib()
        filteredWords = words
        self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.filteredWords.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
        cell.label.text = self.filteredWords[indexPath.row]
        return cell
    }
}

In ViewController add target to textField for .editingChanged.
Then filter, sort the array and reload the collectionView.

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView {
            self.textField.inputAccessoryView = customView
            self.textField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
        }
    }
    @objc func textChanged(_ sender: UITextField) {
        if let customView = textField.inputAccessoryView as? CustomView {
            if textField.text!.isEmpty {
                customView.filteredWords = customView.words
                customView.collectionView.reloadData()
            } else {
                customView.filteredWords = customView.words
                    .filter({ $0.localizedCaseInsensitiveContains(textField.text!) }).sorted(by: {
                        if let range0 = $0.range(of: textField.text!, options: [.caseInsensitive], range: $0.startIndex..<$0.endIndex, locale: nil),
                            let range1 = $1.range(of: textField.text!, options: [.caseInsensitive], range: $1.startIndex..<$1.endIndex, locale: nil) {
                            return range0.lowerBound < range1.lowerBound
                        } else {
                            return false
                        }
                    })
                customView.collectionView.reloadData()
            }
        }
    }
}

The sorted array will be sorted based on the index of searched text. Ex. for text "in" the filtered and sorted result will be

["lind", "sind", "tinned", "wind", "skinned", "thin-skinned",
  "twinned", "upwind", "abscind", "rescind", "downwind", "headwind",
  "tailwind", "whirlwind"]


问:
Howto convert file to byte stream in javascript
How to convert a file to a byte array.

another way round of below one

```<code>let file = new File([myBlob], "name");
</code>```

file need to convert into a byte stream

答:
You can probably try to use FileReader API available in Browser.

```<code>let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const result = ev.target.result;
    console.log(result); // here it is
}
</code>```

According to this answer, if the result from readAsArrayBuffer will not work for you, you may need to convert it to the real byte[] using new Uint8Array. Here is extended version of the above code:

```<code>let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const array = new Uint8Array(ev.target.result);
    const fileByteArray = [];
    for (let i = 0; i < array.length; i++) {
       fileByteArray.push(array[i]);
    }
    console.log(array); // here it is
}
</code>```

And here is implementation wrapped in promise for comfortable usage:

```<code>function getByteArray(file) {
   return new Promise(function(resolve, reject) {
       fileReader.readAsArrayBuffer(file);
       fileReader.onload = function(ev) {
           const array = new Uint8Array(ev.target.result);
           const fileByteArray = [];
           for (let i = 0; i < array.length; i++) {
               fileByteArray.push(array[i]);
           }
           resolve(array);  // successful
       }
       fileReader.onerror = reject; // call reject if error
   })
}

//usage
let file = new File(...)
getByteArray(file).then((byteArray) => {
    // do whatever you need
    console.log(byteArray);
})
</code>```

P.S.
If for some reason you can not refer to ev.target, please try to use fileReader.result instead.

Body:
How to convert a file to a byte array.

another way round of below one

let file = new File([myBlob], "name");

file need to convert into a byte stream

Body:
You can probably try to use FileReader API available in Browser.

let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const result = ev.target.result;
    console.log(result); // here it is
}

According to this answer, if the result from readAsArrayBuffer will not work for you, you may need to convert it to the real byte[] using new Uint8Array. Here is extended version of the above code:

let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const array = new Uint8Array(ev.target.result);
    const fileByteArray = [];
    for (let i = 0; i < array.length; i++) {
       fileByteArray.push(array[i]);
    }
    console.log(array); // here it is
}

And here is implementation wrapped in promise for comfortable usage:

function getByteArray(file) {
   return new Promise(function(resolve, reject) {
       fileReader.readAsArrayBuffer(file);
       fileReader.onload = function(ev) {
           const array = new Uint8Array(ev.target.result);
           const fileByteArray = [];
           for (let i = 0; i < array.length; i++) {
               fileByteArray.push(array[i]);
           }
           resolve(array);  // successful
       }
       fileReader.onerror = reject; // call reject if error
   })
}

//usage
let file = new File(...)
getByteArray(file).then((byteArray) => {
    // do whatever you need
    console.log(byteArray);
})

P.S.
If for some reason you can not refer to ev.target, please try to use fileReader.result instead.


答:
Press and hold 'ctrl' for Windows ('command' for macOS)

Move a mouse cursor over the variable of interest

You can see "Inferred type". Sometimes, as in the case above, it is not what the real variable ever be in this place, but at least PyCharm tried it best to infer.

```<code>import random
variable = 1
variable = None
for i in range(10):
    variable = random.randint(1, 3)
    if variable <= 0:
        variable = 'Zero or less'
    elif variable == 1:
        variable = 1.0
    elif variable == 2:
        variable = [2]
    elif variable == 3:
        variable = {'three': 3}
    else:
        variable = (4, '4 or more')
    print(i, type(variable), variable)
# Extra blank lines to show variable type
#
#
#
del variable
</code>```

Title: PyCharm see Object Data Type

Body:
Currently I am dealing with a lot of code inspection in pycharm. Often I have the problem that I don't know which is the actual data type of a variable in python. Then I have to revisit the code to find the actual definition of the variable, or use some inserted code snippets like type() to get the data format.

What would be the most elegant / most comfortable way to do this task? I though maybe there are some built-in functions in PyCharm.

Body:
Press and hold 'ctrl' for Windows ('command' for macOS)

Move a mouse cursor over the variable of interest

You can see "Inferred type". Sometimes, as in the case above, it is not what the real variable ever be in this place, but at least PyCharm tried it best to infer.

import random
variable = 1
variable = None
for i in range(10):
    variable = random.randint(1, 3)
    if variable <= 0:
        variable = 'Zero or less'
    elif variable == 1:
        variable = 1.0
    elif variable == 2:
        variable = [2]
    elif variable == 3:
        variable = {'three': 3}
    else:
        variable = (4, '4 or more')
    print(i, type(variable), variable)
# Extra blank lines to show variable type
#
#
#
del variable