问:
Button with both background image and color WPF
I have a button in my wpf app, looking like :

```<code>    <Button x:Name="button" Content="" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="26" Height="28" BorderBrush="{x:Null}" Grid.Column="1" Foreground="White">
     <Button.Background>
            <ImageBrush ImageSource="cls_blk_btn.png" Stretch="None"/>
        </Button.Background>
    </Button>

</code>```

Now as you can see the button has a background image, is it possible to have a background color keeping the image also ??

What i am trying to do is change the button's background color(keeping the image as it is) on mouse enter with this :

```<code>      <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Button.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="Color" To="#FF484A4D" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Button.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Color" To="#FF57626C" Duration="0:0:0.1" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
            </Button.Style>
</code>```

The problem is, as the background is an image, i get exceptions while trying to change the color...Any help in keeping the image as it is and changing the backColor ???

THIS IS WHAT I JUST TRIED

```<code>    <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="resources\c_ml.bmp" Stretch="Fill"/>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <ImageBrush ImageSource="Resources\c_mo.bmp" Stretch="Fill"/>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
</code>```

But it gives me 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' in line 45.The lines throwing the exceptions are:

```<code>   <Style TargetType="{x:Type Button}">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="resources\c_ml.png" Stretch="Fill"/>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
</code>```

Any idea how to fix it ?

I FIXED MY SECOND ERROR BUT HAVE A NEW PROBLEM

The second error occured because i didn't include the pictures in my project.After including, i have a new problem. Now , on mouse over, The button becomes white, i mean it changes it's Background color instead of changing the image...What's wrong ?

答:
FIXED IT MYSELF

```<code>    <Button.Content>
    <StackPanel>
        <Image Name="image1"  Source="pack://application:,,,/OffPo Diagnostic Tool;component/resources/c_ml.bmp" Stretch="Fill" >
            <Image.Style>
                <Style TargetType="Image">
                    <Setter Property="Visibility" Value="Visible" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                            <Setter Property="Visibility" Value="Collapsed" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
        <Image Name="image2" Source="pack://application:,,,/OffPo Diagnostic Tool;component/resources/c_mo.bmp" Stretch="Fill" >
            <Image.Style>
                <Style TargetType="Image">
                    <Setter Property="Visibility" Value="Collapsed" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                            <Setter Property="Visibility" Value="Visible" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
    </StackPanel>
</Button.Content>
</code>```

Body:
I have a button in my wpf app, looking like :

    <Button x:Name="button" Content="" HorizontalAlignment="Left" Margin="402,10,0,0" VerticalAlignment="Top" Width="26" Height="28" BorderBrush="{x:Null}" Grid.Column="1" Foreground="White">
     <Button.Background>
            <ImageBrush ImageSource="cls_blk_btn.png" Stretch="None"/>
        </Button.Background>
    </Button>

Now as you can see the button has a background image, is it possible to have a background color keeping the image also ??

What i am trying to do is change the button's background color(keeping the image as it is) on mouse enter with this :

      <Button.Style>

            </Style>
            </Button.Style>

The problem is, as the background is an image, i get exceptions while trying to change the color...Any help in keeping the image as it is and changing the backColor ???

THIS IS WHAT I JUST TRIED

    <Button.Style>

            </Style>
        </Button.Style>

But it gives me 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' in line 45.The lines throwing the exceptions are:

Body:
FIXED IT MYSELF

    <Button.Content>
    <StackPanel>
        <Image Name="image1"  Source="pack://application:,,,/OffPo Diagnostic Tool;component/resources/c_ml.bmp" Stretch="Fill" >
            <Image.Style>
                <Style TargetType="Image">
                    <Setter Property="Visibility" Value="Visible" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                            <Setter Property="Visibility" Value="Collapsed" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
        <Image Name="image2" Source="pack://application:,,,/OffPo Diagnostic Tool;component/resources/c_mo.bmp" Stretch="Fill" >
            <Image.Style>
                <Style TargetType="Image">
                    <Setter Property="Visibility" Value="Collapsed" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" Value="True">
                            <Setter Property="Visibility" Value="Visible" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
    </StackPanel>
</Button.Content>


来源: stackexchange

问:
returning component inside function not working
I've a component which i'm rendering by considering some conditions. It's done as follows

```<code>const Test = () => {
    return <div className="text_align_center white_color">
        <span><i className="fa fa-exclamation-triangle" aria-hidden="true"></i>
            No internet connection. Please check your connection settings and try again
        </span>
    </div>
}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}
</code>```

Then i'm calling my function as follows

```<code>const App = () => (
    <div className="ui container">

        {checkInternetConnection()}
);
</code>```

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?

答:
Your <Test/> is being returned by the then callback function, not your checkInternetConnection function. Because you are conditionally rendering based on some asynchronous operation, you need to take a different approach in order for your component to update correctly.

One idea is to turn your stateless component into a stateful component by making it a class, and calling setState when your promise resolves:

```<code>import React from 'react';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isOnline: false // set initial state to false
        };
    }

    componentDidMount() {
        isOnline().then(online => {
            this.setState({
                isOnline: true; // call setState to update state and rerender App
            });
        });
    }

    render() { // use inline expression to conditionally show <Test/> if isOnline is true

        return (

            <div className="ui container">

              { this.state.isOnline && <Test /> }

            </div>
        );
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've a component which i'm rendering by considering some conditions. It's done as follows

const Test = () => {
    return

            No internet connection. Please check your connection settings and try again

}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}

Then i'm calling my function as follows

const App = () => (

        {checkInternetConnection()}
);

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?

Body:
Your <Test/> is being returned by the then callback function, not your checkInternetConnection function. Because you are conditionally rendering based on some asynchronous operation, you need to take a different approach in order for your component to update correctly.

One idea is to turn your stateless component into a stateful component by making it a class, and calling setState when your promise resolves:

import React from 'react';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isOnline: false // set initial state to false
        };
    }

    componentDidMount() {
        isOnline().then(online => {
            this.setState({
                isOnline: true; // call setState to update state and rerender App
            });
        });
    }

    render() { // use inline expression to conditionally show <Test/> if isOnline is true

        return (

            <div className="ui container">

              { this.state.isOnline && <Test /> }

            </div>
        );
    }
}


问:
Shell script: Ensure that script isn't executed if already running

Possible Duplicate:

  Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.

Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?

答:
A solution without race condition or early exit problems is to use a lock file. The flock utility handles this very well and can be used like this:

```<code>flock -n /var/run/your.lockfile -c /your/script
</code>```

It will return immediately with a non 0 status if the script is already running.

ContentLicense: CC BY-SA 4.0

Body:
A solution without race condition or early exit problems is to use a lock file. The flock utility handles this very well and can be used like this:

flock -n /var/run/your.lockfile -c /your/script

It will return immediately with a non 0 status if the script is already running.

ContentLicense: CC BY-SA 2.5


问:
Multiple select queries on the same table in Oracle
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

```<code>FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ
</code>```

The current SQL statement that I use is:

```<code>SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';
</code>```

And I get the following result:

```<code>FILENAME | VALUE1
AA       | XX
AA       | YY
</code>```

and

```<code>FILENAME | VALUE2
DD       | GG
DD       | HH
</code>```

but I need the result to be:

```<code>FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH
</code>```

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

```<code>SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');
</code>```

Any help is appreciated.

答:
One way using row_number() could be as follow.

```<code>with cte as(
select t.*, row_number() over(partition by FILENAME1 order by value1) as rn
from table1 t
  )
select t1.FILENAME1, t1.value1 as value1, t2.value1 as value2
from cte t1
join cte t2
on t1.rn = t2.rn and t1.FILENAME1 = 'AA' and t2.FILENAME1 = 'DD'
</code>```

What the above does is that in cte it assigned row_number() starting from 1 partition by FILENAME1 and then in main query, it joins the table to itself on row_number() and other respective hardcoded values.

Result:

```<code>+-----------+--------+--------+
| FILENAME1 | VALUE1 | VALUE2 |
+-----------+--------+--------+
| AA        | XX     | GG     |
| AA        | YY     | HH     |
+-----------+--------+--------+
</code>```

DEMO

Body:
I have a table with all my data. I have tried joins, subqueries and unions, but none give me the desired result. I am running Oracle 12g.

This is a sample table:

FILENAME | VALUE | RAW
AA       | XX    | ZZ
AA       | YY    | WW
DD       | GG    | II
DD       | HH    | JJ

The current SQL statement that I use is:

SELECT FILENAME, VALUE VALUE1 FROM TABLE WHERE FILENAME='AA';
SELECT FILENAME, VALUE VALUE2 FROM TABLE WHERE FILENAME='DD';

And I get the following result:

FILENAME | VALUE1
AA       | XX
AA       | YY

and

FILENAME | VALUE2
DD       | GG
DD       | HH

but I need the result to be:

FILENAME | VALUE1 | VALUE2
AA       | XX     | GG
AA       | YY     | HH

It doesn't matter if AA or DD is in the FILENAME. There are no foreign keys or unique values that I can do a simple INNER JOIN. I am not able to add new columns to the table. I was hoping to do sort my data and then use Oracle's ROWNUM as a temp column which I could then use to do a SELF JOIN but Oracle won't let me.

Example:

SELECT L.FILENAME, L.VALUE VALUE1, R.VALUE VALUE2
FROM TABLE L JOIN TABLE R
ON (L.ROWNUM=R.ROWNUM)
WHERE L.FILENAME IN ('AA','DD');

Any help is appreciated.

Body:
One way using row_number() could be as follow.

with cte as(
select t.*, row_number() over(partition by FILENAME1 order by value1) as rn
from table1 t
  )
select t1.FILENAME1, t1.value1 as value1, t2.value1 as value2
from cte t1
join cte t2
on t1.rn = t2.rn and t1.FILENAME1 = 'AA' and t2.FILENAME1 = 'DD'

What the above does is that in cte it assigned row_number() starting from 1 partition by FILENAME1 and then in main query, it joins the table to itself on row_number() and other respective hardcoded values.

Result:

+-----------+--------+--------+
| FILENAME1 | VALUE1 | VALUE2 |
+-----------+--------+--------+
| AA        | XX     | GG     |
| AA        | YY     | HH     |
+-----------+--------+--------+

DEMO


问:
How can I make custom SQL with order by in codeigniter
My code is here Sql Query :

```<code>$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();
</code>```

view all products by using customs SQL but still not showing order by desc.

答:
Can you "describe" type the table? If the field "product_id" is text (Example: VARCHAR), then it will never follow the order asc/desc..

Sorry My English.. Good work!

Body:
My code is here Sql Query :

$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();

view all products by using customs SQL but still not showing order by desc.


问:
How to replace two characters at the same time with js?
Below is my code.

```<code> var str = 'test//123_456';
 var new_str = str .replace(/\//g, '').replace(/_/g, '');
 console.log(new_str);
</code>```

It will print test123456 on the screen.

My question is how to do it in same regular express? not replace string twice.

Thanks.

答:
Use character class in the regex to match any character in the collection. Although use repetition (+, 1 or more) for replacing // in a single match.

```<code>var new_str = str .replace(/[/_]+/g, '');
</code>```

var str = 'test//123_456';
var new_str = str.replace(/[/_]+/g, '');
console.log(new_str);```

FYI : Inside the character class, there is no need to escape the forward slash(in case of Javascript RegExp).

Body:
Below is my code.

 var str = 'test//123_456';
 var new_str = str .replace(/\//g, '').replace(/_/g, '');
 console.log(new_str);

It will print test123456 on the screen.

My question is how to do it in same regular express? not replace string twice.

Thanks.

Body:
Use character class in the regex to match any character in the collection. Although use repetition (+, 1 or more) for replacing // in a single match.

var new_str = str .replace(/[/_]+/g, '');

var str = 'test//123_456';
var new_str = str.replace(/[/_]+/g, '');
console.log(new_str);

FYI : Inside the character class, there is no need to escape the forward slash(in case of Javascript RegExp).


问:
Maven TestNG Class No found exception
I'm running TestNG file from maven and I'm getting this exception.
I checked target folder of maven there are no classes generated

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test
  (default-test) on project Tes ts: Execution default-test of goal
  org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test failed:
  There was an error in the forked process

[ERROR] org.testng.TestNGException: [ERROR] Cannot find class in
  classpath: ai.dharma.web.test.functional.TestBaseSetup [ERROR] at
  org.testng.xml.XmlClass.loadClass(XmlClass.java:81) [ERROR] at
  org.testng.xml.XmlClass.init(XmlClass.java:73)

答:
Ok i found answer almost after 5 days of deep search..

it was folder structure,it should be "Src > Main > Java" + your regular package structure, maven searches through that structure for generating class..

Title: Maven TestNG Class No found exception


问:
Storing state in Elixir
Recently I tackled a problem which involved updating a large number of key values.

Naturally, I considered using a Map, with operations like Map.put/3.

However this seemed insufficient, given the immutable nature of data structures in Elixir:

iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1}
```

I then solved the problem by holding the state of the Map in a GenServer, and updating it using handle_cast/3 calls.

Generally, is this the right approach, or was this too much here?

答:
I then solved the problem by holding the state of the Map in a GenServer [...]
  Generally, is this the right approach, or was this too much here?

It heavily depends on your goal. There are many different ways to store the state. Rebinding variables like:

```<code>m = Map.put(%{}, :a, 1)
#⇒ %{a: 1}
m = Map.put(m, :b, 2)
#⇒ %{a: 1, b: 2}
</code>```

Does not store anything. It binds the local variable m to RHO and as soon as the control flow leaves the scope, this variable becomes garbage collected. Whether you need the aforementioned map within a single scope, GenServer (and other state holders) is an overkill.

OTOH, if you need to store the state for a long time and share it between different scopes (e. g. between different processes,) GenServer is the simplest way to accomplish that. In Elixir we have Agent module to decrease the boilerplate for GenServer that is used as a simple in-memory storage, but my advice would be to always use GenServer: sooner or later Agent will become too tight for your purposes.

Also, one might use ets module to keep in-memory key-value storage, shared between processes.

dets is a way to store the state between process restarts.

And, finally, mnesia is an OTP native approach to share the state between both restarts and different nodes (in distributed environment.)

Title: Storing state in Elixir

Body:
Recently I tackled a problem which involved updating a large number of key values.

Naturally, I considered using a Map, with operations like Map.put/3.

However this seemed insufficient, given the immutable nature of data structures in Elixir:

iex> m = Map.put(%{}, :a, 1)
%{a: 1}
iex> Map.put(m, :b, 2)
%{a: 1, b: 2}
iex> m
%{a: 1}

I then solved the problem by holding the state of the Map in a GenServer, and updating it using handle_cast/3 calls.

Generally, is this the right approach, or was this too much here?

Body:
I then solved the problem by holding the state of the Map in a GenServer [...]
  Generally, is this the right approach, or was this too much here?

It heavily depends on your goal. There are many different ways to store the state. Rebinding variables like:

m = Map.put(%{}, :a, 1)
#⇒ %{a: 1}
m = Map.put(m, :b, 2)
#⇒ %{a: 1, b: 2}

Does not store anything. It binds the local variable m to RHO and as soon as the control flow leaves the scope, this variable becomes garbage collected. Whether you need the aforementioned map within a single scope, GenServer (and other state holders) is an overkill.

OTOH, if you need to store the state for a long time and share it between different scopes (e. g. between different processes,) GenServer is the simplest way to accomplish that. In Elixir we have Agent module to decrease the boilerplate for GenServer that is used as a simple in-memory storage, but my advice would be to always use GenServer: sooner or later Agent will become too tight for your purposes.

Also, one might use ets module to keep in-memory key-value storage, shared between processes.

dets is a way to store the state between process restarts.

And, finally, mnesia is an OTP native approach to share the state between both restarts and different nodes (in distributed environment.)


问:
face_recognition.load_image_file("{}"), what does it mean?
I'm newbie in python. Now I'm working with python related project. I saw following code while I am searching in google related to project.

```<code>image = face_recognition.load_image_file("{}")
</code>```

What does "{}" do inside load_image_file() function? Also, When and where should I use it?

答:
According to documentation:

```<code>face_recognition.api.load_image_file(file, mode='RGB')[source]
Loads an image file (.jpg, .png, etc) into a numpy array

Parameters:
file – image file name or file object to load
mode – format to convert the image to. Only ‘RGB’ (8-bit RGB, 3 channels) and ‘L’ (black and white) are supported.
Returns:
image contents as numpy array
</code>```

https://face-recognition.readthedocs.io/en/latest/face_recognition.html#face_recognition.api.load_image_file

So you need to pas image path or object. "{}" sims incomplete code to me.

Body:
I'm newbie in python. Now I'm working with python related project. I saw following code while I am searching in google related to project.

image = face_recognition.load_image_file("{}")

What does "{}" do inside load_image_file() function? Also, When and where should I use it?

Body:
According to documentation:

face_recognition.api.load_image_file(file, mode='RGB')[source]
Loads an image file (.jpg, .png, etc) into a numpy array

Parameters:
file – image file name or file object to load
mode – format to convert the image to. Only ‘RGB’ (8-bit RGB, 3 channels) and ‘L’ (black and white) are supported.
Returns:
image contents as numpy array

https://face-recognition.readthedocs.io/en/latest/face_recognition.html#face_recognition.api.load_image_file

So you need to pas image path or object. "{}" sims incomplete code to me.


问:
How to show two properties when filtering a list in Angular
I am trying to show two properties of an object. To do this, I am filtering from an array using another one of it's properties. I found a solution on here but it only works for a single property.

Here is a sample code

```<code>controller.js
$scope.people= [{name, last_name, code}, {name, last_name, code}];

view
<tr ng-repeat="item in transactions | filter:search">
  <td>{{(people| filter : {code:item.person_code}:true)[0].name}}</td>
</tr>
</code>```

I want to be able to show not only the name but also the last_name. Separated by comma if possible.

Right now it works but I am only displaying the name and I don't know how to display more than one property.

Is this even possible???

答:
You should store filters result into temp variable and then use it to show desired properties:

```<code><tr ng-repeat="item in transactions | filter : search">
    <td ng-init='temp = (people | filter : {code:item.person_code}:true)[0]'>
         {{temp.name}} {{temp.last_name}}
    </td>
</tr>
</code>```

Body:
I am trying to show two properties of an object. To do this, I am filtering from an array using another one of it's properties. I found a solution on here but it only works for a single property.

Here is a sample code

controller.js
$scope.people= [{name, last_name, code}, {name, last_name, code}];

view

  {{(people| filter : {code:item.person_code}:true)[0].name}}

I want to be able to show not only the name but also the last_name. Separated by comma if possible.

Right now it works but I am only displaying the name and I don't know how to display more than one property.

Is this even possible???

Body:
You should store filters result into temp variable and then use it to show desired properties:

<tr ng-repeat="item in transactions | filter : search">
    <td ng-init='temp = (people | filter : {code:item.person_code}:true)[0]'>
         {{temp.name}} {{temp.last_name}}
    </td>
</tr>


问:
communication between two containers using another container

I am running a docker server container attached to the server_router network (bridge network driver) and a docker client container attached to the client_router network (bridge network driver). Router container is connected to both server_router and client_router network.

I need this network topology where server and client belong to different docker networks and router is able to connect the server and client containers (actual router which can route server and client traffic). This is needed for network simulation where i am running the simulation on docker containers instead of actual computers. (network simulator being used is TCP Experiment Automation Controlled Using Python (TEACUP) ).

commands used to create the setup:

```<code>docker network create server_router
docker network create client_router
docker run -itd --net client_router --name client ubuntu:14.04
docker run -itd --net server_router --name server ubuntu:14.04
docker run -itd --net server_router --name router ubuntu:14.04
docker network connect client_router router
docker network inspect client_router
docker network inspect server_router
</code>```

representation of the network topology

I am able to ping client container from router container and vice versa, also I am able to ping server container from router container and vice versa (as they belong to the same network).
But I am not able to ping server container from client container and vice versa.

ping command does not show any result.

Any suggestions will be of great help.

答:
OK if this is for mockup and testing, let's list the actions you'll likely need to check off:

You'd need to ensure the router is setup to route IP packets between the two virtual networks.

You'd need to hardcode IP subnets during network creation.

You'd need to hardcode routes during router creation.

Because the default gateway of client and server are not the router container, you'd need to manually add routes to those containers to know they need to go through the router to talk to each other.

You'd need to manually edit host files in client and server if you want to address them by name.

You'd need to manually identify IP's of each container for above DNS to work.

And likely more steps I'm forgetting...

Body:
I am running a docker server container attached to the server_router network (bridge network driver) and a docker client container attached to the client_router network (bridge network driver). Router container is connected to both server_router and client_router network.

I need this network topology where server and client belong to different docker networks and router is able to connect the server and client containers (actual router which can route server and client traffic). This is needed for network simulation where i am running the simulation on docker containers instead of actual computers. (network simulator being used is TCP Experiment Automation Controlled Using Python (TEACUP) ).

commands used to create the setup:

docker network create server_router
docker network create client_router
docker run -itd --net client_router --name client ubuntu:14.04
docker run -itd --net server_router --name server ubuntu:14.04
docker run -itd --net server_router --name router ubuntu:14.04
docker network connect client_router router
docker network inspect client_router
docker network inspect server_router

representation of the network topology

I am able to ping client container from router container and vice versa, also I am able to ping server container from router container and vice versa (as they belong to the same network).
But I am not able to ping server container from client container and vice versa.

ping command does not show any result.

Any suggestions will be of great help.


问:
How to apply values in column based on condition in row values in python
I have a dataframe that looks like this:

df

```<code>    Name        year    week    date
0   Adam        2016    16  2016-04-24
1   Mary        2016    17  2016-05-01
2   Jane        2016    20  2016-05-22
3   Joe         2016    17  2016-05-01
4   Arthur      2017    44  2017-11-05
5   Liz         2017    41  2017-10-15
6   Janice      2016    47  2016-11-27
</code>```

And I want to create column season so df['season'] that attributes a season MAM or OND depending on the value in week.

The result should look like this:

df_final

```<code>    Name        year    week    date      season
0   Adam        2016    16      2016-04-24 MAM
1   Mary        2016    17      2016-05-01 MAM
2   Jane        2016    20      2016-05-22 MAM
3   Joe         2016    17      2016-05-01 MAM
4   Arthur      2017    44      2017-11-05 OND
5   Liz         2017    41      2017-10-15 OND
6   Janice      2016    47      2016-11-27 OND
</code>```

In essence, values of week that are below 40 should be paired with MAM and values above 40 should be OND.

So far I have this:

```<code>condition =df.week < 40
df['season'] = df[condition][[i for i in df.columns.values if i not in   ['a']]].apply(lambda x: 'OND')
</code>```

But it is clunky and does not produce the final response.

Thank you.

答:
Use numpy.where:

```<code>condition = df.week < 40
df['season'] = np.where(condition, 'MAM', 'OND')
print (df)
     Name  year  week        date season
0    Adam  2016    16  2016-04-24    MAM
1    Mary  2016    17  2016-05-01    MAM
2    Jane  2016    20  2016-05-22    MAM
3     Joe  2016    17  2016-05-01    MAM
4  Arthur  2017    44  2017-11-05    OND
5     Liz  2017    41  2017-10-15    OND
6  Janice  2016    47  2016-11-27    OND
</code>```

EDIT:

For convert strings to integers use astype:

```<code>condition = df.week.astype(int) < 40
</code>```

Or convert column:

```<code>df.week = df.week.astype(int)
condition = df.week < 40
</code>```

Body:
I have a dataframe that looks like this:

df

    Name        year    week    date
0   Adam        2016    16  2016-04-24
1   Mary        2016    17  2016-05-01
2   Jane        2016    20  2016-05-22
3   Joe         2016    17  2016-05-01
4   Arthur      2017    44  2017-11-05
5   Liz         2017    41  2017-10-15
6   Janice      2016    47  2016-11-27

And I want to create column season so df['season'] that attributes a season MAM or OND depending on the value in week.

The result should look like this:

df_final

    Name        year    week    date      season
0   Adam        2016    16      2016-04-24 MAM
1   Mary        2016    17      2016-05-01 MAM
2   Jane        2016    20      2016-05-22 MAM
3   Joe         2016    17      2016-05-01 MAM
4   Arthur      2017    44      2017-11-05 OND
5   Liz         2017    41      2017-10-15 OND
6   Janice      2016    47      2016-11-27 OND

In essence, values of week that are below 40 should be paired with MAM and values above 40 should be OND.

So far I have this:

condition =df.week < 40
df['season'] = df[condition][[i for i in df.columns.values if i not in   ['a']]].apply(lambda x: 'OND')

But it is clunky and does not produce the final response.

Thank you.

Body:
Use numpy.where:

condition = df.week < 40
df['season'] = np.where(condition, 'MAM', 'OND')
print (df)
     Name  year  week        date season
0    Adam  2016    16  2016-04-24    MAM
1    Mary  2016    17  2016-05-01    MAM
2    Jane  2016    20  2016-05-22    MAM
3     Joe  2016    17  2016-05-01    MAM
4  Arthur  2017    44  2017-11-05    OND
5     Liz  2017    41  2017-10-15    OND
6  Janice  2016    47  2016-11-27    OND

EDIT:

For convert strings to integers use astype:

condition = df.week.astype(int) < 40

Or convert column:

df.week = df.week.astype(int)
condition = df.week < 40


问:
How to interpret using Most Significant Bit of single byte - Pcapng time format "if_tsresol"
I'm writing a library to parse a file format (pcapng) documented here. There's one particular section I'm having trouble with, it's an option that defines how the long epoch/time variable should be parsed. The option if_tsresol is defined by a single octlet/byte, according to the spec:

The if_tsresol option identifies the resolution of timestamps. If the
  Most Significant Bit is equal to zero, the remaining bits indicates
  the resolution of the timestamp as a negative power of 10 (e.g. 6
  means microsecond resolution, timestamps are the number of
  microseconds since 1/1/1970). If the Most Significant Bit is equal to
  one, the remaining bits indicates the resolution as as negative power
  of 2 (e.g. 10 means 1/1024 of second). If this option is not present,
  a resolution of 10^-6 is assumed (i.e. timestamps have the same
  resolution of the standard 'libpcap' timestamps).

Example: '6'.

I'm happy with how either case works. E.g. for the first, if the value is '0' it represents seconds since 1970, '3' means milliseconds since 1970, '9' would mean microseconds etc.

I'm also happy with the second case, 10 would mean it's 1/1024 of a second, (i.e. nearly milliseconds), 20 would mean 1/1048576 of a second (i.e. nearly microsecond).

My confusion is over the "Most Significant Bit", and how to choose between these two. My understanding is the Most Significant Bit is effectively the left-most bit in a bit sequence.

So, taking the first example, a value of '3' has the bits 00000011, so the most significant bit is equal to zero right?

However, this first significant bit won't stop being zero until the whole byte is 128 or greater, in which case the second 'option' is meaningless as we're expecting a number from 10-30.

Should I be ignoring the first bit in the calculation of the byte itself? So:

```<code>00001010 = 10 which is 10 (option 1)
10001010 = 138 which is 10 (option 2)
</code>```

and

```<code>00000110 = 6 which is 6 (option 1)
10000110 = 134 which is 6 (option 2)
</code>```

答:
Should I be ignoring the first bit in the calculation of the byte itself?

Yes.  As the pcapng spec says:

If the Most Significant Bit is equal to one, the remaining bits indicates the resolution as as negative power of 2 (e.g. 10 means 1/1024 of second).

so the first bit is a flag and the rest of the bits are the value, and you ignore the first bit when doing the calculation.

Body:
I'm writing a library to parse a file format (pcapng) documented here. There's one particular section I'm having trouble with, it's an option that defines how the long epoch/time variable should be parsed. The option if_tsresol is defined by a single octlet/byte, according to the spec:

The if_tsresol option identifies the resolution of timestamps. If the
  Most Significant Bit is equal to zero, the remaining bits indicates
  the resolution of the timestamp as a negative power of 10 (e.g. 6
  means microsecond resolution, timestamps are the number of
  microseconds since 1/1/1970). If the Most Significant Bit is equal to
  one, the remaining bits indicates the resolution as as negative power
  of 2 (e.g. 10 means 1/1024 of second). If this option is not present,
  a resolution of 10^-6 is assumed (i.e. timestamps have the same
  resolution of the standard 'libpcap' timestamps).

Example: '6'.

I'm happy with how either case works. E.g. for the first, if the value is '0' it represents seconds since 1970, '3' means milliseconds since 1970, '9' would mean microseconds etc.

I'm also happy with the second case, 10 would mean it's 1/1024 of a second, (i.e. nearly milliseconds), 20 would mean 1/1048576 of a second (i.e. nearly microsecond).

My confusion is over the "Most Significant Bit", and how to choose between these two. My understanding is the Most Significant Bit is effectively the left-most bit in a bit sequence.

So, taking the first example, a value of '3' has the bits 00000011, so the most significant bit is equal to zero right?

However, this first significant bit won't stop being zero until the whole byte is 128 or greater, in which case the second 'option' is meaningless as we're expecting a number from 10-30.

Should I be ignoring the first bit in the calculation of the byte itself? So:

00001010 = 10 which is 10 (option 1)
10001010 = 138 which is 10 (option 2)

and

00000110 = 6 which is 6 (option 1)
10000110 = 134 which is 6 (option 2)


问:
How can I avoid duplicate rows from SQL statement?
My problem is, that the following SQL query returns duplicate rows:

```<code>select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;
</code>```

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?

答:
The following query returns just one record per pmid:

```<code>    select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
inv.i4204 as device,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
device,
CustomerName
order by pmid;
</code>```

Meanwhile I solved the problem by exporting the results into a single Postgres table and removing the duplicate rows with a simple max() aggregation function.

Thanks you all for you time to read my posting.

Body:
My problem is, that the following SQL query returns duplicate rows:

select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;

What do I do to get just one row for each pmid with the latest dateCalibration and/or dateExpiry?

Body:
The following query returns just one record per pmid:

    select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
inv.i4204 as device,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
device,
CustomerName
order by pmid;

Meanwhile I solved the problem by exporting the results into a single Postgres table and removing the duplicate rows with a simple max() aggregation function.

Thanks you all for you time to read my posting.


问:
Mysql SUM based on condition
I need help to formulate a query to calculate points based on user action.
There is a user table which stores user info and each user belongs to a specific category (User category). Each category has different levels (say level1, level2 etc..)  and each level has a set of tasks(Task1,Task2...) to be completed. Each task can be performed multiple times. But points is calculated based on a maximum limit field.

Task 1 - 10 points ( Max:2 - Means user can perform this task N times but for point calculation it will be only counted twice )

Task 2 - 5 points  ( Max:1 )

For example lets say User1 performs Task1 5 times, but for point calculation Task1 will only be counted 2 times , so total points is 20. This is similar for all tasks.

On completing each task the user gains N points and get upgraded to next level.
 Please find below the table structure and query:

users

uid , uname , uc_id ( References User Category ) , ul_id (References user level and indicates current level of user )

user_category

uc_id  ....

user_level

ul_id, uc_id (References User Category)
 ...

level_tasks

lt_id , ul_id (References User level) , lt_point, lt_max

user_tasks

ut_id, lt_id (References level task), uid (References user)

The below is the query i have tried so far :

SELECT uid, SUM(LT.lt_point/LT.lt_max) as TotalLevelPoints
FROM users AS U
INNER JOIN  user_tasks AS UT ON UT.ut_user_id = U.id
INNER JOIN  level_tasks AS LT ON LT.lt_id = UT.lt_id
INNER JOIN  user_level AS UL ON UL.ul_id = LT.ul_id
INNER JOIN  user_category AS UC ON UC.uc_id = UL.uc_id
WHERE UT.ut_status = 1 AND U.uid = 1 AND UL.ul_id = 1
GROUP BY U.uid

This gives all the sum without considering the max limit, how should i write so that sum is calculated on that column also.
Hope my question is clear enough.. Any help would be really appreciated.

答:
I believe you will need to do this in 2 steps. First sum the points and compare to the maximums allowed for each task type. Once that is determined, sum those results for each user. e.g.</p>

```<code>SELECT
      u.uid
    , SUM(user_task_points) AS user_task_points
FROM users AS u
INNER JOIN (
      SELECT
            ut.UT_user_id
          , lt_id
          , lt.LT_point
          , lt.LT_max_times
          , CASE WHEN SUM(lt.LT_point) > (lt.LT_point * lt.LT_max_times) THEN (lt.LT_point * lt.LT_max_times)
                 ELSE SUM(lt.LT_point)
            END AS user_task_points
      FROM user_tasks AS ut
      INNER JOIN level_tasks AS lt ON ut.UT_rule_id = lt.LT_id
      INNER JOIN  user_level AS UL ON UL.ul_id = LT.ul_id
      WHERE ut.UT_status = 1
          AND ut.UT_user_id = 1
          AND ul.ul_id = 1
      GROUP BY
            ut.UT_user_id
          , lt_id
          , lt.LT_point
          , lt.LT_max_times
      ) AS p ON u.id = p.UT_user_id
GROUP BY
      u.uid
;
</code>```

Title: Mysql SUM based on condition

Body:
I believe you will need to do this in 2 steps. First sum the points and compare to the maximums allowed for each task type. Once that is determined, sum those results for each user. e.g.

SELECT
      u.uid
    , SUM(user_task_points) AS user_task_points
FROM users AS u
INNER JOIN (
      SELECT
            ut.UT_user_id
          , lt_id
          , lt.LT_point
          , lt.LT_max_times
          , CASE WHEN SUM(lt.LT_point) > (lt.LT_point * lt.LT_max_times) THEN (lt.LT_point * lt.LT_max_times)
                 ELSE SUM(lt.LT_point)
            END AS user_task_points
      FROM user_tasks AS ut
      INNER JOIN level_tasks AS lt ON ut.UT_rule_id = lt.LT_id
      INNER JOIN  user_level AS UL ON UL.ul_id = LT.ul_id
      WHERE ut.UT_status = 1
          AND ut.UT_user_id = 1
          AND ul.ul_id = 1
      GROUP BY
            ut.UT_user_id
          , lt_id
          , lt.LT_point
          , lt.LT_max_times
      ) AS p ON u.id = p.UT_user_id
GROUP BY
      u.uid
;


问:
Javascript, inner classes, and how to access parent scope efficiently
In Javascript, I would like to define a class with an inner (or nested) class.  Within the inner class I'd like to be able to get access to the parent instance. How can I do this efficiently?

Some code will show what I mean. Suppose I define a class, MyType1, which exposes several properties and one function, SayHello:

```<code>(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();
</code>```

Ok, now, starting from there, I want to add an "inner class" to MyType1, so I add some new code so that it looks like this:

```<code>(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
        var parentName = name;
        this.Child = function(name) {
            this.Description = parentName + "'s child, " + name;
        };

        this.Child.prototype.Introduce = function() {
            say(this.Description + ", greets you...");
        };
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();
</code>```

Now I can use these classes like this:

```<code>var x = new MyType1("Victor");
x.SayHello();

var c = new x.Child("Elizabeth");
c.Introduce();
</code>```

that all works.  But it defines a new Child function (or type, if you like) for every instance of MyType1.  What I'd like to do is get access to the parent class scope, without resorting to that inefficiency.
Something like this:

```<code>(function(){
    MyType2 = function(name){
        this.TypeName = "MyType2";
        this.Name = name;
        this.Prop1 = 1872;
        var parentName = name;
    };

    MyType2.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };

    var c1 = function(name) {
        this.Description = parentName + "'s child, " + name;
        //                ^^ no go! ^^
    };

    c1.prototype.Introduce = function() {
        say(this.Description + ", greets you...");
    };

    MyType2.prototype.Child = c1;

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

But, this doesn't work.  The parentName var is out of scope, of course.

Is there an efficient way for the Child instance (in the constructor, or in any class function) to gain access to the parent (MyType2) instance?

I know that I could define the Child class to be an independent, non-nested class, then in the ctor for that, just pass the Parent instance. But this creates N references to the parent instance, one for every Child instance. That seems like an inefficiency I'd like to avoid.

thanks for any tips.

EDIT - the reason I want the Child to have access to the parent instance, is that the parent holds an object that is fairly expensive to create - something like a db connection - and I'd like the child to be able to utilize that thing.

答:
It would probably help you out if you do away with notions like "type", "class", etc. when dealing with javascript.  In javascript, there is no differentiation from "type", "class", "function", "instance", or "object" -- it's "object" all the way down.

Since every "type" is an "object" and is mutable, you get nothing of the sort of strong-typed efficiency gains you might get from Java or C++ by reusing a single type definition.  Think of the "new" operator in javascript as something like "clone the definition and call the constructor", after which the definition of the instance could still be changed.

So go with your first, working example: you won't get any gains by doing something different.

Body:
In Javascript, I would like to define a class with an inner (or nested) class.  Within the inner class I'd like to be able to get access to the parent instance. How can I do this efficiently?

Some code will show what I mean. Suppose I define a class, MyType1, which exposes several properties and one function, SayHello:

(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();

Ok, now, starting from there, I want to add an "inner class" to MyType1, so I add some new code so that it looks like this:

(function(){
    MyType1 = function(name){
        this.TypeName = "MyType1";
        this.Name = name;
        var parentName = name;
        this.Child = function(name) {
            this.Description = parentName + "'s child, " + name;
        };

        this.Child.prototype.Introduce = function() {
            say(this.Description + ", greets you...");
        };
    };

    MyType1.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };
})();

Now I can use these classes like this:

var x = new MyType1("Victor");
x.SayHello();

var c = new x.Child("Elizabeth");
c.Introduce();

that all works.  But it defines a new Child function (or type, if you like) for every instance of MyType1.  What I'd like to do is get access to the parent class scope, without resorting to that inefficiency.
Something like this:

(function(){
    MyType2 = function(name){
        this.TypeName = "MyType2";
        this.Name = name;
        this.Prop1 = 1872;
        var parentName = name;
    };

    MyType2.prototype.SayHello = function() {
        say(this.Name + " says hello...");
    };

    var c1 = function(name) {
        this.Description = parentName + "'s child, " + name;
        //                ^^ no go! ^^
    };

    c1.prototype.Introduce = function() {
        say(this.Description + ", greets you...");
    };

    MyType2.prototype.Child = c1;

})();

But, this doesn't work.  The parentName var is out of scope, of course.

Is there an efficient way for the Child instance (in the constructor, or in any class function) to gain access to the parent (MyType2) instance?

I know that I could define the Child class to be an independent, non-nested class, then in the ctor for that, just pass the Parent instance. But this creates N references to the parent instance, one for every Child instance. That seems like an inefficiency I'd like to avoid.

thanks for any tips.

EDIT - the reason I want the Child to have access to the parent instance, is that the parent holds an object that is fairly expensive to create - something like a db connection - and I'd like the child to be able to utilize that thing.


问:
Lazy loading. No component factory found. Did you add it to @NgModule.entryComponents?
I create page with simple modal window using ng2-bootstrap library. It looks like:

action-list.component.html

```<code><a class="btn-setting"  (click)="dangerModal.show()"><i class="fa fa-trash"></i></a>

<div bsModal #dangerModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-danger" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Modal title</h4>
        <button type="button" class="close" (click)="dangerModal.hide()" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="dangerModal.hide()">Close</button>
        <button type="button" class="btn btn-primary" (click)="delete()">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

But when I clicked trash icon (first href) I got error:

```<code>ERROR Error: No component factory found for ModalBackdropComponent. Did you add it to @NgModule.entryComponents?
    at noComponentFactoryError (core.es5.js:3202)
    at CodegenComponentFactoryResolver.webpackJsonp.../../../core/@angular/core.es5.js.CodegenComponentFactoryResolver.resolveComponentFactory (core.es5.js:3267)
    at ComponentLoader.webpackJsonp.../../../../ng2-bootstrap/component-loader/component-loader.class.js.ComponentLoader.attach (component-loader.class.js:42)
    at ModalDirective.webpackJsonp.../../../../ng2-bootstrap/modal/modal.component.js.ModalDirective.showBackdrop (modal.component.js:195)
    at ModalDirective.webpackJsonp.../../../../ng2-bootstrap/modal/modal.component.js.ModalDirective.show (modal.component.js:102)
    at Object.eval [as handleEvent] (ActionListComponent.html:102)
    at handleEvent (core.es5.js:12047)
    at callWithDebugContext (core.es5.js:13506)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13094)
    at dispatchEvent (core.es5.js:8659)
</code>```

I found info that may by missing entryComponents annotation in my module for showing component, so I tried add:

action.module.ts

```<code>@NgModule({
    //...
    imports: [
        //...
        ModalModule,
    ],
    entryComponents: [
        ModalBackdropComponent
    ]
})
</code>```

But i still have the same error.

My question: Can the error be caused by lazy loading my module? If so, how can I get around this issue? If you know answer, let me explain how does entryComponents work, please.

答:
In my case, forgetting to add the NgbModule to my lazy loaded module imports caused the same error. So, the solution template is the following:

```<code>@NgModule({
  imports: [
    ...
    NgbModule,
    ...
  ],
  declarations: [
    ...
    ModalDlgComponent,
    ...
  ],
  entryComponents: [
    ...
    ModalDlgComponent,
    ...
  ]
})
export class MyLazyLoadedModule {}
</code>```

Body:
I create page with simple modal window using ng2-bootstrap library. It looks like:

action-list.component.html

Modal title

        <button type="button" class="close" (click)="dangerModal.hide()" aria-label="Close">
          ×
        </button>

One fine body…

        <button type="button" class="btn btn-secondary" (click)="dangerModal.hide()">Close</button>
        <button type="button" class="btn btn-primary" (click)="delete()">Save changes</button>

But when I clicked trash icon (first href) I got error:

ERROR Error: No component factory found for ModalBackdropComponent. Did you add it to @NgModule.entryComponents?
    at noComponentFactoryError (core.es5.js:3202)
    at CodegenComponentFactoryResolver.webpackJsonp.../../../core/@angular/core.es5.js.CodegenComponentFactoryResolver.resolveComponentFactory (core.es5.js:3267)
    at ComponentLoader.webpackJsonp.../../../../ng2-bootstrap/component-loader/component-loader.class.js.ComponentLoader.attach (component-loader.class.js:42)
    at ModalDirective.webpackJsonp.../../../../ng2-bootstrap/modal/modal.component.js.ModalDirective.showBackdrop (modal.component.js:195)
    at ModalDirective.webpackJsonp.../../../../ng2-bootstrap/modal/modal.component.js.ModalDirective.show (modal.component.js:102)
    at Object.eval [as handleEvent] (ActionListComponent.html:102)
    at handleEvent (core.es5.js:12047)
    at callWithDebugContext (core.es5.js:13506)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13094)
    at dispatchEvent (core.es5.js:8659)

I found info that may by missing entryComponents annotation in my module for showing component, so I tried add:

action.module.ts

@NgModule({
    //...
    imports: [
        //...
        ModalModule,
    ],
    entryComponents: [
        ModalBackdropComponent
    ]
})

But i still have the same error.

My question: Can the error be caused by lazy loading my module? If so, how can I get around this issue? If you know answer, let me explain how does entryComponents work, please.

Body:
In my case, forgetting to add the NgbModule to my lazy loaded module imports caused the same error. So, the solution template is the following:

@NgModule({
  imports: [
    ...
    NgbModule,
    ...
  ],
  declarations: [
    ...
    ModalDlgComponent,
    ...
  ],
  entryComponents: [
    ...
    ModalDlgComponent,
    ...
  ]
})
export class MyLazyLoadedModule {}


问:
OpenCV running optical flow on particular rectangles
I am using OpenCV's Optical Flow module. I understand the examples in the documentation but those take the entire image and then get the optical flow over the image.

I only want to pass it over some parts of an image. Is it possible to do that? If yes, how do I go about it?

Thanks!

答:
Yes, it's possible. cv2.calcOpticalFlowPyrLK() will be the optical flow function you need. Before you make that function call, you will have to create an image mask. I did a similar project, but in C++, though I can outline the steps for you:

Create an empty matrix with same width and height of your images

Using the points from your ROI, create a shape out of it (I did mine using cv2.fillPoly()) and fill the inside of the shape with white (Your image mask should only be comprised of black and white color)

If you are planning on using corners as features, then call cv2.goodFeaturesToTrack() and pass in the mask you've made as one of its arguments.

If you're using the Feature2D module to detect features, you can use the same mask to only extract the features in that masked area.

By this step, you should now have a collection of features/points that are only within the bounds of the shape! Call the optical flow function and then process the results.

I hope that helps.


问:
How to get the name of decorator for function at run time?
In the following code the methods(print_a and print_b) of class Test, has been decorated by the two different decorators.

How can I determine that the given method(let say print_a), is decorated with some specific decorator (decorator1) at the runtime?

The easy solution is to change the name of the wrapper function, i.e. changing the wrapper to wrapper1 and wrapper2 in the decorator method, but the problem with that is I don't have control over that part of the code.

Does python have any reflection API like Java, and could that help me here ?

```<code>def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    return wrapper

def my_decorator2(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:2')
        func(*args, **kwargs)
    return wrapper

class Test():

    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

    @my_decorator1
    def print_a(self):
        print('Value of a is {}'.format(self.a))

    @my_decorator2
    def print_b(self):
        print('Value of b is {}'.format(self.b))

if __name__ == '__main__':

    d = Test.__dict__

    f1 = d.get('print_a')
    f2 = d.get('print_b')
</code>```

答:
Since the decorator function is executed at decoration time, it is difficult to get the name. You can solve your problem with an additional decorator. The decorator annotator writes into a property of the function and you can read this name inside of the decorated function:

```<code>def annotator(decorator):
    def wrapper(f):
        g = decorator(f)
        g.decorator = decorator.__name__
        return g
    return wrapper

@annotator(my_decorator1)
def x():
    print x.decorator
</code>```

Body:
In the following code the methods(print_a and print_b) of class Test, has been decorated by the two different decorators.

How can I determine that the given method(let say print_a), is decorated with some specific decorator (decorator1) at the runtime?

The easy solution is to change the name of the wrapper function, i.e. changing the wrapper to wrapper1 and wrapper2 in the decorator method, but the problem with that is I don't have control over that part of the code.

Does python have any reflection API like Java, and could that help me here ?

def my_decorator1(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:1')
        func(*args, **kwargs)
    return wrapper

def my_decorator2(func):
    def wrapper(*args, **kwargs):
        print('I am decorated:2')
        func(*args, **kwargs)
    return wrapper

class Test():

    def __init__(self, a=None, b=None):
        self.a = a
        self.b = b

    @my_decorator1
    def print_a(self):
        print('Value of a is {}'.format(self.a))

    @my_decorator2
    def print_b(self):
        print('Value of b is {}'.format(self.b))

if __name__ == '__main__':

    d = Test.__dict__

    f1 = d.get('print_a')
    f2 = d.get('print_b')

Body:
Since the decorator function is executed at decoration time, it is difficult to get the name. You can solve your problem with an additional decorator. The decorator annotator writes into a property of the function and you can read this name inside of the decorated function:

def annotator(decorator):
    def wrapper(f):
        g = decorator(f)
        g.decorator = decorator.__name__
        return g
    return wrapper

@annotator(my_decorator1)
def x():
    print x.decorator


问:
What are the disadvantages of discarding symbols?
the program strip on GNU/Linux (man) allows you to discard symbols from object files or executables. By doing this you gain a smaller file size.

So my question is what are the trade-offs of discarding the symbols?

答: It makes debugging a great deal harder, since you no longer know what variables or functions are stored where in memory.</p>


问:
Wp_admin shows blank after udating wp_debug in wp_config
// Enable Debugging

```<code>define('WP_DEBUG', true);
</code>```

// Tell WordPress to log everything to /wp-content/debug.log

```<code>define('WP_DEBUG_LOG', true);
</code>```

// Turn off the display of error messages on your site

```<code>define('WP_DEBUG_DISPLAY', false);
</code>```

// For good measure, you can also add the follow code, which will hide errors from being displayed on-screen

```<code>@ini_set('display_errors', 0);
</code>```

wp-admin page shows blank after adding the above content to the wp_config.php in ftp to hide the errors that appear on the site page

is there any way this problem can be fixed

答:
Modify wp_config.php file.

Open wp-config.php file and find the following line of code:

Modify

define('WP_DEBUG', false);```
</div>
</div>
</p>

<p><strong>To</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>define('WP_DEBUG', true);</code>```

Body:
// Enable Debugging

define('WP_DEBUG', true);

// Tell WordPress to log everything to /wp-content/debug.log

define('WP_DEBUG_LOG', true);

// Turn off the display of error messages on your site

define('WP_DEBUG_DISPLAY', false);

// For good measure, you can also add the follow code, which will hide errors from being displayed on-screen

@ini_set('display_errors', 0);

wp-admin page shows blank after adding the above content to the wp_config.php in ftp to hide the errors that appear on the site page

is there any way this problem can be fixed

Body:
Modify wp_config.php file.

Open wp-config.php file and find the following line of code:

Modify

define('WP_DEBUG', false);

To

define('WP_DEBUG', true);


问:
F# project types in Visual Studio 2017 v15.5.0
I upgraded VS2017 to v15.5 today and I'm no longer able to create an F# project that uses plain old .NET Framework. The main options that I now see are:

Console App (.NET Core)

Class Library (.NET Standard)

There are also a bunch of other project types under .NET Core.
I'm working in an existing solution with projects that target .NET Framework 4.6.1, so I'd like to create a new project that's consistent with these. Also, I'd like the option of using WPF and other Windows-specific features. Is that no longer possible with F#?

答: Found the problem: I had "F# language support" installed, but needed to add "F# desktop language support" in 15.5. It looks like the installer deselects this option by default, even when upgrading an installation that actually has these project types.</p>


问:
How to access the elements in numpy array of sets?
By mistake I used numpy array over a set to save my result. The run was time-consuming and it is hard to repeat it. It seems something is stored in the variable, but how can I retrieve the elements inside it?

To simplify, I did something like

```<code>#import numpy as np
result = np.array({1,2,3,4})
</code>```

Now how can I access the elements (i.e., 1,2,3,4) in result?

答: The only "problem" here is that your array is a scalar (otherwise you could use result[0]). In this case you can simply use result.item().

Body:
By mistake I used numpy array over a set to save my result. The run was time-consuming and it is hard to repeat it. It seems something is stored in the variable, but how can I retrieve the elements inside it?

To simplify, I did something like

#import numpy as np
result = np.array({1,2,3,4})

Now how can I access the elements (i.e., 1,2,3,4) in result?


问:
the entity type is not part of the model for the current context strange error
My DB context initialization is as below. Everything works fine. After stop and restart project on visual studio debug mode the error 'the entity 'x' type is not part of the model for the current context' occurs for the same operation.In debug mode, I see this 'x' entityType is invoked.

But if I rebuild entity project everything works fine until next debug restart.

Any idea?

```<code>public class FsDbContext : DataContext<DbContext>, ITransientDataContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //MappingAssemblies.All.ForEach(assembly => modelBuilder.Configurations.AddFromAssembly(assembly));

        var addMethod = typeof(ConfigurationRegistrar).GetMethods().Single(m => m.Name == "Add"
            && m.GetGenericArguments().Any(a => a.Name == "TEntityType"));

        MappingAssemblies.All.ForEach(assembly =>
        {
            var configTypes = assembly.GetTypes().Where(t => t.BaseType != null
                && t.BaseType.IsGenericType
                && t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

            foreach (var type in configTypes)
            {
                var entityType = type.BaseType.GetGenericArguments().Single();

                var entityConfig = assembly.CreateInstance(type.FullName);
                addMethod.MakeGenericMethod(entityType)
                  .Invoke(modelBuilder.Configurations, new object[] { entityConfig });
            }
        });

    }
}
</code>```

答:
If you load entity assembly dynamically do not use

```<code>AppDomain.CurrentDomain.GetAssemblies()
</code>```

Use

```<code>Directory.GetFiles(path, "*.dll")
</code>```

Body:
My DB context initialization is as below. Everything works fine. After stop and restart project on visual studio debug mode the error 'the entity 'x' type is not part of the model for the current context' occurs for the same operation.In debug mode, I see this 'x' entityType is invoked.

But if I rebuild entity project everything works fine until next debug restart.

Any idea?

public class FsDbContext : DataContext<DbContext>, ITransientDataContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //MappingAssemblies.All.ForEach(assembly => modelBuilder.Configurations.AddFromAssembly(assembly));

        var addMethod = typeof(ConfigurationRegistrar).GetMethods().Single(m => m.Name == "Add"
            && m.GetGenericArguments().Any(a => a.Name == "TEntityType"));

        MappingAssemblies.All.ForEach(assembly =>
        {
            var configTypes = assembly.GetTypes().Where(t => t.BaseType != null
                && t.BaseType.IsGenericType
                && t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

            foreach (var type in configTypes)
            {
                var entityType = type.BaseType.GetGenericArguments().Single();

                var entityConfig = assembly.CreateInstance(type.FullName);
                addMethod.MakeGenericMethod(entityType)
                  .Invoke(modelBuilder.Configurations, new object[] { entityConfig });
            }
        });

    }
}

Body:
If you load entity assembly dynamically do not use

AppDomain.CurrentDomain.GetAssemblies()

Use

Directory.GetFiles(path, "*.dll")


问:
using sort and set() on list values in dictionary
I have a dictionary which has single value as key and a list as the value. I am trying to go through the dictionary values and remove duplicates and sort the lists. Im using the below code to try this.

```<code>def activity_time_from_dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()
</code>```

From printing within the loop it seems to do it correctly, but if I look at the dictionary outside of the loop it has just been sorted and the duplicates remain. I want to replace the original list in the dictionary with the seted and sorted list. What am I doing wrong ?

答:
you can try this</p>

```<code>def dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()
        return v

new_dict['your_key']=dict(old_dict)
</code>```

Body:
I have a dictionary which has single value as key and a list as the value. I am trying to go through the dictionary values and remove duplicates and sort the lists. Im using the below code to try this.

def activity_time_from_dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()

From printing within the loop it seems to do it correctly, but if I look at the dictionary outside of the loop it has just been sorted and the duplicates remain. I want to replace the original list in the dictionary with the seted and sorted list. What am I doing wrong ?

Body:
you can try this

def dict(adict):
    for v in adict.values():
        v = list(set(v))
        v.sort()
        return v

new_dict['your_key']=dict(old_dict)


问:
Want Mybatis to insert booleans as Y,N, not 0,1
I'm writing a class instance to a MySQL DB using MyBatis

```<code>// I have no control over how this java class is laid out -.-
class Hello {
    boolean isFriendly
}
</code>```

my MyBatis Mapper looks like this

```<code><insert id="doHello" parameterType="Hello">
    insert into hello_table (
        is_friendly   --this is a varchar(1) btw
    )
    values (
      #{isFriendly}
    )
 </insert>
</code>```

The problem is it inserts the values into the DB as 0 or 1, but I need to have it as 'N' or 'Y'
and I don't have the choice of modifying the java

I'm trying to keep my code as minimal as possible and ideally would like to add stuff into the Mybatis Mapper

I tried things like

```<code> #{isFriendly,jdbcType=Boolean}
</code>```

but it didn't work

答:
create handler and add it in Mybatis configuration
create handler:

```

    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.MappedJdbcTypes;
    import org.apache.ibatis.type.MappedTypes;

    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    @MappedTypes(Boolean.class)
    @MappedJdbcTypes(JdbcType.CHAR)
    public class BooleanStringTypeHandler extends BaseTypeHandler {

        @Override
        public void setNonNullParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
            preparedStatement.setString(i, aBoolean ? "Y" : "N");
        }
        @Override
        public Boolean getNullableResult(ResultSet resultSet, String s) throws SQLException {
            return getBoolean(resultSet.getString(s));
        }
        @Override
        public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
            return getBoolean(resultSet.getString(i));
        }
        @Override
        public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
            return getBoolean(callableStatement.getString(i));
        }
        private Boolean getBoolean(String s) {
            return "Y".equalsIgnoreCase(s);
        }
    }

```

add it in your Mybatis configuration:

```<code><typeHandlers>
    <typeHandler jdbcType="CHAR" javaType="java.lang.Boolean" handler="crm.data.trade.utils.BooleanStringTypeHandler"/>
</typeHandlers>
</code>```

Body:
I'm writing a class instance to a MySQL DB using MyBatis

// I have no control over how this java class is laid out -.-
class Hello {
    boolean isFriendly
}

my MyBatis Mapper looks like this

<insert id="doHello" parameterType="Hello">
    insert into hello_table (
        is_friendly   --this is a varchar(1) btw
    )
    values (
      #{isFriendly}
    )
 </insert>

The problem is it inserts the values into the DB as 0 or 1, but I need to have it as 'N' or 'Y'
and I don't have the choice of modifying the java

I'm trying to keep my code as minimal as possible and ideally would like to add stuff into the Mybatis Mapper

I tried things like

 #{isFriendly,jdbcType=Boolean}

but it didn't work

Body:
create handler and add it in Mybatis configuration
create handler:

    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.MappedJdbcTypes;
    import org.apache.ibatis.type.MappedTypes;

    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;

    @MappedTypes(Boolean.class)
    @MappedJdbcTypes(JdbcType.CHAR)
    public class BooleanStringTypeHandler extends BaseTypeHandler {

        @Override
        public void setNonNullParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
            preparedStatement.setString(i, aBoolean ? "Y" : "N");
        }
        @Override
        public Boolean getNullableResult(ResultSet resultSet, String s) throws SQLException {
            return getBoolean(resultSet.getString(s));
        }
        @Override
        public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
            return getBoolean(resultSet.getString(i));
        }
        @Override
        public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
            return getBoolean(callableStatement.getString(i));
        }
        private Boolean getBoolean(String s) {
            return "Y".equalsIgnoreCase(s);
        }
    }

add it in your Mybatis configuration:

<typeHandlers>
    <typeHandler jdbcType="CHAR" javaType="java.lang.Boolean" handler="crm.data.trade.utils.BooleanStringTypeHandler"/>
</typeHandlers>


问:
Python string join performance
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

```<code>import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t
</code>```

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697
```

Shouldn't it be exactly the other way around?

答:
The advice is about concatenating a lot of strings.

To compute s = s1 + s2 + ... + sn,

using +. A new string s1+s2 is created, then a new string s1+s2+s3 is created,..., etc, so a lot of memory allocation and copy operations is involved. In fact, s1 is copied n-1 times, s2 is copied n-2 time, ..., etc.

using "".join([s1, s2, ..., sn]). The concatenation is done in one pass, and each char in the strings is copied only once.

In your code, join is called on each iteration, so it's just like using +. The correct way is collect the items in an array, then call join on it.

OwnerDisplayName: Danny

Title: Python string join performance

Body:
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697

Shouldn't it be exactly the other way around?

LastEditorDisplayName: Danny


问:
Button's text not change on RecyclerView
I have a code for RecyclerView where I added 3 buttons one of them is Shortlist button. When I am clicking on button, success is coming from server on volley response. I need when I clicked on button then button's text should be changed and another's item will not be effected.

Below is my CardAdapter class where I extends RecyclerView.Adapter

```<code>public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    //   holder.btnShortlist.setText(superHero.getShortlist());
    //   holder.btnEI.setText(superHero.getExpress_Intrest());

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
    });

    str = superHero.getShortlist();
    Log.e("sh____________",str);

    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

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

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void shortlist(final int position) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setShortlist("Shortlisted");
                    holder.btnShortlist.setText(superHero.getShortlist());
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY, matri_id_by);
                params.put(KEY_MATRI_ID_TO, matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
      }
     }
    }
</code>```

答:
The easy way of doing this will be to pass the reference on the view you want to change.

```<code> holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        holder.btnShortlist.setText("Wait...");
        matri_id_to = superHero.getMglId();
        shortlist( holder.btnShortlist,position); // change this line

    }
});
</code>```

And then in your response you can do this.

```<code> public void shortlist(final Button button , final int position) { // Pass button as param
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
               button.setText("ShortListed"); // finally set your text
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY,matri_id_by);
            params.put(KEY_MATRI_ID_TO,matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}
</code>```

EDIT:

you have to move your onClickListener in your ViewHolder.

```<code> public ViewHolder(final View itemView) {
    super(itemView);
    imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
    textViewId = (TextView) itemView.findViewById(R.id.textViewId);
    AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
    Community = (TextView) itemView.findViewById(R.id.Community);
    Occupation = (TextView) itemView.findViewById(R.id.Occupation);
    Income = (TextView) itemView.findViewById(R.id.Income);
    btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
    btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        btnShortlist.setText("Wait...");
        matri_id_to = superHeroes.get(getAdapterPosition()).getMglId();
        shortlist(btnShortlist,position); // change this line

    }
});

}
</code>```

Body:
I have a code for RecyclerView where I added 3 buttons one of them is Shortlist button. When I am clicking on button, success is coming from server on volley response. I need when I clicked on button then button's text should be changed and another's item will not be effected.

Below is my CardAdapter class where I extends RecyclerView.Adapter

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private static final String url ="http://192.168.2.110/xp/shortlist1.php";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    // Session class instance
    session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
    final SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    //   holder.btnShortlist.setText(superHero.getShortlist());
    //   holder.btnEI.setText(superHero.getExpress_Intrest());

    holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            superHero.setShortlist("Wait...");
            holder.btnShortlist.setText(superHero.getShortlist());
            matri_id_to = superHero.getMglId();
            holder.shortlist(position);
        }
    });

    str = superHero.getShortlist();
    Log.e("sh____________",str);

    if(str.toString().equalsIgnoreCase("shortlisted")) {
        holder.btnShortlist.setText(str);
        holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
        holder.btnShortlist.setEnabled(false);
    }
    else{
        holder.btnShortlist.setText(str);
    }

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });

    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

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

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public Button btnShortlist;
    public Button btnViewProfile;
    public Button btnEI;

    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }

    public void shortlist(final int position) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setShortlist("Shortlisted");
                    holder.btnShortlist.setText(superHero.getShortlist());
                    notifyDataSetChanged();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_MATRI_ID_BY, matri_id_by);
                params.put(KEY_MATRI_ID_TO, matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest);
      }
     }
    }

Body:
The easy way of doing this will be to pass the reference on the view you want to change.

 holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        holder.btnShortlist.setText("Wait...");
        matri_id_to = superHero.getMglId();
        shortlist( holder.btnShortlist,position); // change this line

    }
});

And then in your response you can do this.

 public void shortlist(final Button button , final int position) { // Pass button as param
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equalsIgnoreCase("success")) {
                // If response is success then button's text should be changed i.e "Shortlisted"
               button.setText("ShortListed"); // finally set your text
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY,matri_id_by);
            params.put(KEY_MATRI_ID_TO,matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);
}

EDIT:

you have to move your onClickListener in your ViewHolder.

 public ViewHolder(final View itemView) {
    super(itemView);
    imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
    textViewId = (TextView) itemView.findViewById(R.id.textViewId);
    AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
    Community = (TextView) itemView.findViewById(R.id.Community);
    Occupation = (TextView) itemView.findViewById(R.id.Occupation);
    Income = (TextView) itemView.findViewById(R.id.Income);
    btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
    btnShortlist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        btnShortlist.setText("Wait...");
        matri_id_to = superHeroes.get(getAdapterPosition()).getMglId();
        shortlist(btnShortlist,position); // change this line

    }
});

}