问:
Xdebug and PhpStorm remote does not work
Is there a possibility to check if the web server is sending something to Chrome?

I have setting up PhpStorm and the web server in the same way, I have read in 1000 tutorials, but my PhpStorm doesn't receive anything from chrome.

Here are some settings:

php.ini

```<code>zend_extension="/usr/lib/php/20160303/xdebug.so"
xdebug.coverage_enable=on
xdebug.default_enable=on
xdebug.profiler_enable=on
xdebug.profiler_output_dir="/tmp"
xdebug.remote_autostart=on
xdebug.remote_port=9001
xdebug.remote_enable = on
xdebug.remote_connect_back = on
xdebug.idekey=PHPSTORM
xdebug.remote_handler=dbgp
</code>```

I have disabled the firewall on the server. PhpStorm is listening on the port 9001.

Some ideas?

答:
The solution is very easy! The only thing I forgot was the ssh tunnel to my remote server from my local machine.

Here an example running config:

```<code>[xdebug]
zend_extension="/usr/lib/php/20160303/xdebug.so"
xdebug.remote_autostart=on
xdebug.remote_host=localhost
xdebug.remote_port=9001
xdebug.remote_enable = on
xdebug.idekey=PHPSTORM
</code>```

Use as chrome plugin the XDebug Helper
https://chrome.google.com/webstore/detail/xdebug-helper/eadndfjplgieldjbigjakmdgkmoaaaoc

And as last step create an ssh tunnel to the remote server:

```<code>ssh -R 9001:localhost:9001 user@dev.server.com -N
</code>```

Body:
Is there a possibility to check if the web server is sending something to Chrome?

I have setting up PhpStorm and the web server in the same way, I have read in 1000 tutorials, but my PhpStorm doesn't receive anything from chrome.

Here are some settings:

php.ini

zend_extension="/usr/lib/php/20160303/xdebug.so"
xdebug.coverage_enable=on
xdebug.default_enable=on
xdebug.profiler_enable=on
xdebug.profiler_output_dir="/tmp"
xdebug.remote_autostart=on
xdebug.remote_port=9001
xdebug.remote_enable = on
xdebug.remote_connect_back = on
xdebug.idekey=PHPSTORM
xdebug.remote_handler=dbgp

I have disabled the firewall on the server. PhpStorm is listening on the port 9001.

Some ideas?

Body:
The solution is very easy! The only thing I forgot was the ssh tunnel to my remote server from my local machine.

Here an example running config:

[xdebug]
zend_extension="/usr/lib/php/20160303/xdebug.so"
xdebug.remote_autostart=on
xdebug.remote_host=localhost
xdebug.remote_port=9001
xdebug.remote_enable = on
xdebug.idekey=PHPSTORM

Use as chrome plugin the XDebug Helper
https://chrome.google.com/webstore/detail/xdebug-helper/eadndfjplgieldjbigjakmdgkmoaaaoc

And as last step create an ssh tunnel to the remote server:

ssh -R 9001:localhost:9001 user@dev.server.com -N


来源: stackexchange

问:
JMeter (for Load Test) set duration 1 hr But terminated before 1 hr
Help me pls,
Jmeter terminated before 1 hr(set duration)
I run Jmeter Test Plan that it should be run amount 1 hours.</p>

答:
Kindly inspect your Thread Group configuration, my expectation is that you simply don't provide enough loops, it should be something like:

Action to be taken after a Sampler error: Continue

Number of Threads: according to your test scenario

Ramp-Up Period: according to your test scenario

Loop Count: -1 (or tick "Forever")

Tick "Scheduler"

Put 3600 in Duration

Your test scenario might still end preliminary due to i.e. a Logic Controller or CSV Data Set Config reaching the end of data file, if your test won't be working as expected please update your question with the test plan snapshot and jmeter.log file contents.

ContentLicense: CC BY-SA 3.0


问:
pandas append duplicates as columns
I have a df that looks like this

```<code>         ID       data1     data2
 index
 1       1        3         4
 2       1        2         5
 3       2        9         3
 4       3        7         2
 5       3        4         7
 6       1        10        12
</code>```

What I'm trying to do is append as columns all the lines that have the same ID, so that I'd get something like this

```<code>         ID       data2     data3    data4    data5    data6     data7
 index
 1       1        3         4        2        5        10        12
 3       2        9         3
 4       3        7         2        4        7
</code>```

The problem is that I don't know how many columns I will have to append.
The column. Note that ID is NOT an index but a normal column, but the one that is used to find the duplicates.
I have already tried with pd.concat(), but had no luck.

答:
You can use cumcount for count duplicates with set_index + unstack for reshaping. Then convert MultiIndex to columns by map and last reset_index for column ID from index.

```<code>df['g'] = df.groupby('ID').cumcount().astype(str)
df = df.set_index(['ID','g']).unstack().sort_index(axis=1, level=1)
df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
   ID  data1_0  data2_0  data1_1  data2_1  data1_2  data2_2
0   1      3.0      4.0      2.0      5.0     10.0     12.0
1   2      9.0      3.0      NaN      NaN      NaN      NaN
2   3      7.0      2.0      4.0      7.0      NaN      NaN
</code>```

Solution with pivot:

```<code>df['g'] = df.groupby('ID').cumcount().astype(str)
df = df.pivot(index='ID',columns='g').sort_index(axis=1, level=1)
df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
   ID  data1_0  data2_0  data1_1  data2_1  data1_2  data2_2
0   1      3.0      4.0      2.0      5.0     10.0     12.0
1   2      9.0      3.0      NaN      NaN      NaN      NaN
2   3      7.0      2.0      4.0      7.0      NaN      NaN
</code>```

Another solution with apply and DataFrame constructor:

```<code>df = df.groupby('ID')['data1','data2']
       .apply(lambda x: pd.DataFrame(x.values, columns=['a','b']))
       .unstack()
       .sort_index(axis=1, level=1)
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
df = df.reset_index()
print (df)
   ID  a_0  b_0  a_1  b_1   a_2   b_2
0   1  3.0  4.0  2.0  5.0  10.0  12.0
1   2  9.0  3.0  NaN  NaN   NaN   NaN
2   3  7.0  2.0  4.0  7.0   NaN   NaN
</code>```

Title: pandas append duplicates as columns

Body:
I have a df that looks like this

         ID       data1     data2
 index
 1       1        3         4
 2       1        2         5
 3       2        9         3
 4       3        7         2
 5       3        4         7
 6       1        10        12

What I'm trying to do is append as columns all the lines that have the same ID, so that I'd get something like this

         ID       data2     data3    data4    data5    data6     data7
 index
 1       1        3         4        2        5        10        12
 3       2        9         3
 4       3        7         2        4        7

The problem is that I don't know how many columns I will have to append.
The column. Note that ID is NOT an index but a normal column, but the one that is used to find the duplicates.
I have already tried with pd.concat(), but had no luck.

Body:
You can use cumcount for count duplicates with set_index + unstack for reshaping. Then convert MultiIndex to columns by map and last reset_index for column ID from index.

df['g'] = df.groupby('ID').cumcount().astype(str)
df = df.set_index(['ID','g']).unstack().sort_index(axis=1, level=1)
df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
   ID  data1_0  data2_0  data1_1  data2_1  data1_2  data2_2
0   1      3.0      4.0      2.0      5.0     10.0     12.0
1   2      9.0      3.0      NaN      NaN      NaN      NaN
2   3      7.0      2.0      4.0      7.0      NaN      NaN

Solution with pivot:

df['g'] = df.groupby('ID').cumcount().astype(str)
df = df.pivot(index='ID',columns='g').sort_index(axis=1, level=1)
df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
   ID  data1_0  data2_0  data1_1  data2_1  data1_2  data2_2
0   1      3.0      4.0      2.0      5.0     10.0     12.0
1   2      9.0      3.0      NaN      NaN      NaN      NaN
2   3      7.0      2.0      4.0      7.0      NaN      NaN

Another solution with apply and DataFrame constructor:

df = df.groupby('ID')['data1','data2']
       .apply(lambda x: pd.DataFrame(x.values, columns=['a','b']))
       .unstack()
       .sort_index(axis=1, level=1)
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
df = df.reset_index()
print (df)
   ID  a_0  b_0  a_1  b_1   a_2   b_2
0   1  3.0  4.0  2.0  5.0  10.0  12.0
1   2  9.0  3.0  NaN  NaN   NaN   NaN
2   3  7.0  2.0  4.0  7.0   NaN   NaN


问:
how to make a dynamic xml using java
I have a fixed template of XML and the nodes may increase as per the data.
If I have a fixed template. How to iterate all the child nodes when the parent node name is being supplied?
Can I make a XML based on the xpath?

I have the follwoing code:-

```<code>Map map = hm();
            Set set = map.entrySet();
            // Get an iterator
            Iterator it = set.iterator();
            // Display elements
            while(it.hasNext()) {
                Map.Entry me = (Map.Entry)it.next();
                if (check) {
                    xpath_String+= "|"+me.getKey();
                }else {
                    xpath_String+= me.getKey();
                    check = true;
                }
            }

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        //xml file name acts as template
        Document doc = builder.parse("template.xml");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(xpath_String);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        System.out.println("Total number of tokens: "+nodes.getLength());
        //for (int i = 0; i < nodes.getLength(); i++) {

        int i=0;

        StringTokenizer st = new StringTokenizer(xpath_String,"|");

        while (st.hasMoreElements()) {
            String val = (String) st.nextElement();
            if(hm().containsKey(val)){
                System.out.println("Node value is: "+nodes.item(i).getNodeName());
                nodes.item(i).setTextContent(hm().get(val).toString());
                i++;
            }
        }
        //}

        //write the content into xml file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         // generating the output file name
         StreamResult finalResult =  new StreamResult(new File("newfxml.xml"));
         transformer.transform(source, finalResult);

         //making a string for the dom
         StringWriter writer = new StringWriter();
         StreamResult stResult = new StreamResult(writer);
         transformer.transform(source, stResult);
</code>```

Here I have a fixed template and I a map. from the map I am getting the xpath and its corresponding values. This hold only good until none of the nodes in the template xml repeats itself. So i was wondering if There is any way I can iterate the whole chunk of xml node when I get a repeatable component.
Is there any solution like this ?
Or I need to change way I m intending to proceed??

答:
If you want to enumerate all the children of a node, you just need to get your parent node with something like 'Element parent = root.getChild("parentNodeName")' then you can enumerate the children with the same methode 'List children = parent.getChildren("childName")'.

```<code>    Document doc = null;
    SAXBuilder sxb = new SAXBuilder();
    try {
        doc = sxb.build(new File(MyXmlFilePath));
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();
    List<Element> nodes = root.getChildren("myNode");
    Iterator<Element> it = nodes.iterator();
    while(it.hasNext())
    {
        Element currentNode = it.next();
        // node treatment here
    }
</code>```

Anhuin.

Title: how to make a dynamic xml using java

Body:
I have a fixed template of XML and the nodes may increase as per the data.
If I have a fixed template. How to iterate all the child nodes when the parent node name is being supplied?
Can I make a XML based on the xpath?

I have the follwoing code:-

Map map = hm();
            Set set = map.entrySet();
            // Get an iterator
            Iterator it = set.iterator();
            // Display elements
            while(it.hasNext()) {
                Map.Entry me = (Map.Entry)it.next();
                if (check) {
                    xpath_String+= "|"+me.getKey();
                }else {
                    xpath_String+= me.getKey();
                    check = true;
                }
            }

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        //xml file name acts as template
        Document doc = builder.parse("template.xml");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(xpath_String);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        System.out.println("Total number of tokens: "+nodes.getLength());
        //for (int i = 0; i < nodes.getLength(); i++) {

        int i=0;

        StringTokenizer st = new StringTokenizer(xpath_String,"|");

        while (st.hasMoreElements()) {
            String val = (String) st.nextElement();
            if(hm().containsKey(val)){
                System.out.println("Node value is: "+nodes.item(i).getNodeName());
                nodes.item(i).setTextContent(hm().get(val).toString());
                i++;
            }
        }
        //}

        //write the content into xml file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         // generating the output file name
         StreamResult finalResult =  new StreamResult(new File("newfxml.xml"));
         transformer.transform(source, finalResult);

         //making a string for the dom
         StringWriter writer = new StringWriter();
         StreamResult stResult = new StreamResult(writer);
         transformer.transform(source, stResult);

Here I have a fixed template and I a map. from the map I am getting the xpath and its corresponding values. This hold only good until none of the nodes in the template xml repeats itself. So i was wondering if There is any way I can iterate the whole chunk of xml node when I get a repeatable component.
Is there any solution like this ?
Or I need to change way I m intending to proceed??

Body:
If you want to enumerate all the children of a node, you just need to get your parent node with something like 'Element parent = root.getChild("parentNodeName")' then you can enumerate the children with the same methode 'List children = parent.getChildren("childName")'.

    Document doc = null;
    SAXBuilder sxb = new SAXBuilder();
    try {
        doc = sxb.build(new File(MyXmlFilePath));
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();
    List<Element> nodes = root.getChildren("myNode");
    Iterator<Element> it = nodes.iterator();
    while(it.hasNext())
    {
        Element currentNode = it.next();
        // node treatment here
    }

Anhuin.

ContentLicense: CC BY-SA 2.5


问:
Wordpress - Assign the value return by do_shorcode() to a variable
I am using IP2Location Tags plugin to get user's location by using IP address. I want to assign the value returned by do_shorcode() to a PHP variable. I've tried this code:

```<code><?php
$region = do_shortcode('{ip:regionName}');
echo ord($region);
?>
</code>```

and used ord() to print ASCII value.
echo ord($region); return ASCII value 123 (i.e. { ). After getting the ASCII value of each character in $region I came to know that $region contains value {ip:regionName}, but on using echo $region; It prints Maharashtra.

So my question is how to get Maharashtra as a value in $region;, which will help me to compare strings.

答:
Since this plugin replaces the keywords using filter, do_shortcode does nothing at all. I'm surprised you will get Maharashtra by echoing $region though but if you echo it within the_content, the filter will probably be applied.

To get the location, you can just invoke the class from the plugin and calling the necessary function like so.

```<code><?php
    $ip2l = new IP2LocationTags();
    $ip2l_location = $ip2l->get_location($_SERVER['REMOTE_ADDR']);
    $region = $ip2l_location['regionName'];
?>
</code>```

$region will be the regionName.

$ip2l_location will contain the entire location value including countryCode, countryName etc. and they are stored in an associative array.

Body:
I am using IP2Location Tags plugin to get user's location by using IP address. I want to assign the value returned by do_shorcode() to a PHP variable. I've tried this code:

<?php
$region = do_shortcode('{ip:regionName}');
echo ord($region);
?>

and used ord() to print ASCII value.
echo ord($region); return ASCII value 123 (i.e. { ). After getting the ASCII value of each character in $region I came to know that $region contains value {ip:regionName}, but on using echo $region; It prints Maharashtra.

So my question is how to get Maharashtra as a value in $region;, which will help me to compare strings.

Body:
Since this plugin replaces the keywords using filter, do_shortcode does nothing at all. I'm surprised you will get Maharashtra by echoing $region though but if you echo it within the_content, the filter will probably be applied.

To get the location, you can just invoke the class from the plugin and calling the necessary function like so.

<?php
    $ip2l = new IP2LocationTags();
    $ip2l_location = $ip2l->get_location($_SERVER['REMOTE_ADDR']);
    $region = $ip2l_location['regionName'];
?>

$region will be the regionName.

$ip2l_location will contain the entire location value including countryCode, countryName etc. and they are stored in an associative array.


问:
JAXB & JPA. One to one bidirectional relationship (empty id)
I am using JAXB and JPA. I would like to convert data from a xml file to a database. Below are 2 examples class. When I'm unmarshalling file into java object and when i persist data i have problem with user_id in addres entity (is empty);

When i set it manualy everything is alright, but problem is while unmarshall.

Class User

```<code>@XmlRootElement(name = "User")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity(name = "EntUser")
public class User implements Serializable {

@XmlTransient
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

@Column
private String name;

@Column
private String surname;

@XmlElement(name = "Address")
@OneToOne(mappedBy = "User", cascade = CascadeType.ALL)
private Address address;

public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    address.setUser(this);
    this.address = address;
}
</code>```

Class Address

```<code>@XmlRootElement(name = "Address")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity(name = "EntAddress")
public class Address implements Serializable {

@XmlTransient
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

@XmlTransient
@XmlInverseReference(mappedBy = "address")
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}
</code>```

When i create object manually everything is ok

```<code>User user = new User();
user.setName("Jack");
user.setSurname("AAA");

Address address = new Address();
user.setAddress(address);

em.persist(user);
</code>```

but during unmarshall not

```<code>StringReader reader = new StringReader(xml);
JAXBContext contex = JAXBContext.newInstance(User.class);
Unmarshaller unmarshaler = contex.createUnmarshaller();

User user = (User) unmarshaler.unmarshal(reader);

em.persist(user);
</code>```

except when i use this

```<code>user.getAddress().setUser(user);
</code>```

then is ok. How can i do without this? Because my xml is more complex.

Thanks a lot.

答:
JAXB offers mechanisms for pre-processing and post-processing.
After unmarshal you have to set the user in the Address class. To do this add the following callback method to the Address class:

```<code>public void afterUnmarshal(final Unmarshaller u, final Object parent) {
    this.setUser((User)parent);
}
</code>```

Import the abstract class Listener

```<code>import javax.xml.bind.Unmarshaller.Listener;
</code>```

This method is invoked after all the properties (except IDREF) are unmarshalled for this object, but before this object is set to the parent object.
For more information see:
here

Body:
I am using JAXB and JPA. I would like to convert data from a xml file to a database. Below are 2 examples class. When I'm unmarshalling file into java object and when i persist data i have problem with user_id in addres entity (is empty);

When i set it manualy everything is alright, but problem is while unmarshall.

Class User

@XmlRootElement(name = "User")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity(name = "EntUser")
public class User implements Serializable {

@XmlTransient
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

@Column
private String name;

@Column
private String surname;

@XmlElement(name = "Address")
@OneToOne(mappedBy = "User", cascade = CascadeType.ALL)
private Address address;

public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    address.setUser(this);
    this.address = address;
}

Class Address

@XmlRootElement(name = "Address")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity(name = "EntAddress")
public class Address implements Serializable {

@XmlTransient
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

@XmlTransient
@XmlInverseReference(mappedBy = "address")
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

When i create object manually everything is ok

User user = new User();
user.setName("Jack");
user.setSurname("AAA");

Address address = new Address();
user.setAddress(address);

em.persist(user);

but during unmarshall not

StringReader reader = new StringReader(xml);
JAXBContext contex = JAXBContext.newInstance(User.class);
Unmarshaller unmarshaler = contex.createUnmarshaller();

User user = (User) unmarshaler.unmarshal(reader);

em.persist(user);

except when i use this

user.getAddress().setUser(user);

then is ok. How can i do without this? Because my xml is more complex.

Thanks a lot.

Body:
JAXB offers mechanisms for pre-processing and post-processing.
After unmarshal you have to set the user in the Address class. To do this add the following callback method to the Address class:

public void afterUnmarshal(final Unmarshaller u, final Object parent) {
    this.setUser((User)parent);
}

Import the abstract class Listener

import javax.xml.bind.Unmarshaller.Listener;

This method is invoked after all the properties (except IDREF) are unmarshalled for this object, but before this object is set to the parent object.
For more information see:
here


问:
how to scale to fit the background image objective c
I am trying to set the image without any uiimageview,now I have the image but it is repeated horizontally twice I want to scale and fix it to screen size how do u do that??

I have tried some methods but nothing worked out

below is my code:

```<code>- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"background_themee.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// self.view.backgroundColor = [UIColor colorWithPatternImage:image];
// UIGraphicsBeginImageContext(self.view.frame.size);
// [[UIImage imageNamed:@"background_themee.png"]   drawInRect:self.view.bounds];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"background_themee"]];
 // Do any additional setup after loading the view.
}
</code>```

thanks in advance for your suggestions!!

答:
colorWithPattern will always repeat the image over the view. If you open in iPhone, it maybe appear 2 times image. And if you run on iPad, there might show 4 image. So it is not good for background image.

What you need is a UIImageView with contraints properly set and contentMode set to AspectFill.

Body:
I am trying to set the image without any uiimageview,now I have the image but it is repeated horizontally twice I want to scale and fix it to screen size how do u do that??

I have tried some methods but nothing worked out

below is my code:

- (void)viewDidLoad {
[super viewDidLoad];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"background_themee.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// self.view.backgroundColor = [UIColor colorWithPatternImage:image];
// UIGraphicsBeginImageContext(self.view.frame.size);
// [[UIImage imageNamed:@"background_themee.png"]   drawInRect:self.view.bounds];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
 self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"background_themee"]];
 // Do any additional setup after loading the view.
}

thanks in advance for your suggestions!!


问:
ng-repeat generates blank rows in the table
I am trying to create a single page application using angularjs, MVC and web-API. I am using "ng-repeat" to display all the records in a table, but it is generating blank rows. No of blank rows are equal to the no of records in the database. API is working fine. Also when I print the $scope.Students variable I can see the data in console.

Index page

```<code><script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/MyScripts/script.js"></script>

<h2>Home Page</h2>

<body ng-app="appModule">
    <div>
        <br />
        <a href="/#!/display">Read</a>
        <a href="/#!/create">Create</a>
        <a href="/#!/delete">Delete</a>
        <br />
        <ng-view></ng-view>
        <br />
    </div>
</body>
</code>```

html for display

```<code><br />
{{message}}
<br /><br />
<table border="1">
    <thead>
        <tr>
            <td>
                ID
            </td>
            <td>
                Name
            </td>
            <td>
                City
            </td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="Student in Students">
            <td>
                {{ Student.StudentID }}
            </td>
            <td>
                {{ Student.Name }}
            </td>
            <td>
                {{ Student.City }}
            </td>
            <td>
                <input type="button" value="Edit" ng-click="" />
            </td>
            <td>
                <input type="button" value="Delete" ng-click="" />
            </td>
        </tr>
    </tbody>
</table>
<br /><br />
{{ errorMessage }}
</code>```

Angular controller

```<code>.controller("DisplayController", function ($scope, appService) {
                $scope.message = "Display Page";

                getAll();
                //method to call angular service
                function getAll() {
                    //service call
                    var serviceCall = appService.getStudents();
                    serviceCall.then(function (response) {
                        //store response data to scope variable
                        $scope.Students = response.data;
                        console.log($scope.Students)
                    },
                    function (error) {
                        $scope.errorMessage = error;
                    })
                }
            })
</code>```

View Page

答:
It's case sensitive ,according to your data , it should be,</p>

```<code> <td>
  {{ Student.studentID }}
 </td>
 <td>
  {{ Student.name }}
 </td>
 <td>
   {{ Student.city }}
  </td>
</code>```

Body:
I am trying to create a single page application using angularjs, MVC and web-API. I am using "ng-repeat" to display all the records in a table, but it is generating blank rows. No of blank rows are equal to the no of records in the database. API is working fine. Also when I print the $scope.Students variable I can see the data in console.

Index page

Home Page

        Read
        Create
        Delete

        <ng-view></ng-view>

html for display

{{message}}

                ID

                Name

                City

                {{ Student.StudentID }}

                {{ Student.Name }}

                {{ Student.City }}

                <input type="button" value="Edit" ng-click="" />

                <input type="button" value="Delete" ng-click="" />

{{ errorMessage }}

Angular controller

.controller("DisplayController", function ($scope, appService) {
                $scope.message = "Display Page";

                getAll();
                //method to call angular service
                function getAll() {
                    //service call
                    var serviceCall = appService.getStudents();
                    serviceCall.then(function (response) {
                        //store response data to scope variable
                        $scope.Students = response.data;
                        console.log($scope.Students)
                    },
                    function (error) {
                        $scope.errorMessage = error;
                    })
                }
            })

View Page

Body:
It's case sensitive ,according to your data , it should be,

 <td>
  {{ Student.studentID }}
 </td>
 <td>
  {{ Student.name }}
 </td>
 <td>
   {{ Student.city }}
  </td>


问:
Splitting a string based on Pattern Java
Hi I have log files of the following pattern-

```<code>2014-03-06 03:21:45,432 ERROR [mfs:pool-3-thread-19] dispatcher.StatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
2014-03-06 03:22:06,454 ERROR [mfs:pool-3-thread-19] dispatcher.ClientStatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
2014-03-06 03:22:27,462 ERROR [pool-1-thread-1] cluster.ClusterServiceImpl  - unexpected error when trying to update LastCheckinTime
java.sql.SQLException: Network error IOException: Connection timed out: connect
...
</code>```

I am trying to split the string into substrings such that-

```<code>parsedString[0]=2014-03-06 03:21:45
parsedString[1]=,432 ERROR [mfs:pool-3-thread-19] dispatcher.StatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
parsedString[2]=2014-03-06 03:22:06
....
</code>```

I tried using string.split(datepattern) but it only gives me the content in the string array and not the dates.
I also tried using Pattern matcher but it only gives me a list of matching dates and not the content.

How do I get both values into the same string array.
Any help would be much appreciated.
Thanks

Edit-
     String pattern="([0-9]{4}-[0-1][0-9]-[0-3][0-9]\s(?:[0-1][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9],)";
     String parsedLogMessage[]=GetLogString().split(pattern);
     this.MessageContent=Arrays.asList(parsedLogMessage);

This only gives the string split by regex and not the regex string itself

答:
Suppose your string parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

```<code>import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}
</code>```

Here list result will have parameters n1_1,n2_2,n4_4.

Body:
Hi I have log files of the following pattern-

2014-03-06 03:21:45,432 ERROR [mfs:pool-3-thread-19] dispatcher.StatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
2014-03-06 03:22:06,454 ERROR [mfs:pool-3-thread-19] dispatcher.ClientStatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
2014-03-06 03:22:27,462 ERROR [pool-1-thread-1] cluster.ClusterServiceImpl  - unexpected error when trying to update LastCheckinTime
java.sql.SQLException: Network error IOException: Connection timed out: connect
...

I am trying to split the string into substrings such that-

parsedString[0]=2014-03-06 03:21:45
parsedString[1]=,432 ERROR [mfs:pool-3-thread-19] dispatcher.StatusNotification  - Error processing notification. Operation aborted.
java.sql.SQLException: Network error IOException: Connection timed out: connect
parsedString[2]=2014-03-06 03:22:06
....

I tried using string.split(datepattern) but it only gives me the content in the string array and not the dates.
I also tried using Pattern matcher but it only gives me a list of matching dates and not the content.

How do I get both values into the same string array.
Any help would be much appreciated.
Thanks

Edit-
     String pattern="([0-9]{4}-[0-1][0-9]-[0-3][0-9]\s(?:[0-1][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9],)";
     String parsedLogMessage[]=GetLogString().split(pattern);
     this.MessageContent=Arrays.asList(parsedLogMessage);

This only gives the string split by regex and not the regex string itself

Body:
Suppose your string parameters in between two special charaters like : #parameter# or parameter or even two differnt signs at a time like *paramter#. We can have list of all these parameters between those signs by this code :

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

public class Splitter {

    public static void main(String[] args) {

        String pattern1 = "#";
        String pattern2 = "#";
        String text = "(#n1_1#/#n2_2#)*2/#n1_1#*34/#n4_4#";

        Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
        Matcher m = p.matcher(text);
        while (m.find()) {
            ArrayList parameters = new ArrayList<>();
            parameters.add(m.group(1));
            System.out.println(parameters);
            ArrayList result = new ArrayList<>();
            result.add(parameters);
            // System.out.println(result.size());
        }

    }
}

Here list result will have parameters n1_1,n2_2,n4_4.


问:
Microsoft Security Advisory 4021279 System.BadImageFormatException
My application is an ASP.NET Core 1.0 Web API.

According to the Microsoft Security Advisory 4021279, I wanted to update the direct dependicies of my project.

In the MyClassName.csproj is the following line:

```<code><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3" />
</code>```

which I change to:

```<code><PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.4" />
</code>```

because the versions 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2 of Microsoft.AspNetCore.Mvc are not save to use.

If I then try to run the project, Iam getting the following errormessage:

System.BadImageFormatException: "Could not load file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)"

Inner Exception: BadImageFormatException: Cannot load a reference assembly for execution.

What am I doing wrong?

答:
So The post on Git says the following:

If after recompilation you see a Dependency conflict warning, you must update your other direct dependencies to the appropriate version.

For example if your project refers to Microsoft.AspNetCore.Routing with a version number of 1.0.1 when you update your Microsoft.AspNetCore.Mvc package to 1.0.4, compilation will throw:

NU1012 Dependency conflict. Microsoft.AspNetCore.Mvc.Core 1.0.4 expected Microsoft.AspNetCore.Routing >= 1.0.4 but received 1.0.1

As you can see in my question, I do not get this error message. However, I updated the version of Microsoft.AspNetCore.Routing to 1.0.4 and everything worked.

Body:
My application is an ASP.NET Core 1.0 Web API.

According to the Microsoft Security Advisory 4021279, I wanted to update the direct dependicies of my project.

In the MyClassName.csproj is the following line:

<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3" />

which I change to:

<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.4" />

because the versions 1.0.0, 1.0.1, 1.0.2, 1.0.3
1.1.0, 1.1.1, 1.1.2 of Microsoft.AspNetCore.Mvc are not save to use.

If I then try to run the project, Iam getting the following errormessage:

System.BadImageFormatException: "Could not load file or assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058)"

Inner Exception: BadImageFormatException: Cannot load a reference assembly for execution.

What am I doing wrong?


问:
Vue.js, Axios, JSon and no refresh
Sorry to post it, but I tried all solutions I found on the web. This seems to be a common problem but I just can't make it work. After a full day on it I give up. It must be a silly point, any vue.js guru will find the point in seconds. Any help will be appreciated.

The point : I receive some JSON and try to update my page with the received values, but the fields are null. jsonSettings.length is always 0.

I think I understand why: it's surely because the 'pointer' on the arrays doesn't change so vue.js doesn't detect the change of the content, or something similar, but I just can't make it work and it's driving me CRAZY.

My HTML :

```<code><!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        Typeof : {{ jsonSettings.typeof }} <BR>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>
</code>```

My JavaScript:

```<code>var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        // jsonSettings: [],
    },
    methods: {
        jsonSettings : function() {
            return (
                [
                    { id: 0, resume: 'test 0'},
                    { id: 1, resume: 'test 1'},
                    { id: 2, resume: 'test 2'}
                ]
            )
        },

        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(function (response) {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                    this.message = "getData - OK";

                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + jsonSettings.length + "]";

            jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})
</code>```

Sorry again, but I just can't make it work and I'm stuck in the middle of the river because of this silly point :-(

答:
For next readers, the => method provided by Bert is working like a charm, case closed.

I post here the complete working code for further use, I hope it will help you in your research.

The HTML code page :

```<code><!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        <ul>
            <li v-for="setting in jsonSettings">
                {{ setting.resume }}
            </li>
        </ul>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>
</code>```

the vue javascript :

```<code>var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        jsonSettings: []
    },
    methods: {
        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(response => {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + this.jsonSettings.length + "]";
            this.jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})
</code>```

For the server code -
don't forget to npm install --save axios and vue and add those lines in your router :

```<code>app.use('/js', express.static(__dirname + '/node_modules/vue/dist')); // redirect Vue.js
app.use('/js', express.static(__dirname + '/node_modules/axios/dist')); // redirect axios.js
</code>```

I want to be abble to use and develop without any externale links / library so I add the libs axios, vue (and boostrap) using npm and add a link using express to the proper modules location

so the server code :

```<code>var express = require('express');
var router = express.Router();

// don't forget to change yur dbuser username, password and database name
const sequelize = new Sequelize('postgres://dbuser:password@localhost:5432/database');

const Testing = sequelize.define('testing', {
    resume: Sequelize.TEXT,
    description: Sequelize.TEXT,
    state: Sequelize.BOOLEAN
});

router.get('/', function(req, res, next) {
    res.render('axios', { testings: null });
});

router.get('/LoadAxiosData', function(req, res, next) {
    Testing.findAll({
        order: [ [ 'state' ] ]
    })
        .then (function(testings)   {
            res.json(testings);
        })
        .catch(function(error) {
            console.log("### Error ###" + error);
            res.send(null);
        });
});

// to create database structure - portgresql
router.get('/init', function (req, res, next) {
    Testing.sync ({force:true});
    res.redirect('/');
});

module.exports = router;
</code>```

Title: Vue.js, Axios, JSon and no refresh

Body:
Sorry to post it, but I tried all solutions I found on the web. This seems to be a common problem but I just can't make it work. After a full day on it I give up. It must be a silly point, any vue.js guru will find the point in seconds. Any help will be appreciated.

The point : I receive some JSON and try to update my page with the received values, but the fields are null. jsonSettings.length is always 0.

I think I understand why: it's surely because the 'pointer' on the arrays doesn't change so vue.js doesn't detect the change of the content, or something similar, but I just can't make it work and it's driving me CRAZY.

My HTML :

<!DOCTYPE html>

    <title>List</title>

        Message : {{ message }}

        Length : {{ jsonSettings.length }}

        Typeof : {{ jsonSettings.typeof }}

        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>

My JavaScript:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        // jsonSettings: [],
    },
    methods: {
        jsonSettings : function() {
            return (
                [
                    { id: 0, resume: 'test 0'},
                    { id: 1, resume: 'test 1'},
                    { id: 2, resume: 'test 2'}
                ]
            )
        },

        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(function (response) {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                    this.message = "getData - OK";

                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + jsonSettings.length + "]";

            jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})

Sorry again, but I just can't make it work and I'm stuck in the middle of the river because of this silly point :-(

Body:
For next readers, the => method provided by Bert is working like a charm, case closed.

I post here the complete working code for further use, I hope it will help you in your research.

The HTML code page :

<!DOCTYPE html>
<html>
<head>
    <title>List</title>
    <script src="/js/vue.min.js"></script>
    <script src="/js/axios.js"></script>
</head>
<body>
    <div id="app">
        Message : {{ message }} <BR>
        Length : {{ jsonSettings.length }} <BR>
        <ul>
            <li v-for="setting in jsonSettings">
                {{ setting.resume }}
            </li>
        </ul>
        <button v-on:click="getData()">Load data</button>
        <button v-on:click="printData()">Print data</button>
    </div>
</body>
<script src="/javascripts/axios.js"></script>
</html>

the vue javascript :

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        jsonSettings: []
    },
    methods: {
        getData : function () {
            axios.get('/axios/LoadAxiosData')
                .then(response => {
                    this.jsonSettings = response.data;
                    this.message = "getData - I get objects : " + jsonSettings.length + " lines ";
                    this.$set('jsonSettings', response.data);
                })
                .catch(function (error) {
                    this.message = "getData - I get null";
                });
        },

        printData: function () {
            this.message =  "printData - jsonSettings.length  = [" + this.jsonSettings.length + "]";
            this.jsonSettings.map((item, i) => console.log('Index:', i, 'Id:', item.resume));

        }
    }
})

For the server code -
don't forget to npm install --save axios and vue and add those lines in your router :

app.use('/js', express.static(__dirname + '/node_modules/vue/dist')); // redirect Vue.js
app.use('/js', express.static(__dirname + '/node_modules/axios/dist')); // redirect axios.js

I want to be abble to use and develop without any externale links / library so I add the libs axios, vue (and boostrap) using npm and add a link using express to the proper modules location

so the server code :

var express = require('express');
var router = express.Router();

// don't forget to change yur dbuser username, password and database name
const sequelize = new Sequelize('postgres://dbuser:password@localhost:5432/database');

const Testing = sequelize.define('testing', {
    resume: Sequelize.TEXT,
    description: Sequelize.TEXT,
    state: Sequelize.BOOLEAN
});

router.get('/', function(req, res, next) {
    res.render('axios', { testings: null });
});

router.get('/LoadAxiosData', function(req, res, next) {
    Testing.findAll({
        order: [ [ 'state' ] ]
    })
        .then (function(testings)   {
            res.json(testings);
        })
        .catch(function(error) {
            console.log("### Error ###" + error);
            res.send(null);
        });
});

// to create database structure - portgresql
router.get('/init', function (req, res, next) {
    Testing.sync ({force:true});
    res.redirect('/');
});

module.exports = router;


问:
SSIS:File System Task 'Could not find file'
I am working on a SSIS project that download a file via web and upload the data in sql server then after that move the downloaded file to another folder. Here is an image for a clearer picture

I have a variable:
Source_Folder with a value:C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Dump
Success_Folder value: C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Success

For Each Loop values
    Expressions:@[User::Source_Folder] , Variable Mappings: User::FileName(which is blank string)

and here is my file system task

However I encounter this error message

Error: 0xC002F304 at Success, File System Task: An error occurred with the following error message: "Could not find file 'C:\Users\T-Aordiz\Documents\DumpDatas\Outbound Dump\Dump'.".
   Task failed: Success

I tried changing the expression in File System Task but also encountered an error. Help me guys

答:
In the file system task you must select variables containnig source filename and destination filename not folders.

Choose @[User::Filename] as source and choose the destination as another variable that contains the destination file path (not folder, must include file with extension)

You can generate destination value using script task or expression task. By concatenating the source filename (without path) + destination folder

Note that @[User::Filename] should be mapped in the Foreach Loop container


问:
Unable to fetch records when using between in date range in sql
When I use the following query in SQL, no records have been returned.

```<code>select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00')
</code>```

But when I single date instead of date range, it works fine. e.g.

```<code>select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate = '2017-06-06 00:00:00' )
</code>```

Can someone please help me out to solve this issue as I have to use a date range instead of a particular date.

答:
I think you are confused about the logic of your query:

```<code>select distinct e.No
from attendance a
inner join Employee e
    on a.EmployeeId = e.No
where e.No not in
(
    select EmployeeId from attendance
    where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00'
)
</code>```

If the subquery were to return every employee number in the Employee table, then you would get back no records from the query.  This is how WHERE NOT IN (...) behaves.  My guess is that the reason the single date query appears to be "working" is that no employee records match to that date, and hence your result set is not empty.

If you expect the opposite behavior, then perhaps you should change WHERE e.No NOT IN to WHERE e.No IN.

Body:
When I use the following query in SQL, no records have been returned.

select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00')

But when I single date instead of date range, it works fine. e.g.

select distinct e.No from attendance a
inner join Employee e on a.EmployeeId =e.No
where e.No not in (select EmployeeId from attendance where AttendanceDate = '2017-06-06 00:00:00' )

Can someone please help me out to solve this issue as I have to use a date range instead of a particular date.

Body:
I think you are confused about the logic of your query:

select distinct e.No
from attendance a
inner join Employee e
    on a.EmployeeId = e.No
where e.No not in
(
    select EmployeeId from attendance
    where AttendanceDate between '2017-05-26 00:00:00' and '2017-06-06 00:00:00'
)

If the subquery were to return every employee number in the Employee table, then you would get back no records from the query.  This is how WHERE NOT IN (...) behaves.  My guess is that the reason the single date query appears to be "working" is that no employee records match to that date, and hence your result set is not empty.

If you expect the opposite behavior, then perhaps you should change WHERE e.No NOT IN to WHERE e.No IN.


问:
How to remove a device /disk from zpool where there is no redundancy
I accidentally added a disk to a zpool the wrong way in the process of replacing a bad disk.  Now I can't remove the disk because it is listed as a device with no redundancy.  How do I remove da2?  Using zpool remove pdx-zfs-02 da2 doesn't work.  It returns "cannot remove da2: only inactive hot spares, cache, top-level, or log devices can be removed".  Zfs in freebsd/freenas doesn't allow the removal of devices that don't have redundancy.  There are not force options.  How can I work around this?</p>

```<code>NAME                                            STATE     READ WRITE CKSUM
pdx-zfs-02                                      DEGRADED     0     0     0
  raidz2-0                                      DEGRADED     0     0     0
    gptid/c459110a-a73c-1a49-b12c-f03fbec6eca6  FAULTED    158 25.3K     0  too many errors
    gptid/8c87e988-7832-1e44-9c45-abe95ee2d8f7  ONLINE       0     0     0
    gptid/3b4be4d0-136e-41e3-c546-d5c4ba2b3142  ONLINE       0     0     0
    gptid/209e8c9c-ff66-6f6a-e38b-9045c0b6c3ec  ONLINE       0     0     0
    gptid/ea8b834a-0692-464b-fd29-a877bf8f7bb9  ONLINE       0     0     0
    gptid/cf35d740-ea0b-bae6-9e4f-b7a31d66ab1d  ONLINE       0     0     0
    gptid/fe908e73-c93b-72ed-d4bb-9eae78bcc5b6  ONLINE       0     0     0
    gptid/bdf03e4d-ba71-a4cc-dd90-edfd6446bac3  ONLINE       0     0     0
    gptid/302bacc1-273a-54c9-c8f9-f458640b0d60  ONLINE       0     0     0
    gptid/d94ea326-d5aa-f062-9662-953908ce0b53  ONLINE       0     0     0
  raidz2-1                                      ONLINE       0     0     0
    gptid/3c1b1d3b-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/3ec0ba4a-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/40d8b781-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/43387eae-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/45800439-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/47df2694-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
  da2                                           ONLINE       0     0     0
</code>```

答: Unfortunately you need to destroy and recreate your pool. You can use zfs send and zfs receive to move the data to other disks and back without losing any ZFS-specific information, but you have to move it nevertheless.

Body:
I accidentally added a disk to a zpool the wrong way in the process of replacing a bad disk.  Now I can't remove the disk because it is listed as a device with no redundancy.  How do I remove da2?  Using zpool remove pdx-zfs-02 da2 doesn't work.  It returns "cannot remove da2: only inactive hot spares, cache, top-level, or log devices can be removed".  Zfs in freebsd/freenas doesn't allow the removal of devices that don't have redundancy.  There are not force options.  How can I work around this?

NAME                                            STATE     READ WRITE CKSUM
pdx-zfs-02                                      DEGRADED     0     0     0
  raidz2-0                                      DEGRADED     0     0     0
    gptid/c459110a-a73c-1a49-b12c-f03fbec6eca6  FAULTED    158 25.3K     0  too many errors
    gptid/8c87e988-7832-1e44-9c45-abe95ee2d8f7  ONLINE       0     0     0
    gptid/3b4be4d0-136e-41e3-c546-d5c4ba2b3142  ONLINE       0     0     0
    gptid/209e8c9c-ff66-6f6a-e38b-9045c0b6c3ec  ONLINE       0     0     0
    gptid/ea8b834a-0692-464b-fd29-a877bf8f7bb9  ONLINE       0     0     0
    gptid/cf35d740-ea0b-bae6-9e4f-b7a31d66ab1d  ONLINE       0     0     0
    gptid/fe908e73-c93b-72ed-d4bb-9eae78bcc5b6  ONLINE       0     0     0
    gptid/bdf03e4d-ba71-a4cc-dd90-edfd6446bac3  ONLINE       0     0     0
    gptid/302bacc1-273a-54c9-c8f9-f458640b0d60  ONLINE       0     0     0
    gptid/d94ea326-d5aa-f062-9662-953908ce0b53  ONLINE       0     0     0
  raidz2-1                                      ONLINE       0     0     0
    gptid/3c1b1d3b-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/3ec0ba4a-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/40d8b781-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/43387eae-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/45800439-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
    gptid/47df2694-3977-11e6-b1f0-0025902b035a  ONLINE       0     0     0
  da2                                           ONLINE       0     0     0


问:
Pseudo-element background image doesn't appear
I have a div element with a triangle-border and I'm trying to place an image above it using an ::after pseudo-element with background-image. The method doesn't work though. However if I'm trying to set content: "asd";, the text appears correctly. Basically I just want to have a house image above that triangle.

Here's the HTML code:

```<code><div id = "estatecorner" class = "house"></div>
</code>```

And here's the CSS:

```<code>#estatecorner {
  position: absolute;
  right: 0px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 80px 80px 0;
  border-color: transparent #67b2e4 transparent transparent;
}

#estatecorner.house::after {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(images/mini/house.png);
  content: " ";
}
</code>```

Here's a jsFiddle

答:
You need to give the height and width of the psuedo elements in px and not in %  for this case.

```<code>#estatecorner.house::after {
    position: absolute;
    width: 14px;
    height: 13px;
    background: url(http://i.imgur.com/nceI30v.png) no-repeat;
    content: " ";
    left: 50px;
    top: 20px;
}
</code>```

The reason is that #estatecorner have dimensions of 0 x 0. So, if you give 100%
height and width to its psuedo elements then their dimensions will eventually be 0 x 0 too which would be useless.

Body:
I have a div element with a triangle-border and I'm trying to place an image above it using an ::after pseudo-element with background-image. The method doesn't work though. However if I'm trying to set content: "asd";, the text appears correctly. Basically I just want to have a house image above that triangle.

Here's the HTML code:

And here's the CSS:

#estatecorner {
  position: absolute;
  right: 0px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 80px 80px 0;
  border-color: transparent #67b2e4 transparent transparent;
}

#estatecorner.house::after {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(images/mini/house.png);
  content: " ";
}

Here's a jsFiddle

Body:
You need to give the height and width of the psuedo elements in px and not in %  for this case.

#estatecorner.house::after {
    position: absolute;
    width: 14px;
    height: 13px;
    background: url(http://i.imgur.com/nceI30v.png) no-repeat;
    content: " ";
    left: 50px;
    top: 20px;
}

The reason is that #estatecorner have dimensions of 0 x 0. So, if you give 100%
height and width to its psuedo elements then their dimensions will eventually be 0 x 0 too which would be useless.


问:
How to check FCM Message status?
How do I receive an Acknowledgement with FCM that a message was received? I have a progressive web app that checks if a user has a fcm token saved in the db, and uses FCM if they do and resorts to SMS (through twilio) if they do not.  The problem is that ""Successfully sent fcm message" is logged even when the browser is closed, as messages are queued until the browser is reopened.

How can I tell that a message was actually received by the user, and isn't stuck waiting in a queue? If Chrome is closed, I want an SMS to send immediately.

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

const serviceAccount = require('./service-account.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`
});

function sendFCM(uid, title, body) {
  const payload = {
    notification: {
      title: title,
      body: body,
      click_action: "https://www.google.com"
    }
  };

  const payloadOptions = {
    timeToLive: 0
  };

  getUserDetails(uid).then((details) => {
    if (details.fcmToken !== undefined) {
      // send fcm message
      return admin.messaging().sendToDevice(details.fcmToken, payload, payloadOptions)
        .then(response => {
          console.log("Successfully sent fcm message");
        })
        .catch((err) => {
          console.log("Failed to send fcm message");
          return sendSMS(details.phone_number, body);
        });;
    } else {
      console.log("No fcm token found for uid", uid);
      return sendSMS(details.phone_number, body);
    }
  })
}
</code>```

答:
There is currently no API or a part of the response from FCM that tells you if a message is currently in queue or is already sent.

However, you could make use of Delivery Receipts (Note: Implementing delivery receipts requires an XMPP Connection Protocol).

Title: How to check FCM Message status?

Body:
How do I receive an Acknowledgement with FCM that a message was received? I have a progressive web app that checks if a user has a fcm token saved in the db, and uses FCM if they do and resorts to SMS (through twilio) if they do not.  The problem is that ""Successfully sent fcm message" is logged even when the browser is closed, as messages are queued until the browser is reopened.

How can I tell that a message was actually received by the user, and isn't stuck waiting in a queue? If Chrome is closed, I want an SMS to send immediately.

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const serviceAccount = require('./service-account.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`
});

function sendFCM(uid, title, body) {
  const payload = {
    notification: {
      title: title,
      body: body,
      click_action: "https://www.google.com"
    }
  };

  const payloadOptions = {
    timeToLive: 0
  };

  getUserDetails(uid).then((details) => {
    if (details.fcmToken !== undefined) {
      // send fcm message
      return admin.messaging().sendToDevice(details.fcmToken, payload, payloadOptions)
        .then(response => {
          console.log("Successfully sent fcm message");
        })
        .catch((err) => {
          console.log("Failed to send fcm message");
          return sendSMS(details.phone_number, body);
        });;
    } else {
      console.log("No fcm token found for uid", uid);
      return sendSMS(details.phone_number, body);
    }
  })
}


问:
Ask for user input on button click event in C#
I am making a chess game and I am using array of buttons dynamically so, I am using a single click event for all of them. I want to ask user for inputs on button's click event(where the user wants to put the piece once the button is clicked). How can I do that as I am new to C# and have tried a lot but couldn't figure it out.

Here's my code:

```<code>    private void Btn_Click(object sender, EventArgs e)
    {
        //for black pieces

        Button btn2 = new Button();
        btn2 = sender as Button;
        int k;
        int l;
        for (int i=0; i<8; i++)
        {
            for(int j=0; j<8; j++)
            {
                if (btn2.BackgroundImage == blackpawn)
                {
                    if (btn2 == btn[i, j])
                    {
                        //here i want to ask user where he wants to put the piece
                        btn[i, j].BackgroundImage = null;
                        k = ++i;
                        l = j;
                        btn[k, l].BackgroundImage = blackpawn;
                        btn[k, l].BackgroundImageLayout = ImageLayout.Stretch;

                    }
                }
            }
        }

    }
</code>```

答:
You don't have to do anything complicated, something like this will work</p>

```<code>bool firstClick = true;

private void Btn_Click(object sender, EventArgs e)
{
    if (firstClick)
    {
        // Do the stuff you'd like to do on the first click.

        firstClick = false; // Remember to set firstClick to false.
    }
    else
    {
        // Do the stuff you'd like to do on the second click.

        firstClick = true; // Remember to set firstClick to true.
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a chess game and I am using array of buttons dynamically so, I am using a single click event for all of them. I want to ask user for inputs on button's click event(where the user wants to put the piece once the button is clicked). How can I do that as I am new to C# and have tried a lot but couldn't figure it out.

Here's my code:

    private void Btn_Click(object sender, EventArgs e)
    {
        //for black pieces

        Button btn2 = new Button();
        btn2 = sender as Button;
        int k;
        int l;
        for (int i=0; i<8; i++)
        {
            for(int j=0; j<8; j++)
            {
                if (btn2.BackgroundImage == blackpawn)
                {
                    if (btn2 == btn[i, j])
                    {
                        //here i want to ask user where he wants to put the piece
                        btn[i, j].BackgroundImage = null;
                        k = ++i;
                        l = j;
                        btn[k, l].BackgroundImage = blackpawn;
                        btn[k, l].BackgroundImageLayout = ImageLayout.Stretch;

                    }
                }
            }
        }

    }

Body:
You don't have to do anything complicated, something like this will work

bool firstClick = true;

private void Btn_Click(object sender, EventArgs e)
{
    if (firstClick)
    {
        // Do the stuff you'd like to do on the first click.

        firstClick = false; // Remember to set firstClick to false.
    }
    else
    {
        // Do the stuff you'd like to do on the second click.

        firstClick = true; // Remember to set firstClick to true.
    }
}


问:
How to enter special characters like "&" in oracle database?
I want to insert special character & in my insert statement. My insert is:

```<code>INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');
</code>```

If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.

How can I enter special characters like & in the insert statement for oracle db?

Body:
I want to insert special character & in my insert statement. My insert is:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');

If I try to run this query I am getting a popup and it asks me to enter value for Oracle_14.

How can I enter special characters like & in the insert statement for oracle db?

Body: strAdd=strAdd.replace("&","'||'&'||'");


问:
how to run visual studio or nunit as administrator from teamcity
I am currently running my tests using teamcity. Gaving the following error

SetUp method failed. System.UnauthorizedAccessException : Retrieving the COM class factory for component with CLSID {0002DF01-0000-0000-C000-

Any idea how can I set it to run as administrator as I am using windows 7.

答:
I also use TeamCity and WatiN. Here is what I did to make sure TeamCity can run as Administrator, but not as Local System (because it is better to have a real user when you run IE).

Create a new user (for example "TeamCity")

Add this user to Administrator group

Open the service console window (http://media.techtarget.com/rms/misc/admintools7.jpg) and look for the teamcity agent: "Team City Build Agent Service"

Right click on it, and go to "log on" tab. Enter the newly created user

Hope this helps


问:
What is the simplest SQL Query to find the second largest value?
What is the simplest SQL query to find the second largest integer value in a specific column?

There are maybe duplicate values in the column.

答:
The easiest way to get second last row from a SQL table is to use ORDER BYColumnNameDESC and set LIMIT 1,1.

Try this:

```<code>SELECT * from `TableName` ORDER BY `ColumnName` DESC LIMIT 1,1
</code>```

OwnerDisplayName: Niyaz

Body:
The easiest way to get second last row from a SQL table is to use ORDER BYColumnNameDESC and set LIMIT 1,1.

Try this:

SELECT * from `TableName` ORDER BY `ColumnName` DESC LIMIT 1,1


问:
What is the proper way to re-attach detached objects in Hibernate?
I have a situation in which I need to re-attach detached objects to a hibernate session, although an object of the same identity MAY already exist in the session, which will cause errors.

Right now, I can do one of two things.

getHibernateTemplate().update( obj )
This works if and only if an object doesn't already exist in the hibernate session. Exceptions are thrown stating an object with the given identifier already exists in the session when I need it later.

getHibernateTemplate().merge( obj )
This works if and only if an object exists in the hibernate session. Exceptions are thrown when I need the object to be in a session later if I use this.

Given these two scenarios, how can I generically attach sessions to objects? I don't want to use exceptions to control the flow of this problem's solution, as there must be a more elegant solution...

答:
So it seems that there is no way to reattach a stale detached entity in JPA.

merge() will push the stale state to the DB,
and overwrite any intervening updates.

refresh() cannot be called on a detached entity.

lock() cannot be called on a detached entity,
and even if it could, and it did reattach the entity,
calling 'lock' with argument 'LockMode.NONE'
implying that you are locking, but not locking,
is the most counterintuitive piece of API design I've ever seen.

So you are stuck.
There's an detach() method, but no attach() or reattach().
An obvious step in the object lifecycle is not available to you.

Judging by the number of similar questions about JPA,
it seems that even if JPA does claim to have a coherent model,
it most certainly does not match the mental model of most programmers,
who have been cursed to waste many hours trying understand
how to get JPA to do the simplest things, and end up with cache
management code all over their applications.

It seems the only way to do it is discard your stale detached entity
and do a find query with the same id, that will hit the L2 or the DB.

Mik


问:
Register ansible variable to different name
I have a playbook where I'm running the local_action task (which overwrites the ansible_host variable with "localhost") but I want to access the data that was in the ansible_host variable prior to the local_action task running, during it.

This is what I've tried so far, but I get the error "'register' is not a valid option in debug"

playbook.yml

```<code>- debug:
    var: ansible_host
    register: run_host

- name: Install OBS
  local_action: command ssh ansibler@{{ run_host }} "sudo /home/ansibler/obs/bin/install.sh"
  become_user: bsmith
</code>```

The local_action task should ssh to localhost then run the ssh command given. The reason I'm doing it that way instead of just running the command task against the ansible_host is because I couldn't find any other workaround to make this particular script to work. It would hang indefinitely if I ran it with the command task.

Is there another way to achieve what I'm wanting to do?

答:
That's what the set_fact module is for:

```<code>- set_fact:
    run_host: "{{ ansible_host }}"
</code>```

Body:
I have a playbook where I'm running the local_action task (which overwrites the ansible_host variable with "localhost") but I want to access the data that was in the ansible_host variable prior to the local_action task running, during it.

This is what I've tried so far, but I get the error "'register' is not a valid option in debug"

playbook.yml

- debug:
    var: ansible_host
    register: run_host

- name: Install OBS
  local_action: command ssh ansibler@{{ run_host }} "sudo /home/ansibler/obs/bin/install.sh"
  become_user: bsmith

The local_action task should ssh to localhost then run the ssh command given. The reason I'm doing it that way instead of just running the command task against the ansible_host is because I couldn't find any other workaround to make this particular script to work. It would hang indefinitely if I ran it with the command task.

Is there another way to achieve what I'm wanting to do?

Body:
That's what the set_fact module is for:

- set_fact:
    run_host: "{{ ansible_host }}"


问:
source cantain no data row while using take asp.net
currently when the records are zero i am getting the error source
cantain no data row to manage that i have checked it count>0 but still
i am getting any idea how to solve this.

```<code>dynamic dt = ds.Tables(0);
int totalrowCount = dt.Rows.Count;

//dt.Rows.Count
//dt.Select().Take(100)
// dt.Rows.Cast(Of System.Data.DataRow)().Take(100)
DataTable dt1 = default(DataTable);
if (totalrowCount > 0) {
    dt1 = dt.AsEnumerable().Take(100).CopyToDataTable();
} else {
    dt1 = dt.AsEnumerable().CopyToDataTable();
}
</code>```

答:
As documented, CopyToDataTable() can't be called on an empty sequence of rows - presumably because then there's no schema information to include. Instead, if you know your original table is empty and you want a new table with the same schema, just clone it. So you'd have:

```<code>DataTable dt = ds.Tables(0);
DataTable newTable = dt.Rows.Count > 0
    ? dt.AsEnumerable().Take(100).CopyToDataTable()
    : dt.Clone();
</code>```

Body:
currently when the records are zero i am getting the error source
cantain no data row to manage that i have checked it count>0 but still
i am getting any idea how to solve this.

dynamic dt = ds.Tables(0);
int totalrowCount = dt.Rows.Count;

//dt.Rows.Count
//dt.Select().Take(100)
// dt.Rows.Cast(Of System.Data.DataRow)().Take(100)
DataTable dt1 = default(DataTable);
if (totalrowCount > 0) {
    dt1 = dt.AsEnumerable().Take(100).CopyToDataTable();
} else {
    dt1 = dt.AsEnumerable().CopyToDataTable();
}

Body:
As documented, CopyToDataTable() can't be called on an empty sequence of rows - presumably because then there's no schema information to include. Instead, if you know your original table is empty and you want a new table with the same schema, just clone it. So you'd have:

DataTable dt = ds.Tables(0);
DataTable newTable = dt.Rows.Count > 0
    ? dt.AsEnumerable().Take(100).CopyToDataTable()
    : dt.Clone();


问:
How to Accomplish a Where on a joined table with Entity Framework
I have the following 2 tables in my database:

```<code>[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)
</code>```

and:

```<code>[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)
</code>```

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

```<code>select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()
</code>```

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

```<code>var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );
</code>```

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.

答:
First, I'm not sure if it is wise to do the GetDate() inside your query, as an IQueryable I think it wouldn't work, and as an IEnumerable I'm not sure how many times it would be called during the enumeration.

You could first filter the Schedules you want to use and then do the join.

In small steps:

```<code>DateTime myDate = GetDate();
var oldSchedules = dbCntext.Schedules.Where(schedule => schedule.Time < myDate);

var requiredResult = dbContext.Patients  // join Patients
    .join(oldSchedules,                  // with the old schedules
    patient => patient.PatientID,        // from patients take PatientID
    schedule => schedule.PatientID<      // from old schedules that PatientID
    (patient, schedule) => new           // when they match, take the recods
    {                                    // to create a new Anonymous type
        NameFirst = patient.NameFirst,   // with the required properties
        NameLast = patient.NameLast,
        Dob = patient.Dob,
    });
</code>```

Of course you could put this in one statement (except for GetDate())

```<code>DateTime myDate = GetDate();
var result = dbContext.Schedules
    .Where(schedule => schedule.Time < myDate)
    .Join(dbContext.Patients,
    schedule => schedule.PatientId,
    patient => patient.PatientId,
    (schedule, patient) => new
    {
        ...
    });
</code>```

Body:
I have the following 2 tables in my database:

[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)

and:

[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.

Body:
First, I'm not sure if it is wise to do the GetDate() inside your query, as an IQueryable I think it wouldn't work, and as an IEnumerable I'm not sure how many times it would be called during the enumeration.

You could first filter the Schedules you want to use and then do the join.

In small steps:

DateTime myDate = GetDate();
var oldSchedules = dbCntext.Schedules.Where(schedule => schedule.Time < myDate);

var requiredResult = dbContext.Patients  // join Patients
    .join(oldSchedules,                  // with the old schedules
    patient => patient.PatientID,        // from patients take PatientID
    schedule => schedule.PatientID<      // from old schedules that PatientID
    (patient, schedule) => new           // when they match, take the recods
    {                                    // to create a new Anonymous type
        NameFirst = patient.NameFirst,   // with the required properties
        NameLast = patient.NameLast,
        Dob = patient.Dob,
    });

Of course you could put this in one statement (except for GetDate())

DateTime myDate = GetDate();
var result = dbContext.Schedules
    .Where(schedule => schedule.Time < myDate)
    .Join(dbContext.Patients,
    schedule => schedule.PatientId,
    patient => patient.PatientId,
    (schedule, patient) => new
    {
        ...
    });


问:
Multi-select add/remove select in jquery
In a form I've two multi-select. I can add items from select1 to select2 or remove items from select2 using the following jquery functions:

```<code><script  type="text/javascript">
   function addProject() {
      return !$('#select1 option:selected').remove().appendTo('#select2');
   }

   function removeProject() {
      return !$('#select2 option:selected').remove().appendTo('#select1');
   }
</script>

<select multiple id="select1" class="form-control">
@for(p <- projects) {
    option value="@p.getName">@p.getName</option>
}
</select>

<button type="button" class="btn btn-primary"  onclick="addProject();" >
   <span class='glyphicon glyphicon-plus'></span>
</button>
<button type="button" class="btn btn-primary"  onclick="removeProject();" >
   <span class='glyphicon glyphicon-minus'></span>
</button>

<select name="projects" multiple id="select2" class="form-control">
</select>
</code>```

The problem is that if I add items to select2 and submit the form I receive all values. If I add and remove items or vice-versa I don't receive values.

I tried to add another jquery function to select all items inside select2 before submit the form but didn't work.

```<code>function select_projects() {
    $('#select2').children('option').attr('selected', 'selected');
}
</code>```

How can solve the problem?

答:
I solved changing the select_projects() function like follow:</p>

```<code>function select_projects() {
    $('#select1 option:selected').attr('selected', false);
    $('#select2').children().prop('selected', true);
}
</code>```

Body:
In a form I've two multi-select. I can add items from select1 to select2 or remove items from select2 using the following jquery functions:

<select multiple id="select1" class="form-control">
@for(p <- projects) {
    option value="@p.getName">@p.getName</option>
}
</select>

<button type="button" class="btn btn-primary"  onclick="addProject();" >

</button>
<button type="button" class="btn btn-primary"  onclick="removeProject();" >

</button>

<select name="projects" multiple id="select2" class="form-control">
</select>

The problem is that if I add items to select2 and submit the form I receive all values. If I add and remove items or vice-versa I don't receive values.

I tried to add another jquery function to select all items inside select2 before submit the form but didn't work.

function select_projects() {
    $('#select2').children('option').attr('selected', 'selected');
}

How can solve the problem?

Body:
I solved changing the select_projects() function like follow:

function select_projects() {
    $('#select1 option:selected').attr('selected', false);
    $('#select2').children().prop('selected', true);
}