问:
PHP array search
I'm trying to add some quick and simple search functionality to a site. The site has an XML file with all their stores, and I want to create a search box to search for the closest store to the user by town or postcode.

I have put all the data into an array, but as far as I can tell, there is no way to 'search' an array (NOT array_search) to retrieve results like using a MySQL LIKE query.

Surely there must be a way? Using MySQL isn't an option in this case.

答: I think you're looking for something like LINQ but in a PHP environment. Unfortunately I don't know of any solution like this. Best solution I can see is a custom search with a foreach and your own search parameters. Or just store the information in SQL and avoid trying to emulate it.</p>

Title: PHP array search


来源: stackexchange

问:
Python - Write for loop output to file
I have a function that outputs a list of IPs.

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))
</code>```

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

```<code>172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51
</code>```

Now I want to write this output to file.

What I have done is

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()
</code>```

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

答:
Reassigning sys.stdout? That's... brave.

You can assign the open file to some other variable, then call its write method. If you want stuff on separate lines, you'll have to add those yourself.

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","w")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python - Write for loop output to file

Body:
I have a function that outputs a list of IPs.

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51

Now I want to write this output to file.

What I have done is

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

Body:
Reassigning sys.stdout? That's... brave.

You can assign the open file to some other variable, then call its write method. If you want stuff on separate lines, you'll have to add those yourself.

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    my_file=open("test.txt","w")
    for ips in ip:
        my_file.write(ips.get('ip')+'\n')
    my_file.close()


问:
How to initialize a new screen and go to it, while adding it to a table view in the background
I'm trying to go straight to a screen that is normally reached through tapping on a table view cell - Basically the user enters a page name on Screen A, and then is taken the table view, Screen B, where the name they entered is now the first and only cell in the table view. Then they tap on that cell to reach Screen C.

Now I want to cut Screen B out of the equation - I'll be embedding that table in a slide-out menu so I don't want it presented at all, I just want to update the table in the background.

This is my code so far, all on the setup page (Screen A):

This is the prepareForSegue, that's called when the user finishes signing up for the app and presses "done":

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "initChat") {
        let chatVc = segue.destination as! ChatViewController
        let roomVc = RoomsTableViewController()
                if let roomName = self.chatRoomNameTextField.text {

                    let newRoomRef = roomRef.childByAutoId()
                    let roomItem = [
                        "name": roomName
                    ]
                    newRoomRef.setValue(roomItem)

                    // Start participants list with current user
                    let participantsRef = newRoomRef.child("participants")
                    let newParticipantRef = participantsRef.childByAutoId()

                    if let uid = FIRAuth.auth()?.currentUser?.uid {
                        newParticipantRef.setValue(uid)
                    }
                }
                roomVc.senderDisplayName = "Joe"
    }
}
</code>```

And this is an observer for Firebase that is in charge of updating the table view once the user enters a name:

```<code>    private func observeRooms() {
        // Observe method to listen for new channels being written to Firebase
        let roomVc = RoomsTableViewController()

        roomVc.roomRefHandle = roomVc.roomRef.observe(.childAdded, with: { (snapshot) -> Void in
            let roomData = snapshot.value as! Dictionary<String, AnyObject>
            let id = snapshot.key

            if let uid = FIRAuth.auth()?.currentUser?.uid {
                if let name = roomData["name"] as! String!, name.characters.count > 0 {
                    roomVc.rooms.append(Room(id: id, name: name, participants: [uid]))
                    roomVc.tableView.reloadData()
                } else {
                    print("Error! Could not decode channel data")
                }
            }
        })
    }
</code>```

And this is the IBAction for the "done" button being pressed:

```<code>@IBAction func setupDoneButtonPressed(_ sender: Any) {

    setUserInfo()
    observeRooms()

    let room = rooms  // <-- This is where I need to indicate that I want to go to the first room in the table
    self.performSegue(withIdentifier: "initChat", sender: room)
}
</code>```

In this case I know that the screen I want to load will always be the very first cell in the table view, because at this point it will be the first cell created. But I don't know how to specify that without the index path in the table view's methods.

How can I do this?

答:
For update the table view use:

```<code>self.tableView.reloadData()
</code>```

What you have to do is: After the user enters the search value, and press the button, setupDoneButtonPressed() will be executed, after that, you have to set new data into a global variable. When data was set, you have to reload de tableview. I think this could help, let me know if you tried this.

Body:
I'm trying to go straight to a screen that is normally reached through tapping on a table view cell - Basically the user enters a page name on Screen A, and then is taken the table view, Screen B, where the name they entered is now the first and only cell in the table view. Then they tap on that cell to reach Screen C.

Now I want to cut Screen B out of the equation - I'll be embedding that table in a slide-out menu so I don't want it presented at all, I just want to update the table in the background.

This is my code so far, all on the setup page (Screen A):

This is the prepareForSegue, that's called when the user finishes signing up for the app and presses "done":

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if (segue.identifier == "initChat") {
        let chatVc = segue.destination as! ChatViewController
        let roomVc = RoomsTableViewController()
                if let roomName = self.chatRoomNameTextField.text {

                    let newRoomRef = roomRef.childByAutoId()
                    let roomItem = [
                        "name": roomName
                    ]
                    newRoomRef.setValue(roomItem)

                    // Start participants list with current user
                    let participantsRef = newRoomRef.child("participants")
                    let newParticipantRef = participantsRef.childByAutoId()

                    if let uid = FIRAuth.auth()?.currentUser?.uid {
                        newParticipantRef.setValue(uid)
                    }
                }
                roomVc.senderDisplayName = "Joe"
    }
}

And this is an observer for Firebase that is in charge of updating the table view once the user enters a name:

    private func observeRooms() {
        // Observe method to listen for new channels being written to Firebase
        let roomVc = RoomsTableViewController()

        roomVc.roomRefHandle = roomVc.roomRef.observe(.childAdded, with: { (snapshot) -> Void in
            let roomData = snapshot.value as! Dictionary<String, AnyObject>
            let id = snapshot.key

            if let uid = FIRAuth.auth()?.currentUser?.uid {
                if let name = roomData["name"] as! String!, name.characters.count > 0 {
                    roomVc.rooms.append(Room(id: id, name: name, participants: [uid]))
                    roomVc.tableView.reloadData()
                } else {
                    print("Error! Could not decode channel data")
                }
            }
        })
    }

And this is the IBAction for the "done" button being pressed:

@IBAction func setupDoneButtonPressed(_ sender: Any) {

    setUserInfo()
    observeRooms()

    let room = rooms  // <-- This is where I need to indicate that I want to go to the first room in the table
    self.performSegue(withIdentifier: "initChat", sender: room)
}

In this case I know that the screen I want to load will always be the very first cell in the table view, because at this point it will be the first cell created. But I don't know how to specify that without the index path in the table view's methods.

How can I do this?

Body:
For update the table view use:

self.tableView.reloadData()

What you have to do is: After the user enters the search value, and press the button, setupDoneButtonPressed() will be executed, after that, you have to set new data into a global variable. When data was set, you have to reload de tableview. I think this could help, let me know if you tried this.


问:
Leaflet Draw: differentiating between multiple controls
I'm adding two instances of Leaflet Draw (https://github.com/Leaflet/Leaflet.draw) like this (only using lines):

```<code>var drawControl = new L.Control.Draw({
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl);

var drawControl2 = new L.Control.Draw({
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl2);
</code>```

Now I want to listen to the draw:drawvertex event and do different things depending on if I had activated the drawControl or drawControl2:

```<code>map.on('draw:drawvertex', function (e) {
    console.log("Vertex drawn", e);
});
</code>```

How can I differentiate which drawControl is currently active?

答:
Here is a dirty way to know which drawControl is active.

The trick is to put them in different map corners. It helps to check which ul.leaflet-draw-actions is visible when the user draws. The one in div.leaflet-top or the one in div.leaflet-bottom for example :

```<code>var drawControl = new L.Control.Draw({
    position: 'topleft',
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl);

var drawControl2 = new L.Control.Draw({
    position: 'bottomleft',
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl2);

map.on('draw:drawvertex', function (e) {
    console.log("Vertex drawn", e);
    if ($('div.leaflet-top ul.leaflet-draw-actions').is(':visible')){
        console.log('it was drawn with drawControl');
    }
    else {
        console.log('it was drawn with drawControl2 !');
    }
});
</code>```

It's dirty but it works.

Body:
I'm adding two instances of Leaflet Draw (https://github.com/Leaflet/Leaflet.draw) like this (only using lines):

var drawControl = new L.Control.Draw({
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl);

var drawControl2 = new L.Control.Draw({
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl2);

Now I want to listen to the draw:drawvertex event and do different things depending on if I had activated the drawControl or drawControl2:

map.on('draw:drawvertex', function (e) {
    console.log("Vertex drawn", e);
});

How can I differentiate which drawControl is currently active?

Body:
Here is a dirty way to know which drawControl is active.

The trick is to put them in different map corners. It helps to check which ul.leaflet-draw-actions is visible when the user draws. The one in div.leaflet-top or the one in div.leaflet-bottom for example :

var drawControl = new L.Control.Draw({
    position: 'topleft',
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl);

var drawControl2 = new L.Control.Draw({
    position: 'bottomleft',
    draw: {
        polygon: false,
        rectangle: false,
        circle: false,
        marker: false
    }
});
map.addControl(drawControl2);

map.on('draw:drawvertex', function (e) {
    console.log("Vertex drawn", e);
    if ($('div.leaflet-top ul.leaflet-draw-actions').is(':visible')){
        console.log('it was drawn with drawControl');
    }
    else {
        console.log('it was drawn with drawControl2 !');
    }
});

It's dirty but it works.


问:
Erlang: programmatically get application version
I have an OTP application. The version of this application is found in two places: the src/application_name.src file (standard with OTP applications), and in my rebar.config.

Is there an "official" way for an application to get it's own version, or does this need to be hacked via sed/grep etc? I want to have an "info" endpoint in my application that prints it's own version. Of course I can always do something like grep the version out of my rebar.config, but it seems hacky.

答:
If it is properly packaged as an application, you can get it using application:which_applications(). I have some sample code, but basically you'd do something like this:

```<code>vsn() -> vsn(your_application_atom_name).

vsn(Application) -> vsn(Application, application:which_applications()).
vsn(_Application, []) -> undefined;
vsn(Application, [{Application,_,Vsn}|_]) -> Vsn;
vsn(Application, [_|Rest]) -> vsn(Application, Rest).
</code>```

The downside is that you do have to hardcode the name of your application (as an atom). I never found a way around this, but you might be able to cook something up.

Body:
If it is properly packaged as an application, you can get it using application:which_applications(). I have some sample code, but basically you'd do something like this:

vsn() -> vsn(your_application_atom_name).

vsn(Application) -> vsn(Application, application:which_applications()).
vsn(_Application, []) -> undefined;
vsn(Application, [{Application,_,Vsn}|_]) -> Vsn;
vsn(Application, [_|Rest]) -> vsn(Application, Rest).

The downside is that you do have to hardcode the name of your application (as an atom). I never found a way around this, but you might be able to cook something up.


问:
TypeError: 'module' object is not subscriptable
I'm using python version 3.6.

mystuff.py includes:

mystuff = {'donut': "SHE LOVES DONUTS!"}
```
<p><code>mystuffTest.py</code> includes this</p>
<pre class="lang-py prettyprint-override"><code>import mystuff
print (mystuff['donut'])
</code>```

The error that I receive when I run mystuffTest.py is as follows:

```<code>$ python3.6 mystuffTrythis.py
Traceback (most recent call last):
  File "mystuffTrythis.py", line 3, in <module>
    print (mystuff['donut'])
TypeError: 'module' object is not subscriptable
</code>```

So far I haven't seen this exact error here on stackoverflow.  Can anyone explain why I am getting this error?

答:
import mystuff is importing the module mystuff, not the variable mystuff.  To access the variable you'd need to use:

```<code>import mystuff
print(mystuff.mystuff['donut'])
</code>```

EDIT: It's also possible to import the variable directly, using:

```<code>from mystuff import mystuff
print(mystuff['donut'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using python version 3.6.

mystuff.py includes:

mystuff = {'donut': "SHE LOVES DONUTS!"}

mystuffTest.py includes this

import mystuff
print (mystuff['donut'])

The error that I receive when I run mystuffTest.py is as follows:

$ python3.6 mystuffTrythis.py
Traceback (most recent call last):
  File "mystuffTrythis.py", line 3, in <module>
    print (mystuff['donut'])
TypeError: 'module' object is not subscriptable

So far I haven't seen this exact error here on stackoverflow.  Can anyone explain why I am getting this error?

Body:
import mystuff is importing the module mystuff, not the variable mystuff.  To access the variable you'd need to use:

import mystuff
print(mystuff.mystuff['donut'])

EDIT: It's also possible to import the variable directly, using:

from mystuff import mystuff
print(mystuff['donut'])


问:
Multiple Computed Properties on Vue JS 2 data
So I learned VueJS 2 removed the orderby funtionality in Vue2 :'( I have been attempting to rewrite my app in Vue2 and understand computed properties is the new way to go. I have the following:

```<code>alphabeticalPosts: function () {
    return _.orderBy(this.posts, 'name')
},

searchedPosts: function() {
    return this.posts.filter((post) => {
        return
            post.name.toLowerCase().includes(this.keyword.toLowerCase());
     });
},
</code>```

Both of these work separately from each other. The issue I am having is that I need both on the HTML like so:

```<code><li v-for="post in searchedPosts/alphabeticalPosts">{{post.name}}</a>
</code>```

Now, of course, this does not work but it illustrates my issue. I need both applied to the same data set. In Angular I would just pipe it like so:

```<code>ng-repeat="post in posts | searchedPosts | alphabetizePosts"
</code>```

Of course, this also does not work in Vue. I'm under the impression I need to merge these two computer properties into one? My JS is lacking and every time I attempt this I end up with poor results. How do I go about using both my computed properties?

答:
```<code>computed:{
    filteredAndOrdered: function () {
        const keyword = this.keyword.toLowerCase();
        const filtered = this.posts.filter(post => post.name.toLowerCase().includes(keyword));
        return _.orderBy(filtered , 'name')
    }
}
</code>```

Template

```<code><li v-for="post in filteredAndOrdered">{{post.name}}</a>
</code>```

Body:
So I learned VueJS 2 removed the orderby funtionality in Vue2 :'( I have been attempting to rewrite my app in Vue2 and understand computed properties is the new way to go. I have the following:

alphabeticalPosts: function () {
    return _.orderBy(this.posts, 'name')
},

searchedPosts: function() {
    return this.posts.filter((post) => {
        return
            post.name.toLowerCase().includes(this.keyword.toLowerCase());
     });
},

Both of these work separately from each other. The issue I am having is that I need both on the HTML like so:

{{post.name}}

Now, of course, this does not work but it illustrates my issue. I need both applied to the same data set. In Angular I would just pipe it like so:

ng-repeat="post in posts | searchedPosts | alphabetizePosts"

Of course, this also does not work in Vue. I'm under the impression I need to merge these two computer properties into one? My JS is lacking and every time I attempt this I end up with poor results. How do I go about using both my computed properties?

Body:
computed:{
    filteredAndOrdered: function () {
        const keyword = this.keyword.toLowerCase();
        const filtered = this.posts.filter(post => post.name.toLowerCase().includes(keyword));
        return _.orderBy(filtered , 'name')
    }
}

Template

<li v-for="post in filteredAndOrdered">{{post.name}}</a>


问:
Clojure-idiomatic way to initialize a Java object
I am trying to find a Clojure-idiomatic way to initialize a Java object. I have the following code:

```<code>(let [url-connection
      (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn)]
  ; use the url-connection
  )
</code>```

but it seems very awkward.

What is a better way to create the HttpURLConnection object and initialize it before using it later in the code?

UPDATE: It seems that (doto ...) may come in handy here:

```<code>(let [url-connection
        (doto (java.net.HttpURLConnection.)
          (.setDoInput true)
          ; more initialization
          ))]
  ; use the url-connection
  )
</code>```

According to the doto docs, it returns the value to which it is "doing".

答:
Assuming that there is no constructor that accepts all the initialization parameters needed, then the way you did it is the only one I know.

The one thing you could do is wrap it all in a function like this:

```<code>(defn init-url-conn [doInput ...other params..]
     (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn))
</code>```

And call with:

```<code>(let [url-connection
      (let [url-conn (init-url-con true ...other params..)]
  ; use the url-connection
  )
</code>```

However, this is specific per object and it is really useful only if you are initializing object of that class more than once.

Also you could write a macro that accepts all method names, and params and does this. But, when called, that call wouldn't be much shorter than your first example.

If anyone has a better idea, I'd like to see it, since I was asking myself the same just the other day..

ContentLicense: CC BY-SA 2.5

Body:
I am trying to find a Clojure-idiomatic way to initialize a Java object. I have the following code:

(let [url-connection
      (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn)]
  ; use the url-connection
  )

but it seems very awkward.

What is a better way to create the HttpURLConnection object and initialize it before using it later in the code?

UPDATE: It seems that (doto ...) may come in handy here:

(let [url-connection
        (doto (java.net.HttpURLConnection.)
          (.setDoInput true)
          ; more initialization
          ))]
  ; use the url-connection
  )

According to the doto docs, it returns the value to which it is "doing".

Body:
Assuming that there is no constructor that accepts all the initialization parameters needed, then the way you did it is the only one I know.

The one thing you could do is wrap it all in a function like this:

(defn init-url-conn [doInput ...other params..]
     (let [url-conn (java.net.HttpURLConnection.)]
        (doto url-conn
          (.setDoInput true)
          ; more initialization on url-conn
          )
        url-conn))

And call with:

(let [url-connection
      (let [url-conn (init-url-con true ...other params..)]
  ; use the url-connection
  )

However, this is specific per object and it is really useful only if you are initializing object of that class more than once.

Also you could write a macro that accepts all method names, and params and does this. But, when called, that call wouldn't be much shorter than your first example.

If anyone has a better idea, I'd like to see it, since I was asking myself the same just the other day..


问:
Update current user attributes on .net C#
I started a .net web forms project, the template already allows users to login and register, On the manage page there is an option to reset password. how can I add options to update FirstName and LastName?

This is the code to create a new user:

```<code>var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, LastName = LastName.Text, PhoneNumber = PhoneNumber.Text };
        IdentityResult result = manager.Create(user, Password.Text);
        if (result.Succeeded)
        {
            signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);  //not needed
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); //not needed
        }
        else
        {
            ErrorMessage.Text = result.Errors.FirstOrDefault();
        }
</code>```

this is how the form looks like:

答:
This is how I solved it: hope it helps anybody.</p>

```<code>var currentUserId = HttpContext.Current.User.Identity.GetUserId();
        var context = new ApplicationDbContext();
        var user = context.Users.FirstOrDefault(u => u.Id == currentUserId);

        if (user != null)
        {
            if (FirstName.Text != "")   user.FirstName = FirstName.Text;
            if (LastName.Text != "")    user.LastName = LastName.Text;
            if (PhoneNumber.Text != "") user.PhoneNumber = PhoneNumber.Text;
            if(Email.Text != "")        user.Email = Email.Text;

        }

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        var result = userManager.Update(user);
        context.SaveChanges();
</code>```

Body:
I started a .net web forms project, the template already allows users to login and register, On the manage page there is an option to reset password. how can I add options to update FirstName and LastName?

This is the code to create a new user:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, LastName = LastName.Text, PhoneNumber = PhoneNumber.Text };
        IdentityResult result = manager.Create(user, Password.Text);
        if (result.Succeeded)
        {
            signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);  //not needed
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); //not needed
        }
        else
        {
            ErrorMessage.Text = result.Errors.FirstOrDefault();
        }

this is how the form looks like:

Body:
This is how I solved it: hope it helps anybody.

var currentUserId = HttpContext.Current.User.Identity.GetUserId();
        var context = new ApplicationDbContext();
        var user = context.Users.FirstOrDefault(u => u.Id == currentUserId);

        if (user != null)
        {
            if (FirstName.Text != "")   user.FirstName = FirstName.Text;
            if (LastName.Text != "")    user.LastName = LastName.Text;
            if (PhoneNumber.Text != "") user.PhoneNumber = PhoneNumber.Text;
            if(Email.Text != "")        user.Email = Email.Text;

        }

        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        var result = userManager.Update(user);
        context.SaveChanges();


答:
I don't even know how the last IP was saved because your function doesn't have any write in it.
You can try this :

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    list_ips = str ()
    for ips in ip:
    list_ips = list_ips + ips.get('ip') + '\n'

with open ('test.txt', 'w') as file:
    file.write (list_ips)
</code>```

You need something like file.write () to save your ips. I put all the ips in a string so that they are simpler to save in the file.
The with block doesn't require any close function

EDIT  (I can't comment)
The difference between these two methods:

```<code>my_file = open ('test.txt', 'w')
</code>```

and

```<code>my_file = open ('test.txt', 'a')
</code>```

is only that in the first one, all that was in the file before that function call is executed will be deleted. With append, it will not, and the my_file.write(something_to_add) will be added to the end of the file.
But opening in'w' mode will erase the file at the execution of this precise line only
I tested myself, this works with 'w' as well as with 'a'

Title: Python - Write for loop output to file

Body:
I don't even know how the last IP was saved because your function doesn't have any write in it.
You can try this :

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    list_ips = str ()
    for ips in ip:
    list_ips = list_ips + ips.get('ip') + '\n'

with open ('test.txt', 'w') as file:
    file.write (list_ips)

You need something like file.write () to save your ips. I put all the ips in a string so that they are simpler to save in the file.
The with block doesn't require any close function

EDIT  (I can't comment)
The difference between these two methods:

my_file = open ('test.txt', 'w')

and

my_file = open ('test.txt', 'a')

is only that in the first one, all that was in the file before that function call is executed will be deleted. With append, it will not, and the my_file.write(something_to_add) will be added to the end of the file.
But opening in'w' mode will erase the file at the execution of this precise line only
I tested myself, this works with 'w' as well as with 'a'


问:
Turn off echo of getpass.getpass() in IDLE
I would like to enter a password into the IDLE terminal in Windows without an echo.

Normally entering passwords is possible with python using the function getpass.getpass(), but in IDLE there comes up the following warning message:

```<code>GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
</code>```

I found out, this is because IDLE replaces the sys.stdin with a different object:

```<code>if sys.stdin is not sys.__stdin__:
    return fallback_getpass(prompt, stream)
</code>```

However, I could not find a solution. Does anybody have an answer or another way to enter a password into the IDLE terminal without an echo?

答:
As an IDLE maintainer with some familiarity with IDLE internals, I do not believe that it is possible to suppress character display but not otherwise change behavior in response to input('prompt') without major changes to IDLE code.

But even that would be insufficient for getpass.getpass since it calls one of unix_getpass, win_getpass, or default_getpass, and the first two use system_specific low-level functions that bypass stdin.

In terms of design intent: IDLE is, as its name says, a program development environment.  Developed programs normally, and sometimes must be, executed by Python directly, without going through IDLE.  Python normally runs attached to a terminal window.  IDLE's Shell is based on a tkinter Text widget, which is a multiline editor, not a terminal.  This is why one can enter, recall, and edit complete multiline statements rather than only a single line at a time.

Body:
I would like to enter a password into the IDLE terminal in Windows without an echo.

Normally entering passwords is possible with python using the function getpass.getpass(), but in IDLE there comes up the following warning message:

GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.

I found out, this is because IDLE replaces the sys.stdin with a different object:

if sys.stdin is not sys.__stdin__:
    return fallback_getpass(prompt, stream)

However, I could not find a solution. Does anybody have an answer or another way to enter a password into the IDLE terminal without an echo?


问:
Typescript compilation returns a lot of errors after VisualStudio 2017 install
After VisualStudio 2017 install on my pc I have problem with typescript compilation. Could somebody help with this issue? I can't find any explanation of this behaviour. In VS2015 it also returns same errors. Now I have installed typescript@2.2.2 globally.

Here is my typings.json

```<code>{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}
</code>```

Here is my tsconfig.json

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

Here in log from VisualStudio

2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(569,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Number'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(599,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Math'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(619,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'RegExp'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(623,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Map'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(624,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Set'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(625,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'WeakMap'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(626,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'WeakSet'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(627,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Promise'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(628,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Symbol'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(629,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Dict'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(630,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'global'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(631,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'log'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(632,11):
  error TS2451: Build:Cannot redeclare block-scoped variable '_'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(661,5):
  error TS2300: Build:Duplicate identifier 'export='.

答:
Visual Studio 2017 does not yet support TypeScript 2.2, so it's entirely possible new 2.2 syntax has been added to the typings, but is not yet supported by the version of TypeScript used in VS.

More information available at this blog post: https://blogs.msdn.microsoft.com/typescript/2017/03/27/typescripts-new-release-cadence/

If it is not a 2.2 issue, you can toggle off errors in your application by setting "skipLibCheck": true inside your tsconfig.json compilerOptions.

Body:
After VisualStudio 2017 install on my pc I have problem with typescript compilation. Could somebody help with this issue? I can't find any explanation of this behaviour. In VS2015 it also returns same errors. Now I have installed typescript@2.2.2 globally.

Here is my typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

Here is my tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

Here in log from VisualStudio

2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(569,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Number'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(599,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Math'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(619,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'RegExp'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(623,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Map'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(624,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Set'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(625,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'WeakMap'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(626,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'WeakSet'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(627,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Promise'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(628,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Symbol'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(629,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'Dict'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(630,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'global'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(631,11):
  error TS2451: Build:Cannot redeclare block-scoped variable 'log'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(632,11):
  error TS2451: Build:Cannot redeclare block-scoped variable '_'.
  2>C:\dev\Marketplace\Marketplace.Web\node_modules\@types\core-js\index.d.ts(661,5):
  error TS2300: Build:Duplicate identifier 'export='.


问:
Detecting an "invalid date" Date instance in JavaScript
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:

```<code>var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
</code>```

Any ideas for writing an isValidDate function?

Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.

What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.

Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.

Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.

答:
date.parse(valueToBeTested) > 0 is all that's needed. A valid date will return the epoch value and an invalid value will return NaN which will fail > 0 test by virtue of not even being a number.

This is so simple that a helper function won't save code though it might be a bit more readable. If you wanted one:

```<code>String.prototype.isDate = function() {
  return !Number.isNaN(Date.parse(this));
}
</code>```

OR

To use:

```<code>"StringToTest".isDate();
</code>```

Body:
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:

var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'

Any ideas for writing an isValidDate function?

Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.

What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.

Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.

Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.

Body:
date.parse(valueToBeTested) > 0 is all that's needed. A valid date will return the epoch value and an invalid value will return NaN which will fail > 0 test by virtue of not even being a number.

This is so simple that a helper function won't save code though it might be a bit more readable. If you wanted one:

String.prototype.isDate = function() {
  return !Number.isNaN(Date.parse(this));
}

OR

To use:

"StringToTest".isDate();


问:
Is an alamofire request to a HTTPS domain any different from that to HTTP?
I just added SSL to my backend framework (Django REST API) and I want my iOS application to talk to it. Do I have to do anything differently on the iOS side of my project? How do I tell Alamofire to encrypt the data its sending? Or Does it happen automatically?</p>

答:
The only difference is using https instead of http. I have the same setup at work, and originally thought I was going to have to delve into certificates. I started heading in that direction and then realized all my requests worked as soon as I stuck the "s" on the end.

I will say, while using NSStream, you do have to setup the stream to handle the certificate. I am doing this in another application, but that is below the URLRequest class. I am unsure of how low level Alomofire actually delves, but it will definitely handle everything you desire without doing anything differently.


问:
SQL Row not printing correct value
I am fairly new to SQL statements and I am trying to print units sold from a database. Under the units sold column it will not print the number it will just print "Units Sold". Any help would be greatly appreciated.
Here is my code: </p>

```<code>SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b
JOIN (
   SELECT brand_id, Avg(prod_price) AS avgprice
   FROM lgproduct
   GROUP BY brand_id
) sub1 ON b.brand_id = sub1.brand_id
JOIN (
   SELECT brand_id, Sum(line_qty) AS "Units Sold"
   FROM lgproduct p
   JOIN lgline l ON p.prod_sku = l.prod_sku
   GROUP BY brand_id
) sub2 ON b.brand_id = sub2.brand_id

ORDER BY brand_name;
</code>```

答:
Try this:</p>

```<code>SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price",  Units_Sold
FROM lgbrand b
JOIN (
   SELECT brand_id, Avg(prod_price) AS avgprice
   FROM lgproduct
   GROUP BY brand_id
) sub1 ON b.brand_id = sub1.brand_id
JOIN (
   SELECT brand_id, Sum(line_qty) AS Units_Sold
   FROM lgproduct p
   JOIN lgline l ON p.prod_sku = l.prod_sku
   GROUP BY brand_id
) sub2 ON b.brand_id = sub2.brand_id

ORDER BY brand_name;
</code>```

Title: SQL Row not printing correct value

Body:
I am fairly new to SQL statements and I am trying to print units sold from a database. Under the units sold column it will not print the number it will just print "Units Sold". Any help would be greatly appreciated.
Here is my code:

SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price", "Units Sold"
FROM lgbrand b
JOIN (
   SELECT brand_id, Avg(prod_price) AS avgprice
   FROM lgproduct
   GROUP BY brand_id
) sub1 ON b.brand_id = sub1.brand_id
JOIN (
   SELECT brand_id, Sum(line_qty) AS "Units Sold"
   FROM lgproduct p
   JOIN lgline l ON p.prod_sku = l.prod_sku
   GROUP BY brand_id
) sub2 ON b.brand_id = sub2.brand_id

ORDER BY brand_name;

Body:
Try this:

SELECT brand_name, brand_type, Round(avgprice,2) AS "Average Price",  Units_Sold
FROM lgbrand b
JOIN (
   SELECT brand_id, Avg(prod_price) AS avgprice
   FROM lgproduct
   GROUP BY brand_id
) sub1 ON b.brand_id = sub1.brand_id
JOIN (
   SELECT brand_id, Sum(line_qty) AS Units_Sold
   FROM lgproduct p
   JOIN lgline l ON p.prod_sku = l.prod_sku
   GROUP BY brand_id
) sub2 ON b.brand_id = sub2.brand_id

ORDER BY brand_name;


问:
Javascript func.prototype.apply() with a string instead of `this`
Just noticed a strange thing-

function one(){
  console.log(this);
}
function two(arg){
  one.apply(arg);
}

two("Hello World");```

Now it returns a String object containing all the letters of the argument [checked in the browser console]. I know I should have passed this as the first argument of apply and an array as the second. I did this accidentally and now I'm curious why is this happening. Can someone explain please? Or at least point me to the right direction?

Thanks in advance. And sorry for being so naive.

答:
In JavaScript, any value passed as this will be coerced to an object.

Thus, for a primitive string variable, this is essentially new String("Hello World"), which is a string wrapper object with all characters assigned as properties (similar to an array).

console.log("Hello World")

console.log(new String("Hello World"))```

For more information, see the distinction between string primitives and String objects on MDN.

Body:
Just noticed a strange thing-

function one(){
  console.log(this);
}
function two(arg){
  one.apply(arg);
}

two("Hello World");

Now it returns a String object containing all the letters of the argument [checked in the browser console]. I know I should have passed this as the first argument of apply and an array as the second. I did this accidentally and now I'm curious why is this happening. Can someone explain please? Or at least point me to the right direction?

Thanks in advance. And sorry for being so naive.

Body:
In JavaScript, any value passed as this will be coerced to an object.

Thus, for a primitive string variable, this is essentially new String("Hello World"), which is a string wrapper object with all characters assigned as properties (similar to an array).

console.log("Hello World")

console.log(new String("Hello World"))

For more information, see the distinction between string primitives and String objects on MDN.


问:
Urban Airship "error: cannot find symbol method shared()"
The "shared()" method is not being recognized for some reason, and this is preventing the code of my App from compiling. The error I see is:

```<code>error: cannot find symbol method shared()
</code>```

I am using this in my "build.gradle (Module: app)" file:

```<code>dependencies {
    ......................
    // Urban Airship SDK
    compile 'com.urbanairship.android:urbanairship-sdk:8.3.+'
    ......................
}
</code>```

I thought this "shared()" method would be included in the Urban Airship SDK version 8.3.+ that I am calling. When I see the Urban Airship Sample app they provide, a "shared()" method is declared at https://github.com/urbanairship/android-library/blob/master/urbanairship-sdk/src/main/java/com/urbanairship/UAirship.java:

```<code>/**
 * Returns the shared UAirship singleton instance. This method will block
 * until airship is ready.
 *
 * @return The UAirship singleton.
 * @throws IllegalStateException if takeoff is not called prior to this method.
 */
@NonNull
public static UAirship shared() {
    synchronized (airshipLock) {
        if (!isTakingOff && !isFlying) {
            throw new IllegalStateException("Take off must be called before shared()");
        }

        return waitForTakeOff(0);
    }
}
</code>```

Any ideas about why the "shared()" method is not available for me? This is an example of how I use it in my code, and I call it several times from different parts of the source code but it is always the same, the method is not recognized:

```<code>String appid=PushManager.shared().getAPID();
</code>```

Thank you.

答:
3.3 to 8.3 is pretty big update. We use "channels" now instead of "apids", essentially the same thing but have been updated a bit. We also removed most the singleton accessors for individual modules and moved them to the UAirship instance. New code should be

UAirship.shared().getPushManager().getChannelId();

I would recommend taking a look at the Urban Airship Android Guide as well as the migration guide. Other than API changes, we made lots of changes to how to listening and customizing push notifications. Although, customizing notification is not as necessary now that we provide most options through our push API now and airship config.

Body:
The "shared()" method is not being recognized for some reason, and this is preventing the code of my App from compiling. The error I see is:

error: cannot find symbol method shared()

I am using this in my "build.gradle (Module: app)" file:

dependencies {
    ......................
    // Urban Airship SDK
    compile 'com.urbanairship.android:urbanairship-sdk:8.3.+'
    ......................
}

I thought this "shared()" method would be included in the Urban Airship SDK version 8.3.+ that I am calling. When I see the Urban Airship Sample app they provide, a "shared()" method is declared at https://github.com/urbanairship/android-library/blob/master/urbanairship-sdk/src/main/java/com/urbanairship/UAirship.java:

/**
 * Returns the shared UAirship singleton instance. This method will block
 * until airship is ready.
 *
 * @return The UAirship singleton.
 * @throws IllegalStateException if takeoff is not called prior to this method.
 */
@NonNull
public static UAirship shared() {
    synchronized (airshipLock) {
        if (!isTakingOff && !isFlying) {
            throw new IllegalStateException("Take off must be called before shared()");
        }

        return waitForTakeOff(0);
    }
}

Any ideas about why the "shared()" method is not available for me? This is an example of how I use it in my code, and I call it several times from different parts of the source code but it is always the same, the method is not recognized:

String appid=PushManager.shared().getAPID();

Thank you.


答:
this return the last message in 24 hours between to users</p>

```<code>select
     cnv.id ,
     cnv.sender_id,
     cnv.recipient_id,
     cnv.content,
     cnv.Created_at
from
    (
    -- first create a table with costum id of conversaton
    select
         -- ex: 1001-256
         concat(greatest(sender_id, recipient_id),'-',least(sender_id, recipient_id) ) as 'cnv_id', --  costum column for joining
         id ,
         sender_id,
         recipient_id,
         content,
         Created_at
    from message
     ) cnv
          INNER JOIN
            (
            -- second extract the last date of every one to one coversation conversation
            -- result ex : 1001-256 | 2017-03-21 23:01:01
                 SELECT
                   concat(greatest(sender_id, recipient_id),'-',least(sender_id, recipient_id) )  as 'cnv_id', -- costum column for joining
                   max(Created_at)  'max_date'
                 group by cnv_id
            ) max_cnv   ON  cnv.cnv_id = max_cnv.cnv_id -- join the two result by the custom cnv_id
    WHERE
      -- here we extract only the record that there Created_at is > 24 hours from the max date
      -- you can make this condition as you want but i think this will work
      (max_cnv.max_date - cnv.Created_at)/1000/60 >= 24;
</code>```

Title: Get users who replied the first message of the conversation within 24hours

Body:
I need to find the users who replied the first message of the conversation (one to one conversation) within 24hours. I have a messages table where all data are stored.

Table: messages

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01
5  | 1002      | 500          | Hi there     | 2017-03-22 10:10:10
6  | 1002      | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 500       | 1002         | Yes          | 2017-03-22 10:20:30
8  | 1003      | 600          | Hello world  | 2017-03-23 01:00:00
9  | 1004      | 700          | Hi           | 2017-03-23 08:10:10
10 | 700       | 1004         | hello        | 2017-03-26 22:00:00

Expected result:

users
256
500

Example: Conversation between user 1001 and 256.

id | sender_id | recipient_id | content      | Created_at
1  | 1001      | 256          | Hi           | 2017-03-20 22:37:30
2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10
3  | 1001      | 256          | XYZ          | 2017-03-21 22:02:00
4  | 256       | 1001         | ???          | 2017-03-21 23:01:01

Here 2  | 256       | 1001         | Hello        | 2017-03-21 20:29:10 is the first replied message of the conversation and its replied within 24 hours.

Body:
this return the last message in 24 hours between to users

select
     cnv.id ,
     cnv.sender_id,
     cnv.recipient_id,
     cnv.content,
     cnv.Created_at
from
    (
    -- first create a table with costum id of conversaton
    select
         -- ex: 1001-256
         concat(greatest(sender_id, recipient_id),'-',least(sender_id, recipient_id) ) as 'cnv_id', --  costum column for joining
         id ,
         sender_id,
         recipient_id,
         content,
         Created_at
    from message
     ) cnv
          INNER JOIN
            (
            -- second extract the last date of every one to one coversation conversation
            -- result ex : 1001-256 | 2017-03-21 23:01:01
                 SELECT
                   concat(greatest(sender_id, recipient_id),'-',least(sender_id, recipient_id) )  as 'cnv_id', -- costum column for joining
                   max(Created_at)  'max_date'
                 group by cnv_id
            ) max_cnv   ON  cnv.cnv_id = max_cnv.cnv_id -- join the two result by the custom cnv_id
    WHERE
      -- here we extract only the record that there Created_at is > 24 hours from the max date
      -- you can make this condition as you want but i think this will work
      (max_cnv.max_date - cnv.Created_at)/1000/60 >= 24;


问:
OpenPGPJS: Error decrypting message: No symmetrically encrypted session key packet found
Below is my simple code (trying to learn how PGP works):

```<code>requirejs(['./openpgp'], function(openpgp) {

    openpgp.initWorker({
        path: './openpgp.worker.js'
    });

    openpgp.config.aead_protect = true;

    var fileContents = "Hello world!!";

    var encryptionCode = function(e) {
        var options;
        var encrypted;
        var myKey = {};

        myKey.pubkey =
`-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBFjMFRwBCACtu5EG8GusNpr5O4wrb3fykjPegUh9KD/ErWrplmXcbtp6T/XH
FPkc5cyMme7PxxlcFy3fshMDPg0adTGi8/TPygmO9THtjHYqynge0hxDyafP39xE
2DKkyuLyV3KxNiUfr+NUB3MQHktqiS/pPK1MJUQdHjYPHax5QT1bMgffx36tM5vo
d3rdu4AMmLgnSlakmWus/hHMFUgXdp4Q0LWf7uVTXTwbnTkfLQOumj+1SiYV40BL
rxgiyW172uqy6/hqK9JgOvAUjWZiO9aNyexENzA8Y+Oyy3OWX91CKTYiE2eQKhFK
YlTf/AFgrnFd0wgAFkZ0dWj51x7kH1a1Ks8/ABEBAAG0DXJhdmlAdGVzdC5jb22J
ARwEEAECAAYFAljMFRwACgkQc0zV1uezYVSN8Qf+NYyVvKK2HbF+Qn7j+Ed0esK2
OS6xVqdlFfUSAUq1ER13ffc4Darj9Z2LJuOvQ4M11IYlorXGdtiay55oT/xoljDr
HHIYzlQ4h6OzOJP6IUxIS0nqtKZCLhvvEYL/vOb/AeOMSo/ZWHD1RjCnpv0vVXki
4U+kAI8+hfI/QQrVco83xWhH0yiO/HH0eHVLkAiAraqv0zTSX6ttpnYDyK+mwLHt
bgWzzjUi1KZrNtR2CLU8nCUjyHLau1bkZnysq7mAAn69VEVAQ833WnKwBG7uIsym
lcZiCtOtIq40kP1wysObkgfLkD37LW3VpzY2i4+wiWa7i8tBYMvm58BYTCLguA==
=Xm9f
-----END PGP PUBLIC KEY BLOCK-----
`;

        myKey.privkey =
`-----BEGIN PGP PRIVATE KEY BLOCK-----

lQOsBFjMFRwBCACtu5EG8GusNpr5O4wrb3fykjPegUh9KD/ErWrplmXcbtp6T/XH
FPkc5cyMme7PxxlcFy3fshMDPg0adTGi8/TPygmO9THtjHYqynge0hxDyafP39xE
2DKkyuLyV3KxNiUfr+NUB3MQHktqiS/pPK1MJUQdHjYPHax5QT1bMgffx36tM5vo
d3rdu4AMmLgnSlakmWus/hHMFUgXdp4Q0LWf7uVTXTwbnTkfLQOumj+1SiYV40BL
rxgiyW172uqy6/hqK9JgOvAUjWZiO9aNyexENzA8Y+Oyy3OWX91CKTYiE2eQKhFK
YlTf/AFgrnFd0wgAFkZ0dWj51x7kH1a1Ks8/ABEBAAH/AwMCAqaV72qGxntgHjJJ
u1IAcTFlGt4e5nXAWGz9nMhQ84p4gHPT3wecMFul9Y8f3Xe8E6+bfaqESrtAaw28
UeRK3HpkYOYgcamC/iIMyZ8/GyqI/VrWpu+ola0WnLQUu58HogpHuk8ezb9Lfypq
qQVp3rTd58sT/RG/25cwSl5QDWZcE2CWTFc9SuwjtRlTj++Hw1ckqGQsGpVoGA3G
Gk5lfK06a3GqDzCaoNG5NUUjKEFhxUfOUCOfV2pyUT+9SBc+HoUptJ/csA/kPCB6
8xW3ycAQFLpYIqLcOJ9H3EMb8FIat2fPyaaocs+yIcYI0VLqS46Rhkj4apBQ8X5d
n3xlL32X/0CA5QKt6ybfXI6uHWvjbyyFl6bw8f8V23fyAXBiqLvz1stGtHTt/IWS
4j2MtOVxOumFY+dG2IHfyWfvh561drasQovtwh9diB4k96dnPYFwlG/8WRkhNF3R
Gkjwy0KOkr/LuvY7H9gFhyYDrXmXrcF3lUYxbQqou4V7nYOKynCGs8phWIezFVbN
4W0ew0rU4MqyAMdZ2YGM/hILSc2/RtufNR/nlPTe7mMGto8TjeVE0LTWcVs+I+A9
Iep0zwJLhdDGH5i0TcHPgxO+mzfcU2V5TrzLMuAlz9xZz3PKHlPMd5GV6THAMHM5
ZJB7P7skxC1zHdL0C00BFxG3QpDMKlFqozE2al7rizU0TtpGPWeOFRjThLuG+4wE
k+zj0EYSxsye7JRkpktMaX0DKk5dtSJn8lcFPR425E+clCwAWyd6Nhf0xEGWbRtL
D2OUWU//FQpDNS74+1EWWiEvfkuz9hZDk19KmpB6amiu4nuyzQJvWB8+gNiSNPZs
af95YSRueaPUYwMFTEhXVZGj1ZX0fM6dfxi4BE/JM7QNcmF2aUB0ZXN0LmNvbYkB
HAQQAQIABgUCWMwVHAAKCRBzTNXW57NhVI3xB/41jJW8orYdsX5CfuP4R3R6wrY5
LrFWp2UV9RIBSrURHXd99zgNquP1nYsm469DgzXUhiWitcZ22JrLnmhP/GiWMOsc
chjOVDiHo7M4k/ohTEhLSeq0pkIuG+8Rgv+85v8B44xKj9lYcPVGMKem/S9VeSLh
T6QAjz6F8j9BCtVyjzfFaEfTKI78cfR4dUuQCICtqq/TNNJfq22mdgPIr6bAse1u
BbPONSLUpms21HYItTycJSPIctq7VuRmfKyruYACfr1URUBDzfdacrAEbu4izKaV
xmIK060irjSQ/XDKw5uSB8uQPfstbdWnNjaLj7CJZruLy0Fgy+bnwFhMIuC4
=Qx/K
-----END PGP PRIVATE KEY BLOCK-----`;

        options = {
            data: fileContents,
            publicKeys: openpgp.key.readArmored(myKey.pubkey).keys
        };

        openpgp.encrypt(options).then(function(ciphertext) {
            myKey.encrypted = ciphertext.data;
            console.log("Encrypted: ", myKey.encrypted);

            options = {
                message: openpgp.message.readArmored(myKey.encrypted),     // parse armored message
                privateKeys: openpgp.key.readArmored(myKey.privkey).keys[0],
                "password": "abcd@1234"
            };

            openpgp.decrypt(options).then(function(plaintext) {
                console.log("plaintext", plaintext);
                return plaintext.data;
            });

        });

    }(this);

});
</code>```

I have generated public and private keys from online site. Its just for testing purpose.

I can see that the string has been encoded properly (console.log). But at the time of decryption, it throws exception Error decrypting message: No symmetrically encrypted session key packet found

What I am doing wrong? Please help me.

答:
Eventually, I figured out that, I had to decrypt my private key in order to decrypt the message.

The following code helped me to complete the encrypt/decrypt demo:

```<code>options = {
    message: openpgp.message.readArmored(myKey.encrypted),
    privateKeys: openpgp.key.readArmored(myKey.privkey).keys[0].decrypt('abcd@1234'),
    "password": "abcd@1234"
};

openpgp.decrypt(options).then(function(plaintext) {
    console.log("Encrypted message got decrypted: ", plaintext.data);
    return plaintext.data;
});
</code>```

Thanks.

Body:
Below is my simple code (trying to learn how PGP works):

requirejs(['./openpgp'], function(openpgp) {

    openpgp.initWorker({
        path: './openpgp.worker.js'
    });

    openpgp.config.aead_protect = true;

    var fileContents = "Hello world!!";

    var encryptionCode = function(e) {
        var options;
        var encrypted;
        var myKey = {};

        myKey.pubkey =
`-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBFjMFRwBCACtu5EG8GusNpr5O4wrb3fykjPegUh9KD/ErWrplmXcbtp6T/XH
FPkc5cyMme7PxxlcFy3fshMDPg0adTGi8/TPygmO9THtjHYqynge0hxDyafP39xE
2DKkyuLyV3KxNiUfr+NUB3MQHktqiS/pPK1MJUQdHjYPHax5QT1bMgffx36tM5vo
d3rdu4AMmLgnSlakmWus/hHMFUgXdp4Q0LWf7uVTXTwbnTkfLQOumj+1SiYV40BL
rxgiyW172uqy6/hqK9JgOvAUjWZiO9aNyexENzA8Y+Oyy3OWX91CKTYiE2eQKhFK
YlTf/AFgrnFd0wgAFkZ0dWj51x7kH1a1Ks8/ABEBAAG0DXJhdmlAdGVzdC5jb22J
ARwEEAECAAYFAljMFRwACgkQc0zV1uezYVSN8Qf+NYyVvKK2HbF+Qn7j+Ed0esK2
OS6xVqdlFfUSAUq1ER13ffc4Darj9Z2LJuOvQ4M11IYlorXGdtiay55oT/xoljDr
HHIYzlQ4h6OzOJP6IUxIS0nqtKZCLhvvEYL/vOb/AeOMSo/ZWHD1RjCnpv0vVXki
4U+kAI8+hfI/QQrVco83xWhH0yiO/HH0eHVLkAiAraqv0zTSX6ttpnYDyK+mwLHt
bgWzzjUi1KZrNtR2CLU8nCUjyHLau1bkZnysq7mAAn69VEVAQ833WnKwBG7uIsym
lcZiCtOtIq40kP1wysObkgfLkD37LW3VpzY2i4+wiWa7i8tBYMvm58BYTCLguA==
=Xm9f
-----END PGP PUBLIC KEY BLOCK-----
`;

        myKey.privkey =
`-----BEGIN PGP PRIVATE KEY BLOCK-----

lQOsBFjMFRwBCACtu5EG8GusNpr5O4wrb3fykjPegUh9KD/ErWrplmXcbtp6T/XH
FPkc5cyMme7PxxlcFy3fshMDPg0adTGi8/TPygmO9THtjHYqynge0hxDyafP39xE
2DKkyuLyV3KxNiUfr+NUB3MQHktqiS/pPK1MJUQdHjYPHax5QT1bMgffx36tM5vo
d3rdu4AMmLgnSlakmWus/hHMFUgXdp4Q0LWf7uVTXTwbnTkfLQOumj+1SiYV40BL
rxgiyW172uqy6/hqK9JgOvAUjWZiO9aNyexENzA8Y+Oyy3OWX91CKTYiE2eQKhFK
YlTf/AFgrnFd0wgAFkZ0dWj51x7kH1a1Ks8/ABEBAAH/AwMCAqaV72qGxntgHjJJ
u1IAcTFlGt4e5nXAWGz9nMhQ84p4gHPT3wecMFul9Y8f3Xe8E6+bfaqESrtAaw28
UeRK3HpkYOYgcamC/iIMyZ8/GyqI/VrWpu+ola0WnLQUu58HogpHuk8ezb9Lfypq
qQVp3rTd58sT/RG/25cwSl5QDWZcE2CWTFc9SuwjtRlTj++Hw1ckqGQsGpVoGA3G
Gk5lfK06a3GqDzCaoNG5NUUjKEFhxUfOUCOfV2pyUT+9SBc+HoUptJ/csA/kPCB6
8xW3ycAQFLpYIqLcOJ9H3EMb8FIat2fPyaaocs+yIcYI0VLqS46Rhkj4apBQ8X5d
n3xlL32X/0CA5QKt6ybfXI6uHWvjbyyFl6bw8f8V23fyAXBiqLvz1stGtHTt/IWS
4j2MtOVxOumFY+dG2IHfyWfvh561drasQovtwh9diB4k96dnPYFwlG/8WRkhNF3R
Gkjwy0KOkr/LuvY7H9gFhyYDrXmXrcF3lUYxbQqou4V7nYOKynCGs8phWIezFVbN
4W0ew0rU4MqyAMdZ2YGM/hILSc2/RtufNR/nlPTe7mMGto8TjeVE0LTWcVs+I+A9
Iep0zwJLhdDGH5i0TcHPgxO+mzfcU2V5TrzLMuAlz9xZz3PKHlPMd5GV6THAMHM5
ZJB7P7skxC1zHdL0C00BFxG3QpDMKlFqozE2al7rizU0TtpGPWeOFRjThLuG+4wE
k+zj0EYSxsye7JRkpktMaX0DKk5dtSJn8lcFPR425E+clCwAWyd6Nhf0xEGWbRtL
D2OUWU//FQpDNS74+1EWWiEvfkuz9hZDk19KmpB6amiu4nuyzQJvWB8+gNiSNPZs
af95YSRueaPUYwMFTEhXVZGj1ZX0fM6dfxi4BE/JM7QNcmF2aUB0ZXN0LmNvbYkB
HAQQAQIABgUCWMwVHAAKCRBzTNXW57NhVI3xB/41jJW8orYdsX5CfuP4R3R6wrY5
LrFWp2UV9RIBSrURHXd99zgNquP1nYsm469DgzXUhiWitcZ22JrLnmhP/GiWMOsc
chjOVDiHo7M4k/ohTEhLSeq0pkIuG+8Rgv+85v8B44xKj9lYcPVGMKem/S9VeSLh
T6QAjz6F8j9BCtVyjzfFaEfTKI78cfR4dUuQCICtqq/TNNJfq22mdgPIr6bAse1u
BbPONSLUpms21HYItTycJSPIctq7VuRmfKyruYACfr1URUBDzfdacrAEbu4izKaV
xmIK060irjSQ/XDKw5uSB8uQPfstbdWnNjaLj7CJZruLy0Fgy+bnwFhMIuC4
=Qx/K
-----END PGP PRIVATE KEY BLOCK-----`;

        options = {
            data: fileContents,
            publicKeys: openpgp.key.readArmored(myKey.pubkey).keys
        };

        openpgp.encrypt(options).then(function(ciphertext) {
            myKey.encrypted = ciphertext.data;
            console.log("Encrypted: ", myKey.encrypted);

            options = {
                message: openpgp.message.readArmored(myKey.encrypted),     // parse armored message
                privateKeys: openpgp.key.readArmored(myKey.privkey).keys[0],
                "password": "abcd@1234"
            };

            openpgp.decrypt(options).then(function(plaintext) {
                console.log("plaintext", plaintext);
                return plaintext.data;
            });

        });

    }(this);

});

I have generated public and private keys from online site. Its just for testing purpose.

I can see that the string has been encoded properly (console.log). But at the time of decryption, it throws exception Error decrypting message: No symmetrically encrypted session key packet found

What I am doing wrong? Please help me.

Body:
Eventually, I figured out that, I had to decrypt my private key in order to decrypt the message.

The following code helped me to complete the encrypt/decrypt demo:

options = {
    message: openpgp.message.readArmored(myKey.encrypted),
    privateKeys: openpgp.key.readArmored(myKey.privkey).keys[0].decrypt('abcd@1234'),
    "password": "abcd@1234"
};

openpgp.decrypt(options).then(function(plaintext) {
    console.log("Encrypted message got decrypted: ", plaintext.data);
    return plaintext.data;
});

Thanks.


问:
Apply patch to JBoss 5.1.0 GA
I would like to add the patch to a JBoss 5.1.0 GA installation in order to do some tests.

My question : How can I add this patch? Couldn't find anything revlevant so far.

Thank you.

答: You can use http://www.jboss.org/ejb3/ejb3plugin to patch an existing JBoss 5.1.0GA installation with the latest bits and bobs. </p>

Title: Apply patch to JBoss 5.1.0 GA


问:
Getting Argument out of range during pathfinding Coroutine
I'm new to using coroutines and am getting and out of range array error when running this function. I'm hoping it is a simple problem contained within this function, perhaps I am yielding at the wrong point, or need to use path.count -1.

```<code>public void UpdatePath() {
    the.pathFinder.FindPath (my);

    Vector3[] pathVectors = new Vector3[my.path.Count + 1];

    pathVectors [0] = (Vector3)my.transform.position;

    if (my.path.Count > 0) {
        for (int i = 0; i < my.path.Count; i++)
            pathVectors [i + 1] = my.path [i].transform.position;
    }

    my.pathLine.SetVertexCount (my.path.Count + 1);
    my.pathLine.SetPositions(pathVectors);

    StopCoroutine("FollowPath");
    StartCoroutine("FollowPath");
}

IEnumerator FollowPath() {

    Vector3 currentWayPoint = my.path [0].transform.position;

    while (true) {

        Vector2 heading = the.Heading (my.transform.position, currentWayPoint);

        if (heading.sqrMagnitude < 0.4) {
            targetIndex++;
            if (targetIndex >= my.path.Count) {
                print ("On yield break - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
                yield break;
            }
            print ("On assigning currentWayPoint - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
            currentWayPoint = my.path [targetIndex].transform.position;
        }

        my.pathGoal = ((heading).sqrMagnitude > 1f) ? heading.normalized * my.speed : heading * my.speed;
        yield return null;
    }
}
</code>```

I have put in a print log to check targetIndex against my.path.Count. To my understanding, in the second print log, the targetIndex should not be able to be equal to or greater than the my.path.Count and yet in the log, I'm getting "On assigning currentWayPoint - TargetIndex is 1 and my.path.Count is 1". I realise this is why I'm getting the out of range exception, but I don't understand how the code is reachable if the TargetIndex is equal to the my.path.Count. Is it possible for something else to happen between the yield break; line and the print log? Do coroutines run simultaneously with other code that could conflict?.

答:
This has nothing to do with coroutines.

You're trying to access member with index higher than the number of array elements:

```<code>for (int i = 0; i < my.path.Count; i++)
    pathVectors [i + 1] = my.path [i].transform.position; // will fail on i = path.Count
</code>```

Moreover, compiler tells you at what point in the code this exception happens, which should pretty easily lead you to a conclusion you have already reached:

need to use path.count -1

It's always a good idea to try what's on your mind in code to see if that works, before asking questions on SO.

Also, the if statement around this code is meaningless.

Body:
I'm new to using coroutines and am getting and out of range array error when running this function. I'm hoping it is a simple problem contained within this function, perhaps I am yielding at the wrong point, or need to use path.count -1.

public void UpdatePath() {
    the.pathFinder.FindPath (my);

    Vector3[] pathVectors = new Vector3[my.path.Count + 1];

    pathVectors [0] = (Vector3)my.transform.position;

    if (my.path.Count > 0) {
        for (int i = 0; i < my.path.Count; i++)
            pathVectors [i + 1] = my.path [i].transform.position;
    }

    my.pathLine.SetVertexCount (my.path.Count + 1);
    my.pathLine.SetPositions(pathVectors);

    StopCoroutine("FollowPath");
    StartCoroutine("FollowPath");
}

IEnumerator FollowPath() {

    Vector3 currentWayPoint = my.path [0].transform.position;

    while (true) {

        Vector2 heading = the.Heading (my.transform.position, currentWayPoint);

        if (heading.sqrMagnitude < 0.4) {
            targetIndex++;
            if (targetIndex >= my.path.Count) {
                print ("On yield break - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
                yield break;
            }
            print ("On assigning currentWayPoint - TargetIndex is " + targetIndex + " and my.path.Count is " + my.path.Count);
            currentWayPoint = my.path [targetIndex].transform.position;
        }

        my.pathGoal = ((heading).sqrMagnitude > 1f) ? heading.normalized * my.speed : heading * my.speed;
        yield return null;
    }
}

I have put in a print log to check targetIndex against my.path.Count. To my understanding, in the second print log, the targetIndex should not be able to be equal to or greater than the my.path.Count and yet in the log, I'm getting "On assigning currentWayPoint - TargetIndex is 1 and my.path.Count is 1". I realise this is why I'm getting the out of range exception, but I don't understand how the code is reachable if the TargetIndex is equal to the my.path.Count. Is it possible for something else to happen between the yield break; line and the print log? Do coroutines run simultaneously with other code that could conflict?.

Body:
This has nothing to do with coroutines.

You're trying to access member with index higher than the number of array elements:

for (int i = 0; i < my.path.Count; i++)
    pathVectors [i + 1] = my.path [i].transform.position; // will fail on i = path.Count

Moreover, compiler tells you at what point in the code this exception happens, which should pretty easily lead you to a conclusion you have already reached:

need to use path.count -1

It's always a good idea to try what's on your mind in code to see if that works, before asking questions on SO.

Also, the if statement around this code is meaningless.


问:
how to navigate to a url from our local host?
I have a url eg: xyz.net/645636. I'm trying to access it but it is giving me an error saying cannot get to xyz.net/645636. But, I didn't have any problem navigating to that page directly.
The local host url is http://localhost:3000/index.html.
I'm running my application using node server setup on my local system.

```<code><a href="xyz.net/645636"> Example Link </a>
</code>```

The link doesn't have any protocols. Could some one point out where am I doing it wrong?

答:
It needs a protocol:

```<code><a href="http://example.com/645636"> Example Link </a>
</code>```

When you type the address into your browser without one, it adds it for you for convenience.

Body:
I have a url eg: xyz.net/645636. I'm trying to access it but it is giving me an error saying cannot get to xyz.net/645636. But, I didn't have any problem navigating to that page directly.
The local host url is http://localhost:3000/index.html.
I'm running my application using node server setup on my local system.

 Example Link

The link doesn't have any protocols. Could some one point out where am I doing it wrong?

Body:
It needs a protocol:

<a href="http://example.com/645636"> Example Link </a>

When you type the address into your browser without one, it adds it for you for convenience.


问:
python string splitting with multiple splitting points
Ok so ill get straight to the point here is my code

```<code>def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment
</code>```

Input for this function is a list of multiple strings (seq) e.g. :

```<code>List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
</code>```

And enzymes as input:

```<code>[["TC", 1],["GC",1]]
</code>```

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

```<code>Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]
</code>```

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

答:
Assuming the idea is to split at each enzyme, at the index point where enzymes are multiple letters, and the split, in essence comes between the two letters. Don't need regex.

You can do this by looking for the occurrences and inserting a split indicator at the correct index and then post-process the result to actually split.

For example:

```<code>def digestfragmentwithenzyme(seqs, enzymes):
    # preprocess enzymes once, then apply to each sequence
    replacements = []
    for enzyme in enzymes:
        replacements.append((enzyme[0], enzyme[0][0:enzyme[1]] + '|' + enzyme[0][enzyme[1]:]))
    result = []
    for seq in seqs:
        for r in replacements:
            seq = seq.replace(r[0], r[1])   # So AATTC becomes AATT|C
        result.append(seq.split('|'))       # So AATT|C becomes AATT, C
    return result

def test():
    seqs = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
    enzymes = [["TC", 1],["GC",1]]
    print digestfragmentwithenzyme(seqs, enzymes)
</code>```

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
Assuming the idea is to split at each enzyme, at the index point where enzymes are multiple letters, and the split, in essence comes between the two letters. Don't need regex.

You can do this by looking for the occurrences and inserting a split indicator at the correct index and then post-process the result to actually split.

For example:

def digestfragmentwithenzyme(seqs, enzymes):
    # preprocess enzymes once, then apply to each sequence
    replacements = []
    for enzyme in enzymes:
        replacements.append((enzyme[0], enzyme[0][0:enzyme[1]] + '|' + enzyme[0][enzyme[1]:]))
    result = []
    for seq in seqs:
        for r in replacements:
            seq = seq.replace(r[0], r[1])   # So AATTC becomes AATT|C
        result.append(seq.split('|'))       # So AATT|C becomes AATT, C
    return result

def test():
    seqs = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
    enzymes = [["TC", 1],["GC",1]]
    print digestfragmentwithenzyme(seqs, enzymes)


问:
Django object not saving all iterations of a recursive save method
I have a recursive save method in my Django project to create multiple instances of calendar events; the problem is only the last event actually seems to get saved. I'm either missing something obvious, or there's an obscure bit of Django wizardy I'm not familiar with.

ETA: As an example, if I have an event on the first Friday of a month for three months, only the third month will actually save to the database.

Save method is below and related functions are below:

```<code>def move_to_next_month(sent_date):
    temp_date = sent_date.replace(tzinfo=None)
    if temp_date.month != 12:
        temp_date = temp_date.replace(month=temp_date.month + 1, day=1)
        return temp_date
    else:
       temp_date = temp_date.replace(year=temp_date.year + 1, month=1, day=1)
        return temp_date

def date_checker(temp_date, day_of_week, week_of_month):
    if week_of_month == "first":
        return temp_date.weekday() == day_of_week and 0 < temp_date.day < 8
    if week_of_month == "second":
        return temp_date.weekday() == day_of_week and 7 < temp_date.day < 15
    if week_of_month == "third":
        return temp_date.weekday() == day_of_week and 14 < temp_date.day < 22
    if week_of_month == "fourth":
        return temp_date.weekday() == day_of_week and 21 < temp_date.day < 28

def save(self, *args, **kwargs):
    if not self.orig_title:
        self.orig_title = self.title
    if self.end_date is None:
        self.end_date = self.start_date
    tempSlug = slugify("%s %s %s" % (self.orig_title, self.start_date.strftime("%b %d %Y"), self.branch))
    self.slug = tempSlug
    if not self.pk:
        self.is_repeating = repeating_event_check(self)
        super(MonthlyRepeatingEvent, self).save(*args,**kwargs)
        if self.number_of_repetitions > 1:
            temp_start_date = move_to_next_month(self.start_date)
            temp_end_date = move_to_next_month(self.end_date)
            next_repetition = self
            next_repetition.pk = None
            next_repetition.end_date = temp_end_date
            next_repetition.start_date = temp_start_date
            next_repetition.number_of_repetitions = self.number_of_repetitions - 1
            while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
            next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
            if next is not None:
                 next_repetition.pk = next.pk
                 next_repetition.slug = next_slug
                 next.delete()
                 next_repetition.save()
            else:
                 next_repetition.slug = next_slug
                 next_repetition.save()
    else:
        super(MonthlyRepeatingEvent, self).save(*args,**kwargs)
        if self.number_of_repetitions > 1:
            temp_start_date = move_to_next_month(self.start_date)
            temp_end_date = move_to_next_month(self.end_date)
            next_repetition = self
            next_repetition.pk = None
            next_repetition.end_date = temp_end_date
            next_repetition.start_date = temp_start_date
            next_repetition.number_of_repetitions = self.number_of_repetitions - 1
            while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
            next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
            if next is not None:
                 next_repetition.pk = next.pk
                 next_repetition.slug = next_slug
                 next.delete()
                 next_repetition.save()
            else:
                 next_repetition.slug = next_slug
                 next_repetition.save()
</code>```

ETA: updated code is below

```<code>class MonthlyRepeatingEvent(Event):
    day_of_week = models.PositiveSmallIntegerField(default=0, choices=DAY_OPTIONS,blank=True,null=True)
    week_of_month = models.CharField(max_length=6, choices=WEEK_OPTIONS,blank=True,null=True)
    number_of_repetitions = models.PositiveSmallIntegerField(default=0)

def create_new_instance(instance):
    temp_start_date = move_to_next_month(instance.start_date)
    temp_end_date = move_to_next_month(instance.end_date)
    next_repetition = instance
    next_repetition.pk = None
    next_repetition.end_date = temp_end_date
    next_repetition.start_date = temp_start_date
    next_repetition.number_of_repetitions = instance.number_of_repetitions - 1
    while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
    next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
    if next is not None:
        print("Delete function called.")
        next.delete()
    print("Save function called")
    next_repetition.save()

@receiver(post_save, sender=MonthlyRepeatingEvent)
    def repeater(sender, instance, **kwargs):
    if instance.number_of_repetitions > 1:
        create_new_instance(instance)
</code>```

答:
First and foremost - thanks to the commenters for their tips - that helped clean up my code considerably, which in turn aided with troubleshooting.

When I duplicated the repeating function  in a simplified form, it worked perfectly, indicating the problem was not in the logic behind the function; the primary difference between the simplified object and the one in the original query is the simplified object inherited directly from models.Model, and the original query object used inheritance from a base Event object.

And, in fact, the answer has to do with inheritance and Django models:

Making Queries|Django documentation|Django

When you create a copy of an object instance from a class that uses inheritance, you have to declare both instance.pk = None and instance.id = None.

Accordingly, the function to create repetition would be:

```<code>def create_mre_new_instance(instance):
    temp_start_date = move_to_next_month(instance.start_date)
    temp_end_date = move_to_next_month(instance.end_date)
    next_repetition = instance
    next_repetition.start_date = temp_start_date
    next_repetition.end_date = temp_end_date
    next_repetition.number_of_repetitions = instance.number_of_repetitions - 1
    while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
    next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
    if next is not None:
        next.delete()
    next_repetition.pk = None
    next_repetition.id = None
    next_repetition.save()
</code>```

Body:
I have a recursive save method in my Django project to create multiple instances of calendar events; the problem is only the last event actually seems to get saved. I'm either missing something obvious, or there's an obscure bit of Django wizardy I'm not familiar with.

ETA: As an example, if I have an event on the first Friday of a month for three months, only the third month will actually save to the database.

Save method is below and related functions are below:

def move_to_next_month(sent_date):
    temp_date = sent_date.replace(tzinfo=None)
    if temp_date.month != 12:
        temp_date = temp_date.replace(month=temp_date.month + 1, day=1)
        return temp_date
    else:
       temp_date = temp_date.replace(year=temp_date.year + 1, month=1, day=1)
        return temp_date

def date_checker(temp_date, day_of_week, week_of_month):
    if week_of_month == "first":
        return temp_date.weekday() == day_of_week and 0 < temp_date.day < 8
    if week_of_month == "second":
        return temp_date.weekday() == day_of_week and 7 < temp_date.day < 15
    if week_of_month == "third":
        return temp_date.weekday() == day_of_week and 14 < temp_date.day < 22
    if week_of_month == "fourth":
        return temp_date.weekday() == day_of_week and 21 < temp_date.day < 28

def save(self, *args, **kwargs):
    if not self.orig_title:
        self.orig_title = self.title
    if self.end_date is None:
        self.end_date = self.start_date
    tempSlug = slugify("%s %s %s" % (self.orig_title, self.start_date.strftime("%b %d %Y"), self.branch))
    self.slug = tempSlug
    if not self.pk:
        self.is_repeating = repeating_event_check(self)
        super(MonthlyRepeatingEvent, self).save(*args,**kwargs)
        if self.number_of_repetitions > 1:
            temp_start_date = move_to_next_month(self.start_date)
            temp_end_date = move_to_next_month(self.end_date)
            next_repetition = self
            next_repetition.pk = None
            next_repetition.end_date = temp_end_date
            next_repetition.start_date = temp_start_date
            next_repetition.number_of_repetitions = self.number_of_repetitions - 1
            while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
            next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
            if next is not None:
                 next_repetition.pk = next.pk
                 next_repetition.slug = next_slug
                 next.delete()
                 next_repetition.save()
            else:
                 next_repetition.slug = next_slug
                 next_repetition.save()
    else:
        super(MonthlyRepeatingEvent, self).save(*args,**kwargs)
        if self.number_of_repetitions > 1:
            temp_start_date = move_to_next_month(self.start_date)
            temp_end_date = move_to_next_month(self.end_date)
            next_repetition = self
            next_repetition.pk = None
            next_repetition.end_date = temp_end_date
            next_repetition.start_date = temp_start_date
            next_repetition.number_of_repetitions = self.number_of_repetitions - 1
            while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
                next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
            next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
            next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
            if next is not None:
                 next_repetition.pk = next.pk
                 next_repetition.slug = next_slug
                 next.delete()
                 next_repetition.save()
            else:
                 next_repetition.slug = next_slug
                 next_repetition.save()

ETA: updated code is below

class MonthlyRepeatingEvent(Event):
    day_of_week = models.PositiveSmallIntegerField(default=0, choices=DAY_OPTIONS,blank=True,null=True)
    week_of_month = models.CharField(max_length=6, choices=WEEK_OPTIONS,blank=True,null=True)
    number_of_repetitions = models.PositiveSmallIntegerField(default=0)

def create_new_instance(instance):
    temp_start_date = move_to_next_month(instance.start_date)
    temp_end_date = move_to_next_month(instance.end_date)
    next_repetition = instance
    next_repetition.pk = None
    next_repetition.end_date = temp_end_date
    next_repetition.start_date = temp_start_date
    next_repetition.number_of_repetitions = instance.number_of_repetitions - 1
    while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
    next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
    if next is not None:
        print("Delete function called.")
        next.delete()
    print("Save function called")
    next_repetition.save()

@receiver(post_save, sender=MonthlyRepeatingEvent)
    def repeater(sender, instance, **kwargs):
    if instance.number_of_repetitions > 1:
        create_new_instance(instance)

Body:
First and foremost - thanks to the commenters for their tips - that helped clean up my code considerably, which in turn aided with troubleshooting.

When I duplicated the repeating function  in a simplified form, it worked perfectly, indicating the problem was not in the logic behind the function; the primary difference between the simplified object and the one in the original query is the simplified object inherited directly from models.Model, and the original query object used inheritance from a base Event object.

And, in fact, the answer has to do with inheritance and Django models:

Making Queries|Django documentation|Django

When you create a copy of an object instance from a class that uses inheritance, you have to declare both instance.pk = None and instance.id = None.

Accordingly, the function to create repetition would be:

def create_mre_new_instance(instance):
    temp_start_date = move_to_next_month(instance.start_date)
    temp_end_date = move_to_next_month(instance.end_date)
    next_repetition = instance
    next_repetition.start_date = temp_start_date
    next_repetition.end_date = temp_end_date
    next_repetition.number_of_repetitions = instance.number_of_repetitions - 1
    while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month):
        next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1)
    next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch))
    next = MonthlyRepeatingEvent.objects.filter(slug=next_slug).first()
    if next is not None:
        next.delete()
    next_repetition.pk = None
    next_repetition.id = None
    next_repetition.save()


问:
Class not registered HRESULT 0x80040154
I'm using the .NET framework version 6.0 on Windows Vista. I recently installed a program that displays charts. When I open it, I get an error message from the Microsoft .NET framework:

Class not registered (exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

How do I fix the problem? Thanks.

答:
The simple answer is that you register the class.  (if you knew which class wasn't registered, and what library it was in.)  But its a big failing of errors such as this that they don't tell you these important details.

I think your better option is to uninstall the software, and re-install it carefully, reading every installation panel carefully, checking for prerequisites, or any other instructions.  And be sure to start the installer with "Run As Administrator".

If that still fails, call tech-support for the software.

Title: Class not registered HRESULT 0x80040154

LastEditorDisplayName: moocha

OwnerDisplayName: Aaron


问:
Can I give an intermediate string to fetch from mysql table which values has that string in middle?
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

```<code>Select *
from orders
where date = "%03%"
</code>```

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

答:
There is more than one way to do it. You can use SUBSTRING:

```<code>SELECT * FROM orders WHERE SUBSTRING(`date`, 3, 2) = "03"
</code>```

Using LIKE "__03____" as shown in the other answers should also work.

My favorite option would be to

STORE YOUR DATES IN A DATE COLUMN

so you can just do this:

```<code>SELECT * FROM orders WHERE MONTH(`date`) = 3
</code>```

FYI:

```<code>ALTER TABLE orders ADD COLUMN order_date DATE;
UPDATE orders SET order_date = str_to_date(`date`,'%d%m%Y');
</code>```

Body:
For Example :-

I have saved date in my table in the format of ddmmyyyy

Now I need to fetch rows of month 03

So my query can be

Select *
from orders
where date = "%03%"

But it will bring values of date 03 and year 2003 too.

Is there anyway to fetch the values where the 03 is in the position of 3rd and 4th in the string?

Body:
There is more than one way to do it. You can use SUBSTRING:

SELECT * FROM orders WHERE SUBSTRING(`date`, 3, 2) = "03"

Using LIKE "__03____" as shown in the other answers should also work.

My favorite option would be to

STORE YOUR DATES IN A DATE COLUMN

so you can just do this:

SELECT * FROM orders WHERE MONTH(`date`) = 3

FYI:

ALTER TABLE orders ADD COLUMN order_date DATE;
UPDATE orders SET order_date = str_to_date(`date`,'%d%m%Y');


问:
Setting styles in Openpyxl
I need advice on setting styles in Openpyxl.

I see that the NumberFormat of a cell can be set, but I also require setting of font colors and attributes (bold etc). There is a style.py class but it seems I can't set the style attribute of a cell, and I don't really want to start tinkering with the openpyxl source code.

Has anyone found a solution to this?

答:
For openpyxl version 2.4.1 and above use below code to set font color:

```<code>from openpyxl.styles import Font
from openpyxl.styles.colors import Color

ws1['A1'].font = Font(color = "FF0000")
</code>```

hex codes for various colors can be found at:
http://dmcritchie.mvps.org/excel/colors.htm

Title: Setting styles in Openpyxl

Body:
For openpyxl version 2.4.1 and above use below code to set font color:

from openpyxl.styles import Font
from openpyxl.styles.colors import Color

ws1['A1'].font = Font(color = "FF0000")

hex codes for various colors can be found at:
http://dmcritchie.mvps.org/excel/colors.htm