问:
Making my cython code more efficient
I've written a python program which I try to cythonize.
Is there any suggestion how to make the for-loop more efficient, as this is taking 99% of the time?

This is the for-loop:

```<code>    for i in range(l):
        b1[i] = np.nanargmin(locator[i,:]) # Closer point
        locator[i, b1[i]] = NAN # Do not consider Closer point
        b2[i] = np.nanargmin(locator[i,:]) # 2nd Closer point
        Adjacents[i,0] = np.array((Existed_Pips[b1[i]]), dtype=np.double)
        Adjacents[i,1] = np.array((Existed_Pips[b2[i]]), dtype=np.double)
</code>```

This is the rest of the code:

```<code>import numpy as np
cimport numpy as np
from libc.math cimport NAN #, isnan

def PIPs(np.ndarray[np.double_t, ndim=1, mode='c'] ys, unsigned int nofPIPs, unsigned int typeofdist):
    cdef:
        unsigned int currentstate, j, i
        np.ndarray[np.double_t, ndim=1, mode="c"] D
        np.ndarray[np.int64_t, ndim=1, mode="c"] Existed_Pips
        np.ndarray[np.int_t, ndim=1, mode="c"] xs
        np.ndarray[np.double_t, ndim=2] Adjacents, locator, Adjy, Adjx, Raw_Fire_PIPs, Raw_Fem_PIPs
        np.ndarray[np.int_t, ndim=2, mode="c"] PIP_points, b1, b2

    cdef unsigned int l = len(ys)
    xs = np.arange(0,l, dtype=np.int) # Column vector with xs
    PIP_points = np.zeros((l,1), dtype=np.int) # Binary indexation
    PIP_points[0] = 1 # One indicate the PIP points.The first two PIPs are the first and the last observation.
    PIP_points[-1] = 1
    Adjacents = np.zeros((l,2), dtype=np.double)
    currentstate = 2 # Initial PIPs

    while currentstate <= nofPIPs: #    for eachPIPs in range(nofPIPs)
        Existed_Pips = np.flatnonzero(PIP_points)
        currentstate = len(Existed_Pips)
        locator = np.full((l,currentstate), NAN, dtype=np.double) #np.int*
        for j in range(currentstate):
            locator[:,j] = np.absolute(xs-Existed_Pips[j])
        b1 = np.zeros((l,1), dtype=np.int)
        b2 = np.zeros((l,1), dtype=np.int)
        for i in range(l):
            b1[i] = np.nanargmin(locator[i,:]) # Closer point
            locator[i, b1[i]] = NAN # Do not consider Closer point
            b2[i] = np.nanargmin(locator[i,:]) # 2nd Closer point
            Adjacents[i,0] = np.array((Existed_Pips[b1[i]]), dtype=np.double)
            Adjacents[i,1] = np.array((Existed_Pips[b2[i]]), dtype=np.double)

        ##Calculate Distance
        Adjx = Adjacents
        Adjy = np.array([ys[np.array(Adjacents[:,0], dtype=np.int)], ys[np.array(Adjacents[:,1], dtype=np.int)]]).transpose()
        Adjx[Existed_Pips,:] = NAN # Existed PIPs are not candidates for new PIP.
        Adjy[Existed_Pips,:] = NAN

        if typeofdist == 1: #Euclidean Distance
            ##[D] = EDist(ys,xs,Adjx,Adjy)
            ED = np.power(np.power((Adjx[:,1]-xs),2) + np.power((Adjy[:,1]-ys),2),(0.5)) + np.power(np.power((Adjx[:,0]-xs),2) + np.power((Adjy[:,0]-ys),2),(0.5))

        EDmax = np.nanargmax(ED)
        PIP_points[EDmax]=1

        currentstate=currentstate+1

    return np.array([Existed_Pips, ys[Existed_Pips]]).transpose()
</code>```

答:
A couple of suggestions:

Take the calls to np.nanargmin out of the loop (use the axis parameter to let you operate on the whole array at once. This reduces the number of Python function calls you have to make:

```<code>b1 = np.nanargmin(locator,axis=1)
locator[np.arange(locator.shape[0]),b1] = np.nan
b2 = np.nanargmin(locator,axis=1)
</code>```

Your assignment to Adjacents is odd - you seem to be creating a length-1 array for the right-hand side first. Instead just do

```<code>Adjacents[i,0] = Existed_Pips[b1[i]]
# ...
</code>```

However, in this case, you can also take both lines outside the loop, eliminating the entire loop:

```<code>Adjacents = np.vstack((Existing_Pips[b1], Existings_Pips[b2])).T
</code>```

All of this is relying on numpy, rather than Cython, for the speed-up, but it probably beats your version.

Title: Making my cython code more efficient

Body:
I've written a python program which I try to cythonize.
Is there any suggestion how to make the for-loop more efficient, as this is taking 99% of the time?

This is the for-loop:

    for i in range(l):
        b1[i] = np.nanargmin(locator[i,:]) # Closer point
        locator[i, b1[i]] = NAN # Do not consider Closer point
        b2[i] = np.nanargmin(locator[i,:]) # 2nd Closer point
        Adjacents[i,0] = np.array((Existed_Pips[b1[i]]), dtype=np.double)
        Adjacents[i,1] = np.array((Existed_Pips[b2[i]]), dtype=np.double)

This is the rest of the code:

import numpy as np
cimport numpy as np
from libc.math cimport NAN #, isnan

def PIPs(np.ndarray[np.double_t, ndim=1, mode='c'] ys, unsigned int nofPIPs, unsigned int typeofdist):
    cdef:
        unsigned int currentstate, j, i
        np.ndarray[np.double_t, ndim=1, mode="c"] D
        np.ndarray[np.int64_t, ndim=1, mode="c"] Existed_Pips
        np.ndarray[np.int_t, ndim=1, mode="c"] xs
        np.ndarray[np.double_t, ndim=2] Adjacents, locator, Adjy, Adjx, Raw_Fire_PIPs, Raw_Fem_PIPs
        np.ndarray[np.int_t, ndim=2, mode="c"] PIP_points, b1, b2

    cdef unsigned int l = len(ys)
    xs = np.arange(0,l, dtype=np.int) # Column vector with xs
    PIP_points = np.zeros((l,1), dtype=np.int) # Binary indexation
    PIP_points[0] = 1 # One indicate the PIP points.The first two PIPs are the first and the last observation.
    PIP_points[-1] = 1
    Adjacents = np.zeros((l,2), dtype=np.double)
    currentstate = 2 # Initial PIPs

    while currentstate <= nofPIPs: #    for eachPIPs in range(nofPIPs)
        Existed_Pips = np.flatnonzero(PIP_points)
        currentstate = len(Existed_Pips)
        locator = np.full((l,currentstate), NAN, dtype=np.double) #np.int*
        for j in range(currentstate):
            locator[:,j] = np.absolute(xs-Existed_Pips[j])
        b1 = np.zeros((l,1), dtype=np.int)
        b2 = np.zeros((l,1), dtype=np.int)
        for i in range(l):
            b1[i] = np.nanargmin(locator[i,:]) # Closer point
            locator[i, b1[i]] = NAN # Do not consider Closer point
            b2[i] = np.nanargmin(locator[i,:]) # 2nd Closer point
            Adjacents[i,0] = np.array((Existed_Pips[b1[i]]), dtype=np.double)
            Adjacents[i,1] = np.array((Existed_Pips[b2[i]]), dtype=np.double)

        ##Calculate Distance
        Adjx = Adjacents
        Adjy = np.array([ys[np.array(Adjacents[:,0], dtype=np.int)], ys[np.array(Adjacents[:,1], dtype=np.int)]]).transpose()
        Adjx[Existed_Pips,:] = NAN # Existed PIPs are not candidates for new PIP.
        Adjy[Existed_Pips,:] = NAN

        if typeofdist == 1: #Euclidean Distance
            ##[D] = EDist(ys,xs,Adjx,Adjy)
            ED = np.power(np.power((Adjx[:,1]-xs),2) + np.power((Adjy[:,1]-ys),2),(0.5)) + np.power(np.power((Adjx[:,0]-xs),2) + np.power((Adjy[:,0]-ys),2),(0.5))

        EDmax = np.nanargmax(ED)
        PIP_points[EDmax]=1

        currentstate=currentstate+1

    return np.array([Existed_Pips, ys[Existed_Pips]]).transpose()

Body:
A couple of suggestions:

Take the calls to np.nanargmin out of the loop (use the axis parameter to let you operate on the whole array at once. This reduces the number of Python function calls you have to make:

b1 = np.nanargmin(locator,axis=1)
locator[np.arange(locator.shape[0]),b1] = np.nan
b2 = np.nanargmin(locator,axis=1)

Your assignment to Adjacents is odd - you seem to be creating a length-1 array for the right-hand side first. Instead just do

Adjacents[i,0] = Existed_Pips[b1[i]]
# ...

However, in this case, you can also take both lines outside the loop, eliminating the entire loop:

Adjacents = np.vstack((Existing_Pips[b1], Existings_Pips[b2])).T

All of this is relying on numpy, rather than Cython, for the speed-up, but it probably beats your version.


来源: stackexchange

问:
Generate structure classes from StructureDefintion with HAPI
Is it possible to generate structure classes from a custom StructureDefintion in a similar fashion as HAPI generates official DSTU2/3 structure classes?

I want to implement some local StructureDefinition from simplifier.net (For example: https://simplifier.net/NictizSTU3/nl-core-address/).

The documentation of HAPI wasn't helping me either, am i suppose to use the hapi-tinder-plugin?

It seems tedious and error prone to hand write custom structures as specified in http://hapifhir.io/doc_custom_structures.html

For me the ideal workflow is something like:

Fetch StructureDefinition from simplifier

Generate models for the StructureDefinition

Register generated models in HAPI and fill the models accordingly

答: Generating classes from profiles is on our list of things to do, but doing it well (particularly when there's slicing involved) isn't super-easy, so most of the reference implementations have been holding off until there's funding support to get it done.</p>

ContentLicense: CC BY-SA 3.0


问:
Deep copy of Poco::JSON::Object
I'm trying to create deep copy of Poco::JSON::Object.

Internally Poco::JSON::Object uses pointers and copy constructor just copy those pointers. Is there a clever solution how to copy this structure using Poco framework?

答:
could not find good documentation. so here is another way of copying. you can check if the key and value need further deeper copy like using c_str(). for me this works fine.</p>

```<code>Poco::JSON::Object::Ptr cloneJsonObject(Poco::JSON::Object::Ptr obj)
{
    Poco::JSON::Object::Iterator it;
    Poco::JSON::Object *ptr = new Poco::JSON::Object;
    // loop and copy
    for(it = obj->begin(); it != obj->end(); it++)
        ptr->set(it->first, it->second);

    return ptr;
}
</code>```

Title: Deep copy of Poco::JSON::Object

Body:
could not find good documentation. so here is another way of copying. you can check if the key and value need further deeper copy like using c_str(). for me this works fine.

Poco::JSON::Object::Ptr cloneJsonObject(Poco::JSON::Object::Ptr obj)
{
    Poco::JSON::Object::Iterator it;
    Poco::JSON::Object *ptr = new Poco::JSON::Object;
    // loop and copy
    for(it = obj->begin(); it != obj->end(); it++)
        ptr->set(it->first, it->second);

    return ptr;
}


问:
Echo printing variables in a completely wrong order
I am trying to create a string with a query that will be save / send to another location, this string contains different variables.

The issue that I am having is that the echo of the variables are completely upside down and mix.

See code below:

```<code>tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt")
serverName="asdasd"
attQuery="$tokenID $serverName"
agentRegQuery="$./opt/mule/bin/amc_setup -H $attQuery"

echo TOKEN ID $tokenID
echo SERVER NAME $serverName
echo $attQuery
echo $agentRegQuery
</code>```

Find below the output I am receiving:

```<code>TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
SERVER NAME asdasd
 asdasdf-fa0e-4f08-87eb-418722872d80---46407
 asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407
</code>```

答:
There's a carriage return character at the end of the tokenID variable, probably because /tempdir/tokenfile.txt is in DOS/Windows format (lines end with carriage return+linefeed), not unix (lines end with just linefeed). When you print tokenID by itself, it looks ok, but if you print something else after that on the same line, it winds up overwriting the first part of the line. So when you print $attQuery, it prints this:

```<code>29a6966f-fa0e-4f08-87eb-418722872d80---46407[carriage return]
 asdasd
</code>```

...but with the second line printed on top of the first, so it comes out as:

```<code> asdasdf-fa0e-4f08-87eb-418722872d80---46407
</code>```

The solution is to either convert the file to unix format (dos2unix will do this if you have it), or remove the carriage return in your script. You can do it like this:

```<code>tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt" | tr -d '\r')
</code>```

Body:
I am trying to create a string with a query that will be save / send to another location, this string contains different variables.

The issue that I am having is that the echo of the variables are completely upside down and mix.

See code below:

tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt")
serverName="asdasd"
attQuery="$tokenID $serverName"
agentRegQuery="$./opt/mule/bin/amc_setup -H $attQuery"

echo TOKEN ID $tokenID
echo SERVER NAME $serverName
echo $attQuery
echo $agentRegQuery

Find below the output I am receiving:

TOKEN ID 29a6966f-fa0e-4f08-87eb-418722872d80---46407
SERVER NAME asdasd
 asdasdf-fa0e-4f08-87eb-418722872d80---46407
 asdasdmule/bin/amc_setup -H 29a6966f-fa0e-4f08-87eb-418722872d80---46407

Body:
There's a carriage return character at the end of the tokenID variable, probably because /tempdir/tokenfile.txt is in DOS/Windows format (lines end with carriage return+linefeed), not unix (lines end with just linefeed). When you print tokenID by itself, it looks ok, but if you print something else after that on the same line, it winds up overwriting the first part of the line. So when you print $attQuery, it prints this:

29a6966f-fa0e-4f08-87eb-418722872d80---46407[carriage return]
 asdasd

...but with the second line printed on top of the first, so it comes out as:

 asdasdf-fa0e-4f08-87eb-418722872d80---46407

The solution is to either convert the file to unix format (dos2unix will do this if you have it), or remove the carriage return in your script. You can do it like this:

tokenID=$(docker exec -ti $dockerContainerID /bin/sh -c "cat /tempdir/tokenfile.txt" | tr -d '\r')


问:
How to make your c# app work as windows service?
How to make your c# app work as windows service? (matereals, todos wanted)</p>

答:
To get some pointers on how to make a standalone WCF service, you can look at

http://social.msdn.microsoft.com/Forums/en/wcf/thread/1f62d283-f3aa-4c8e-a4ee-237e03801da9

You may want to start with having part of the app in IIS, and then as you get the web service fleshed out, then move it to your own application, removing the need for IIS.

That way you limit how much you actually need to debug at one time.

ContentLicense: CC BY-SA 2.5


问:
ssh_exchange_identification: Connection closed by remote host under Git bash
I work at win7 and set up git server with sshd.
I git --bare init myapp.git, and clone ssh://git@localhost/home/git/myapp.git in Cywgin correctly. But I need config git of Cygwin again, I want to git clone in Git Bash. I run git clone ssh://git@localhost/home/git/myapp.git and get following message

```<code>ssh_exchange_identification: Connection closed by remote host
</code>```

then I run ssh -vvv git@localhost in Git Bash and get message

```<code>debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host
</code>```

it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without BEGIN and END.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.

Any advises are welcome.
btw, I have read first 3 pages on google about this problem.

答:
We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.

```<code>Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.
</code>```

This will help if you are connecting to some or all servers via a jump host server.

Earlier in my ~/.ssh/config file, my setting to connect were:

```<code>Host * !ssh.somejumphost.my.company.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com
</code>```

What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.

To FIX the issue, all I did was, change the config to ignore git server as well:

```<code>Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com
</code>```

So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.

Body:
I work at win7 and set up git server with sshd.
I git --bare init myapp.git, and clone ssh://git@localhost/home/git/myapp.git in Cywgin correctly. But I need config git of Cygwin again, I want to git clone in Git Bash. I run git clone ssh://git@localhost/home/git/myapp.git and get following message

ssh_exchange_identification: Connection closed by remote host

then I run ssh -vvv git@localhost in Git Bash and get message

debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host

it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without BEGIN and END.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.

Any advises are welcome.
btw, I have read first 3 pages on google about this problem.

Body:
We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.

Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

This will help if you are connecting to some or all servers via a jump host server.

Earlier in my ~/.ssh/config file, my setting to connect were:

Host * !ssh.somejumphost.my.company.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.

To FIX the issue, all I did was, change the config to ignore git server as well:

Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.


问:
Using grep to recursively search through subdirectories for specific keyword inside specific filename
Im trying to look for the text Elapsed time inside a specific log file names vsim.log. Im not familiar with grep, but after some googling I found that grep -r will allow me to do recursively searches and grep -r "Elapsed time" will do recursive searches for that phrase within all files in my directory. According to this link, I can then do grep -r "Elapsed time" ./vsim* to recursively search through the directories for files starting with vsim and look inside those files for Elapsed time. However, when i tried this i get grep: No match. which i know is not true since I know the files exist there with those keywords. What am i messing up?

答:
Try:

```<code>grep -r "Elapsed time" * --include vsim.log
</code>```

Or this answer Use grep --exclude/--include syntax to not grep through certain files.

Body:
Try:

grep -r "Elapsed time" * --include vsim.log

Or this answer Use grep --exclude/--include syntax to not grep through certain files.


问:
making a code that can fill in automatically a list with restrictions
such as the content must be only of ones and zeros with a length of 7 variables and has to be different each time. I am a rookie at python ,at coding in general i know there is a way to do it but my knowledge is limited i really hadn't tried by my own but it because I dont have any clue at all

```<code>def variable_creator:
    auto_variable_list = [None]*7
    content = ['0','1']
    for auto_variable_list in content:
        "auto_variable_list return 7 length with content variables"
</code>```

The output that I expect is

```<code>list1=[0000000]
list2=[1000000]
list3=[0100000]
...
list128=[1111111]
</code>```

not necessarily in that particular order but don't violate this statement for every list needs to be different content for all the 127 list

答:
Use random.choice and a list comprehension:

```<code>import random
choices = [0,1]
[random.choice(choices) for _ in xrange(7)]
[0, 1, 1, 0, 1, 1, 0]
[random.choice(choices) for _ in xrange(7)]
[0, 1, 1, 0, 0, 0, 0]
[random.choice(choices) for _ in xrange(7)]
[1, 0, 0, 0, 1, 1, 1]
</code>```

Body:
such as the content must be only of ones and zeros with a length of 7 variables and has to be different each time. I am a rookie at python ,at coding in general i know there is a way to do it but my knowledge is limited i really hadn't tried by my own but it because I dont have any clue at all

def variable_creator:
    auto_variable_list = [None]*7
    content = ['0','1']
    for auto_variable_list in content:
        "auto_variable_list return 7 length with content variables"

The output that I expect is

list1=[0000000]
list2=[1000000]
list3=[0100000]
...
list128=[1111111]

not necessarily in that particular order but don't violate this statement for every list needs to be different content for all the 127 list

Body:
Use random.choice and a list comprehension:

import random
choices = [0,1]
[random.choice(choices) for _ in xrange(7)]
[0, 1, 1, 0, 1, 1, 0]
[random.choice(choices) for _ in xrange(7)]
[0, 1, 1, 0, 0, 0, 0]
[random.choice(choices) for _ in xrange(7)]
[1, 0, 0, 0, 1, 1, 1]


问:
How to update ms access database with parameters c#
I am trying to update my ms access db with windows application and I am having a hard time. When I run it I don't get any errors but it does update like once or twice when I test it but then doesn't work again if I do it again a third time.

This is the code I use

```<code>Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE TABLE SET c_qty=@qty WHERE id = @ID";

Command.Parameters.AddWithValue("@qty", txtQty.Text);
Command.Parameters.AddWithValue("@ID", txtID.Text);
Command.ExecuteNonQuery();
Conn.Close();
</code>```

I felt I was doing this right or on the right track of having it correct but seems to be more of a issue then I thought. Any help would be great

答:
Quantity and Id are hopefully integers and you should pass them as such.

Also Table is a reserved word, if this really is the name of your table you should enclose it with square brackets.

You should also pass in the correct db types in your parameters and not use AddWithvalue which does not allow this.

Code

```<code>Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE [TABLE] SET c_qty= ? WHERE id = ?";

Command.Parameters.Add(new OleDbParameter("@qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("@ID",  OleDbType.Int) {Value = int.Parse(txtID.Text)});
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
Conn.Close();
</code>```

Finally use using blocks for your Disposables. If you were to get an Exception here then connection would remain open until Garbage collection runs which means you might have a problem with other connection attempts to this Access database.

Revised with using blocks

```<code>using (OleDbConnection Conn = new OleDbConnection("connectionStringHere"))
using (OleDbCommand Command = new OleDbCommand("UPDATE [TABLE] SET c_qty= ? WHERE id = ?", Conn))
{
    Command.Parameters.Add(new OleDbParameter("@qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
    Command.Parameters.Add(new OleDbParameter("@ID",  OleDbType.Int) {Value = int.Parse(txtID.Text)});
    Conn.Open();

    var rowsUpdated = Command.ExecuteNonQuery();
    // output rowsUpdated to the log, should be 1 if id is the PK
}
</code>```

Finally OleDbCommand does not support named parameters, see OleDbCommand.Parameters

Body:
I am trying to update my ms access db with windows application and I am having a hard time. When I run it I don't get any errors but it does update like once or twice when I test it but then doesn't work again if I do it again a third time.

This is the code I use

Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE TABLE SET c_qty=@qty WHERE id = @ID";

Command.Parameters.AddWithValue("@qty", txtQty.Text);
Command.Parameters.AddWithValue("@ID", txtID.Text);
Command.ExecuteNonQuery();
Conn.Close();

I felt I was doing this right or on the right track of having it correct but seems to be more of a issue then I thought. Any help would be great

Body:
Quantity and Id are hopefully integers and you should pass them as such.

Also Table is a reserved word, if this really is the name of your table you should enclose it with square brackets.

You should also pass in the correct db types in your parameters and not use AddWithvalue which does not allow this.

Code

Conn.Open();
Command.CommandType = CommandType.Text;
Command.CommandText ="UPDATE [TABLE] SET c_qty= ? WHERE id = ?";

Command.Parameters.Add(new OleDbParameter("@qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
Command.Parameters.Add(new OleDbParameter("@ID",  OleDbType.Int) {Value = int.Parse(txtID.Text)});
var rowsUpdated = Command.ExecuteNonQuery();
// output rowsUpdated to the log, should be 1 if id is the PK
Conn.Close();

Finally use using blocks for your Disposables. If you were to get an Exception here then connection would remain open until Garbage collection runs which means you might have a problem with other connection attempts to this Access database.

Revised with using blocks

using (OleDbConnection Conn = new OleDbConnection("connectionStringHere"))
using (OleDbCommand Command = new OleDbCommand("UPDATE [TABLE] SET c_qty= ? WHERE id = ?", Conn))
{
    Command.Parameters.Add(new OleDbParameter("@qty", OleDbType.Int) {Value = int.Parse(txtQty.Text)});
    Command.Parameters.Add(new OleDbParameter("@ID",  OleDbType.Int) {Value = int.Parse(txtID.Text)});
    Conn.Open();

    var rowsUpdated = Command.ExecuteNonQuery();
    // output rowsUpdated to the log, should be 1 if id is the PK
}

Finally OleDbCommand does not support named parameters, see OleDbCommand.Parameters


答:
Check out the Topshelf project. It was designed to do exactly this.

http://topshelf-project.com/

Body: How to make your c# app work as windows service? (matereals, todos wanted)


问:
Compare results from two different mysqli_fetch_array with PHP
I created a DB where I am saving information about apps. Those apps can be linked to a vertical. I designed the DB in such way that I have one table for standard information about each application which includes an auto-incremented ID a name etc. I have another table that lists all different industries/verticals.

Except for those 2 tables, I have a third one connecting the two, which looks like this (I'm showing it in a PHP array because I think it's easier to read):

```<code>  $verticals_joint = array(
  array('vertical_joint_id' => '1','vertical_id' => '11','demo_id' => '173'),
  array('vertical_joint_id' => '2','vertical_id' => '12','demo_id' => '173'),
  array('vertical_joint_id' => '3','vertical_id' => '13','demo_id' => '173'),
  array('vertical_joint_id' => '4','vertical_id' => '2','demo_id' => '174'),
  array('vertical_joint_id' => '5','vertical_id' => '4','demo_id' => '174'),
  array('vertical_joint_id' => '6','vertical_id' => '3','demo_id' => '175'),
  array('vertical_joint_id' => '7','vertical_id' => '4','demo_id' => '175'),
  array('vertical_joint_id' => '8','vertical_id' => '8','demo_id' => '176'),
  array('vertical_joint_id' => '9','vertical_id' => '9','demo_id' => '176'),
  array('vertical_joint_id' => '10','vertical_id' => '1','demo_id' => '92'),
  array('vertical_joint_id' => '11','vertical_id' => '3','demo_id' => '92'),
  array('vertical_joint_id' => '12','vertical_id' => '12','demo_id' => '92'),
  array('vertical_joint_id' => '13','vertical_id' => '1','demo_id' => '179'),
  array('vertical_joint_id' => '14','vertical_id' => '3','demo_id' => '179'),
  array('vertical_joint_id' => '15','vertical_id' => '4','demo_id' => '179'),
  array('vertical_joint_id' => '16','vertical_id' => '2','demo_id' => '180'),
  array('vertical_joint_id' => '17','vertical_id' => '4','demo_id' => '180')
);
</code>```

The vertical_id connects the industry/vertical with the application/demo. The demo_id references the application (or demo as I called it).

Now comes my issue. I came up with a while-loop in PHP and I nested an if-statement into it so I can display all verticals and additionally mark which verticals the given application was created for. E.g. this is what I want to achieve:

```<code><select id="Vertical[]" class="form-control verticalText" multiple="multiple">
<option value="1">Education</option>
<option value="2">Manufacturing</option>
<option value="3">State, Local or Provincial Government</option>
<option value="4">Federal Government</option>
<option value="5">Other</option>
<option value="6">Transportation and Logistics</option>
<option value="7">Healthcare</option>
<option value="8">Petrochemical</option>
<option value="9">Utilities</option>
<option value="10">Public Safety</option>
<option value="11" selected>Hospitality</option>
<option value="12" selected>Wholesale Distribution</option>
<option value="13" selected>Human Services</option>
<option value="14">Retail</option>
</code>```

That's what I want to achieve but instead when I use my while loop it only correctly selects Hospitality and doesn't select Wholesale Dist or Human Services.

My while-loop + nested if-statement look like this:

```<code>//Gathers the names of all existing verticals.
$vertical_query  = "SELECT * FROM demos.verticals";
$result_vertical = mysqli_query($con, $vertical_query);
//Gathers information about the particular application you are comparing with.
//It retrieves the verticals for a particular app/demo id.
//For this example I used id 173
$joint_query  = "SELECT o.vertical_id, o.vertical_name FROM demos.alldemos alld
    LEFT JOIN demos.verticals_joint j ON alld.id = j.demo_id
    LEFT JOIN demos.verticals o ON o.vertical_id = j.vertical_id
    WHERE alld.id = 173";
$result_joint = mysqli_query($con, $joint_query);
$compare      = mysqli_fetch_array($result_joint);
$output       = '';
// while there are Verticals to be listed.
while ($row_vertical = mysqli_fetch_array($result_vertical)) {
    // If a vertical is already selected for this particular app id,
    if ($compare['vertical_name'] == $row_vertical["vertical_name"]) {
        //then add the word select to the option so it will be selected
        $output .= '<option value="'.$row_vertical["vertical_id"].'" selected>'.$row_vertical['vertical_name'].'</option>';
    } elseif ($compare['vertical_name'] != $row_vertical["vertical_name"]) {
        //Otherwise just print out the normal option without 'selected'.
        $output .= '<option value="'.$row_vertical["vertical_id"].'">'.$row_vertical["vertical_name"].'</option>';
    }
}
echo $output;
</code>```

Would you know why it only compares the first item from my SQL join against the verticals from my other SELECT query? Would you suggest to do things differently?

答:
In order to check all matching conditions between both queries, you would need to run two loops between the $compare and the $row_vertical arrays. Right now you are only checking all $row_vertical rows to the first row of $compare (i.e., Hospitality). And since values can be overwritten in nested looping, include a break 1 when condition is met:

```<code>while ($row_vertical = mysqli_fetch_array($result_vertical)) {
       while ($compare = mysqli_fetch_array($result_joint)) {

              if ($compare['vertical_name'] == $row_vertical["vertical_name"]) {
                 $output = ...;
                 break 1;
                 ...
       }
}
</code>```

However, nested loops is not needed as you run a LEFT JOIN on the same table where unmatched records will return NULL. Hence, there is no need to run and fetch the redundant first query but just run one $compare query and then check for NULL.

```<code>while ($compare = mysqli_fetch_array($result_joint)) {
    // If a vertical is already selected for this particular app id,
    if (is_null($compare['vertical_name']) == false) {
        //then add the word select to the option so it will be selected
        $output .= '<option value="'.$compare["vertical_id"].'" selected>'.$compare['vertical_name'].'</option>';

    } elseif (is_null($compare['vertical_name']) == true) {
        //Otherwise just print out the normal option without 'selected'.
        $output .= '<option value="'.$compare["vertical_id"].'">'.$compare["vertical_name"].'</option>';

    }
}
</code>```

And Vertical values should not repeat if you keep the WHERE condition on one specific demo_id.

Body:
I created a DB where I am saving information about apps. Those apps can be linked to a vertical. I designed the DB in such way that I have one table for standard information about each application which includes an auto-incremented ID a name etc. I have another table that lists all different industries/verticals.

Except for those 2 tables, I have a third one connecting the two, which looks like this (I'm showing it in a PHP array because I think it's easier to read):

  $verticals_joint = array(
  array('vertical_joint_id' => '1','vertical_id' => '11','demo_id' => '173'),
  array('vertical_joint_id' => '2','vertical_id' => '12','demo_id' => '173'),
  array('vertical_joint_id' => '3','vertical_id' => '13','demo_id' => '173'),
  array('vertical_joint_id' => '4','vertical_id' => '2','demo_id' => '174'),
  array('vertical_joint_id' => '5','vertical_id' => '4','demo_id' => '174'),
  array('vertical_joint_id' => '6','vertical_id' => '3','demo_id' => '175'),
  array('vertical_joint_id' => '7','vertical_id' => '4','demo_id' => '175'),
  array('vertical_joint_id' => '8','vertical_id' => '8','demo_id' => '176'),
  array('vertical_joint_id' => '9','vertical_id' => '9','demo_id' => '176'),
  array('vertical_joint_id' => '10','vertical_id' => '1','demo_id' => '92'),
  array('vertical_joint_id' => '11','vertical_id' => '3','demo_id' => '92'),
  array('vertical_joint_id' => '12','vertical_id' => '12','demo_id' => '92'),
  array('vertical_joint_id' => '13','vertical_id' => '1','demo_id' => '179'),
  array('vertical_joint_id' => '14','vertical_id' => '3','demo_id' => '179'),
  array('vertical_joint_id' => '15','vertical_id' => '4','demo_id' => '179'),
  array('vertical_joint_id' => '16','vertical_id' => '2','demo_id' => '180'),
  array('vertical_joint_id' => '17','vertical_id' => '4','demo_id' => '180')
);

The vertical_id connects the industry/vertical with the application/demo. The demo_id references the application (or demo as I called it).

Now comes my issue. I came up with a while-loop in PHP and I nested an if-statement into it so I can display all verticals and additionally mark which verticals the given application was created for. E.g. this is what I want to achieve:

<select id="Vertical[]" class="form-control verticalText" multiple="multiple">
<option value="1">Education</option>
<option value="2">Manufacturing</option>
<option value="3">State, Local or Provincial Government</option>
<option value="4">Federal Government</option>
<option value="5">Other</option>
<option value="6">Transportation and Logistics</option>
<option value="7">Healthcare</option>
<option value="8">Petrochemical</option>
<option value="9">Utilities</option>
<option value="10">Public Safety</option>
<option value="11" selected>Hospitality</option>
<option value="12" selected>Wholesale Distribution</option>
<option value="13" selected>Human Services</option>
<option value="14">Retail</option>

That's what I want to achieve but instead when I use my while loop it only correctly selects Hospitality and doesn't select Wholesale Dist or Human Services.

My while-loop + nested if-statement look like this:

//Gathers the names of all existing verticals.
$vertical_query  = "SELECT * FROM demos.verticals";
$result_vertical = mysqli_query($con, $vertical_query);
//Gathers information about the particular application you are comparing with.
//It retrieves the verticals for a particular app/demo id.
//For this example I used id 173
$joint_query  = "SELECT o.vertical_id, o.vertical_name FROM demos.alldemos alld
    LEFT JOIN demos.verticals_joint j ON alld.id = j.demo_id
    LEFT JOIN demos.verticals o ON o.vertical_id = j.vertical_id
    WHERE alld.id = 173";
$result_joint = mysqli_query($con, $joint_query);
$compare      = mysqli_fetch_array($result_joint);
$output       = '';
// while there are Verticals to be listed.
while ($row_vertical = mysqli_fetch_array($result_vertical)) {
    // If a vertical is already selected for this particular app id,
    if ($compare['vertical_name'] == $row_vertical["vertical_name"]) {
        //then add the word select to the option so it will be selected
        $output .= '<option value="'.$row_vertical["vertical_id"].'" selected>'.$row_vertical['vertical_name'].'</option>';
    } elseif ($compare['vertical_name'] != $row_vertical["vertical_name"]) {
        //Otherwise just print out the normal option without 'selected'.
        $output .= '<option value="'.$row_vertical["vertical_id"].'">'.$row_vertical["vertical_name"].'</option>';
    }
}
echo $output;

Would you know why it only compares the first item from my SQL join against the verticals from my other SELECT query? Would you suggest to do things differently?

Body:
In order to check all matching conditions between both queries, you would need to run two loops between the $compare and the $row_vertical arrays. Right now you are only checking all $row_vertical rows to the first row of $compare (i.e., Hospitality). And since values can be overwritten in nested looping, include a break 1 when condition is met:

while ($row_vertical = mysqli_fetch_array($result_vertical)) {
       while ($compare = mysqli_fetch_array($result_joint)) {

              if ($compare['vertical_name'] == $row_vertical["vertical_name"]) {
                 $output = ...;
                 break 1;
                 ...
       }
}

However, nested loops is not needed as you run a LEFT JOIN on the same table where unmatched records will return NULL. Hence, there is no need to run and fetch the redundant first query but just run one $compare query and then check for NULL.

while ($compare = mysqli_fetch_array($result_joint)) {
    // If a vertical is already selected for this particular app id,
    if (is_null($compare['vertical_name']) == false) {
        //then add the word select to the option so it will be selected
        $output .= '<option value="'.$compare["vertical_id"].'" selected>'.$compare['vertical_name'].'</option>';

    } elseif (is_null($compare['vertical_name']) == true) {
        //Otherwise just print out the normal option without 'selected'.
        $output .= '<option value="'.$compare["vertical_id"].'">'.$compare["vertical_name"].'</option>';

    }
}

And Vertical values should not repeat if you keep the WHERE condition on one specific demo_id.


问:
How do i change the color of the anchor link in bootstrap's navbar-inverse class
Here's the problem that i'm facing, the color of anchor link in the navbar-inverse class by default is set to a greyish color.

When i make changes in the css, im only able to target the link color when it is active or in focus or when hovered.

The moment i click outside (the link goes out of focus) it changes back to grey.

```<code>    .navbar-inverse .navbar-nav > .active > a,
    .navbar-inverse .navbar-nav > .active > a:hover,
    .navbar-inverse .navbar-nav > .active > a:focus
    {
        background:  aquamarine;
        color: white ;

            }
</code>```

How do i specifically target color attribute of the anchor element when its not active in the navbar ?.

答:
The issue is in the fact that you are specifying an anchor tag with active class, but anchor might not have active class, therefore you are seeing it as grey.

First two blocks are targeting the anchor  tag without the .active class. And the last one that you had in your question, is essentially the same with .active class.

```<code>.navbar-inverse .navbar-nav > li > a {
    color: #fff;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
    color: #fff;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
    color: #fff;
    background: aquamarine;
}
</code>```

Title: How do i change the color of the <a>anchor link in bootstrap's navbar-inverse class

Body:
Here's the problem that i'm facing, the color of anchor link in the navbar-inverse class by default is set to a greyish color.

When i make changes in the css, im only able to target the link color when it is active or in focus or when hovered.

The moment i click outside (the link goes out of focus) it changes back to grey.

    .navbar-inverse .navbar-nav > .active > a,
    .navbar-inverse .navbar-nav > .active > a:hover,
    .navbar-inverse .navbar-nav > .active > a:focus
    {
        background:  aquamarine;
        color: white ;

            }

How do i specifically target color attribute of the anchor element when its not active in the navbar ?.

Body:
The issue is in the fact that you are specifying an anchor tag with active class, but anchor might not have active class, therefore you are seeing it as grey.

First two blocks are targeting the anchor <a> tag without the .active class. And the last one that you had in your question, is essentially the same with .active class.

.navbar-inverse .navbar-nav > li > a {
    color: #fff;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
    color: #fff;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
    color: #fff;
    background: aquamarine;
}


问:
Square Root Of A Number In Python
I created a program where you can either roll a dice or find the square root of a number. These options can be toggled with the numbers 1 and 2. Howvever, whenever I want to find the square root of a number, it gives me the square root of the number I want and the square root of 2. How do I solve this? Code is below:
Please disregard indentation errors as Stack Overflow was giving me a tough time putting the code in.

```<code>from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A
Number, Press 2 "))
    while True:
        if UserInput == 1:
            print (randint(1, 6))

        if UserInput == 2:
            print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))
</code>```

And This is my Result when I want to find the square root of 16:

```<code> To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 2
 What Number Would You Like To Find The Square Root Of? 16
 4.0
 1.4142135623730951
</code>```

答:
The main issue with your code as bad indentation as stated in the comments. In addition, I see no need for an infinite loop as that will either repeatedly roll and repeatedly square root, unless that is your goal.
Here is my code:

```<code>from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 "))
if UserInput == 1:
    print (randint(1, 6))

elif UserInput == 2:
    print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))
</code>```

That is unless you want to repeatedly ask for user input In which case put the while loop above the creation of the User Input variable.

Edit: If you really do want re usability then use def to make this a function and have the following code

```<code>while True:
    play = input("Do you want to play? y/n")
    if play == "y":
        function_name()
    elif play == "n":
        break
</code>```

Title: Square Root Of A Number In Python

Body:
I created a program where you can either roll a dice or find the square root of a number. These options can be toggled with the numbers 1 and 2. Howvever, whenever I want to find the square root of a number, it gives me the square root of the number I want and the square root of 2. How do I solve this? Code is below:
Please disregard indentation errors as Stack Overflow was giving me a tough time putting the code in.

from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A
Number, Press 2 "))
    while True:
        if UserInput == 1:
            print (randint(1, 6))

        if UserInput == 2:
            print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))

And This is my Result when I want to find the square root of 16:

 To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 2
 What Number Would You Like To Find The Square Root Of? 16
 4.0
 1.4142135623730951

Body:
The main issue with your code as bad indentation as stated in the comments. In addition, I see no need for an infinite loop as that will either repeatedly roll and repeatedly square root, unless that is your goal.
Here is my code:

from random import randint
import math

UserInput = int(input("To Roll A Dice, Type One. To Find The Square Root Of A Number, Press 2 "))
if UserInput == 1:
    print (randint(1, 6))

elif UserInput == 2:
    print(math.sqrt(int(input("What Number Would You Like To Find The Square Root Of? "))))

That is unless you want to repeatedly ask for user input In which case put the while loop above the creation of the User Input variable.

Edit: If you really do want re usability then use def to make this a function and have the following code

while True:
    play = input("Do you want to play? y/n")
    if play == "y":
        function_name()
    elif play == "n":
        break


问:
Rails 5 and Ruby 2.3.3 Failed to load libmysql.dll
Getting below error message logged in the console while starting the server for an application created with mysql database.

```<code>Failed to load libmysql.dll from C:\RailsInstaller\Ruby2.3.0\lib\ruby\gems\2.3.0\gems\mysql2-0.4.7-x86-mingw32\vendor\libmysql.dll
</code>```

Environment Details :

```<code>Window 7 64 bit
Rails 5.0.4
ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]
mysqld  Ver 5.7.18 for Win64 on x86_64 (MySQL Community Server (GPL))
</code>```

Post install message from mysql2 ruby gem received below message on the console.

```<code>You've installed the binary version of mysql2.
It was built using MySQL Connector/C version 6.1.10.
It's recommended to use the exact same version to avoid potential issues.

At the time of building this gem, the necessary DLL files were retrieved from:
http://cdn.mysql.com/Downloads/Connector-C/mysql-connector-c-6.1.10-win32.zip

This gem *includes* vendor/libmysql.dll with redistribution notice in vendor/README.
</code>```

I have tried the solution from here but did not work.

Any help appreciated, thanks in advance.

答:
Downgrading mysql2 rubygem from version 0.4.7 to 0.3.21 solved my issue.

Below steps I followed

```<code>rails new blog -d mysql # created application with mysql as database
gem uninstall mysql2 #uninstalled mysql2-0.4.7
Gemfile :
    gem 'mysql2', '0.3.21' #Gemfile changed mysql2 version to 0.3.21
bundle update mysql2 #installed mysql2-0.3.21 version
</code>```

Body:
Getting below error message logged in the console while starting the server for an application created with mysql database.

Failed to load libmysql.dll from C:\RailsInstaller\Ruby2.3.0\lib\ruby\gems\2.3.0\gems\mysql2-0.4.7-x86-mingw32\vendor\libmysql.dll

Environment Details :

Window 7 64 bit
Rails 5.0.4
ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]
mysqld  Ver 5.7.18 for Win64 on x86_64 (MySQL Community Server (GPL))

Post install message from mysql2 ruby gem received below message on the console.

You've installed the binary version of mysql2.
It was built using MySQL Connector/C version 6.1.10.
It's recommended to use the exact same version to avoid potential issues.

At the time of building this gem, the necessary DLL files were retrieved from:
http://cdn.mysql.com/Downloads/Connector-C/mysql-connector-c-6.1.10-win32.zip

This gem *includes* vendor/libmysql.dll with redistribution notice in vendor/README.

I have tried the solution from here but did not work.

Any help appreciated, thanks in advance.

Body:
Downgrading mysql2 rubygem from version 0.4.7 to 0.3.21 solved my issue.

Below steps I followed

rails new blog -d mysql # created application with mysql as database
gem uninstall mysql2 #uninstalled mysql2-0.4.7
Gemfile :
    gem 'mysql2', '0.3.21' #Gemfile changed mysql2 version to 0.3.21
bundle update mysql2 #installed mysql2-0.3.21 version


问:
How to sort the following array of objects and strings?
I have the following:

```<code>myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]
</code>```

What is the best way to sort the list such that strings are in the front, and objects come after?

```<code>["Abigail", "Kelsey", {'name':'Adam'}, {'name': 'Jennifer'}, {'name': 'Jorden'}]
</code>```

答:
var myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]

var result = myitems.sort(function(a,b) {
  if(typeof a === 'string' && typeof b === 'object')
    return -1;
  else if(typeof a === 'object' && typeof b === 'string')
    return 1;
  else if(typeof a === 'string' && typeof b === 'string')
    return a.localeCompare(b);
  else
    return a.name.localeCompare(b.name);

});
console.log(result);```

Body:
I have the following:

myitems = [{'name': 'Jorden'},"Kelsey", "Abigail", {'name': 'Jennifer'}, {'name':'Adam'}]

What is the best way to sort the list such that strings are in the front, and objects come after?

["Abigail", "Kelsey", {'name':'Adam'}, {'name': 'Jennifer'}, {'name': 'Jorden'}]


问:
Can't Return Integer Array in Excel VBA
I was just having a similar problem with a String array and now that's working but this isnt. I tried returning an Integer array as Integer() type and as Variant() and looping through and converting each element with Cint(). I get a type mismatch either way. Here is the code:

```<code>Dim pathTimeList() As Integer
ReDim pathTimeList(0 To stepCount)
pathTimeList = set_path_time_list(stepCount)
</code>```

Here is the function code:

```<code>Private Function set_path_time_list(ByVal stepCount As Integer) As Integer

    Dim pathTimeList() As Integer
    ReDim pathTimeList(0 To stepCount - 1)

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 3
    lastRow = 27
    firstColumn = 2
    lastColumn = 2

    For i = firstRow To lastRow

        For j = firstColumn To lastColumn

            pathTimeList(loopIndex) = Cells(i, j).Value

        Next j

        loopIndex = loopIndex + 1

    Next i

    set_path_time = pathTimeList

End Function
</code>```

答:
First, to make the function return an array of integers, in the function declaration follow the return type with () to indicate an array:

```<code>Private Function set_path_time_list(ByVal stepCount As Integer) As Integer()
</code>```

Second, change the last statement to:

```<code>set_path_time_list = pathTimeList
</code>```

A couple of optional clean-up items. After the last statement consider deallocating the storage you got with Redim:

```<code>Erase pathTimeList
</code>```

Finally, you should declare i and j as Integer or Long.

Hope that helps

Title: Can't Return Integer Array in Excel VBA

Body:
I was just having a similar problem with a String array and now that's working but this isnt. I tried returning an Integer array as Integer() type and as Variant() and looping through and converting each element with Cint(). I get a type mismatch either way. Here is the code:

Dim pathTimeList() As Integer
ReDim pathTimeList(0 To stepCount)
pathTimeList = set_path_time_list(stepCount)

Here is the function code:

Private Function set_path_time_list(ByVal stepCount As Integer) As Integer

    Dim pathTimeList() As Integer
    ReDim pathTimeList(0 To stepCount - 1)

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 3
    lastRow = 27
    firstColumn = 2
    lastColumn = 2

    For i = firstRow To lastRow

        For j = firstColumn To lastColumn

            pathTimeList(loopIndex) = Cells(i, j).Value

        Next j

        loopIndex = loopIndex + 1

    Next i

    set_path_time = pathTimeList

End Function

Body:
First, to make the function return an array of integers, in the function declaration follow the return type with () to indicate an array:

Private Function set_path_time_list(ByVal stepCount As Integer) As Integer()

Second, change the last statement to:

set_path_time_list = pathTimeList

A couple of optional clean-up items. After the last statement consider deallocating the storage you got with Redim:

Erase pathTimeList

Finally, you should declare i and j as Integer or Long.

Hope that helps


问:
T-SQL Find Pairs Where at Least one Member has Two or More Pairs with Different Members
I have a dataset with two columns:

```<code>source          target
Michael Scott   Kelly Kapoor
Jim Halpert     Pam Beasley
Jim Halpert     Pam Beasley
Dwight Schrute  Angela
Angela          Dwight Schrute
Erin            Meredith
Erin            Meredith
Kevin Malone    Stanley Hudson
Kevin Malone    Ryan Howard
Pam Beasley     Oscar
</code>```

I want to find the rows that include at least one member who has multiple pairs with at least two different members. So, the end result should return:

```<code>source          target
Jim Halpert     Pam Beasley
Jim Halpert     Pam Beasley
Kevin Malone    Stanley Hudson
Kevin Malone    Ryan Howard
Pam Beasley     Oscar
</code>```

Michael --> Kelly is removed because neither has any other links
Dwight Schrute --> Angela and Angela --> Dwight Schrute are removed because, although there are multiple links, the links are between the same members.
Erin --> Meredith and Erin --> Meredith are removed because, again, the links are between the same members (although in the same direction).

I know how to find distinct links that involve the same members in either direction:

```<code>select source
      ,target
from dbo.networktest
group by source, target
having count(*) > 1
union
select b.source
      ,b.target
from dbo.networktest a
left outer join dbo.networktest b on a.source = b.target and a.target = b.source
where b.source is not null and b.target is not null
</code>```

How would I change (or scrap/rebuild) that to accomplish my objective? Thank you for any insight you all might have! If I can make my question more clear, please let me know.

答:
I think exists does wha tyou want:

```<code>select nt.*
from networktest nt
where exists (select 1
              from networktest nt2
              where nt2.source in (nt.source, nt.target) and
                    nt2.target not in (nt.source, nt.target)
             ) or
      exists (select 1
              from networktest nt2
              where nt2.target in (nt.source, nt.target) and
                    nt2.source not in (nt.source, nt.target)
             );
</code>```

Body:
I have a dataset with two columns:

source          target
Michael Scott   Kelly Kapoor
Jim Halpert     Pam Beasley
Jim Halpert     Pam Beasley
Dwight Schrute  Angela
Angela          Dwight Schrute
Erin            Meredith
Erin            Meredith
Kevin Malone    Stanley Hudson
Kevin Malone    Ryan Howard
Pam Beasley     Oscar

I want to find the rows that include at least one member who has multiple pairs with at least two different members. So, the end result should return:

source          target
Jim Halpert     Pam Beasley
Jim Halpert     Pam Beasley
Kevin Malone    Stanley Hudson
Kevin Malone    Ryan Howard
Pam Beasley     Oscar

Michael --> Kelly is removed because neither has any other links
Dwight Schrute --> Angela and Angela --> Dwight Schrute are removed because, although there are multiple links, the links are between the same members.
Erin --> Meredith and Erin --> Meredith are removed because, again, the links are between the same members (although in the same direction).

I know how to find distinct links that involve the same members in either direction:

select source
      ,target
from dbo.networktest
group by source, target
having count(*) > 1
union
select b.source
      ,b.target
from dbo.networktest a
left outer join dbo.networktest b on a.source = b.target and a.target = b.source
where b.source is not null and b.target is not null

How would I change (or scrap/rebuild) that to accomplish my objective? Thank you for any insight you all might have! If I can make my question more clear, please let me know.

Body:
I think exists does wha tyou want:

select nt.*
from networktest nt
where exists (select 1
              from networktest nt2
              where nt2.source in (nt.source, nt.target) and
                    nt2.target not in (nt.source, nt.target)
             ) or
      exists (select 1
              from networktest nt2
              where nt2.target in (nt.source, nt.target) and
                    nt2.source not in (nt.source, nt.target)
             );


问:
Excel VBA: Storing the Value of One Cell in a Variable if a Certain Value Exists in the Same Column
I'm trying to determine how to store the value of a cell in a variable if a certain value exists in the same column. See the explanation below:

Example Table

So for example, I have a database storing whether an individual enjoys a certain fruit or not. What I want to happen is that for each person, going row by row in myRange (where myRange = "B" i & ":E" & i) if the cell is = Chr(13) & Chr(7) then store the value of the header in a variable (i.e. "Apple", "Grape", Banana", "Orange").

This is what I have right now as a snippet:

```<code>For i = 7 To iLastRow
    Set oCell = myRange.Find(What:=Chr(13) & Chr(7), LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, :=False, SearchFormat:=False)

    If oCell = Chr(13) & Chr(7) Then
        value = "DONT KNOW WHAT TO PUT HERE BUT IT WILL REFERENCE TO THE
                ITEMS 'Apple', 'Grape','Banana', 'Orange' DEPENDING ON WHICH
                COLUMN THE BLANK IS FOUND IN"
        sTemp = sTemp & "," & value
    Else
        Set oCell = Nothing
    End If
Next i
sTemp = Mid(sTemp, 2)
</code>```

答:
Check this out dude, i think this will help you figure out your issue</p>

```<code>Private Sub this()
    Dim arr As Variant, strPerson As String, strFruit As String
    arr = ThisWorkbook.Sheets("Sheet1").UsedRange
    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, 1) <> arr(1, 1) Then
                If arr(i, j) = arr(i, 1) Then strPerson = arr(i, j)
                If arr(i, j) <> arr(i, 1) Then
                    If arr(i, j) = "y" Then
                        strFruit = arr(1, j)
                        strPerson = strPerson & strFruit
                    End If
                End If
            End If
        Next j
        Debug.Print ; strPerson
    Next i
End Sub
</code>```

Body:
I'm trying to determine how to store the value of a cell in a variable if a certain value exists in the same column. See the explanation below:

Example Table

So for example, I have a database storing whether an individual enjoys a certain fruit or not. What I want to happen is that for each person, going row by row in myRange (where myRange = "B" i & ":E" & i) if the cell is = Chr(13) & Chr(7) then store the value of the header in a variable (i.e. "Apple", "Grape", Banana", "Orange").

This is what I have right now as a snippet:

For i = 7 To iLastRow
    Set oCell = myRange.Find(What:=Chr(13) & Chr(7), LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, :=False, SearchFormat:=False)

    If oCell = Chr(13) & Chr(7) Then
        value = "DONT KNOW WHAT TO PUT HERE BUT IT WILL REFERENCE TO THE
                ITEMS 'Apple', 'Grape','Banana', 'Orange' DEPENDING ON WHICH
                COLUMN THE BLANK IS FOUND IN"
        sTemp = sTemp & "," & value
    Else
        Set oCell = Nothing
    End If
Next i
sTemp = Mid(sTemp, 2)

Body:
Check this out dude, i think this will help you figure out your issue

Private Sub this()
    Dim arr As Variant, strPerson As String, strFruit As String
    arr = ThisWorkbook.Sheets("Sheet1").UsedRange
    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, 1) <> arr(1, 1) Then
                If arr(i, j) = arr(i, 1) Then strPerson = arr(i, j)
                If arr(i, j) <> arr(i, 1) Then
                    If arr(i, j) = "y" Then
                        strFruit = arr(1, j)
                        strPerson = strPerson & strFruit
                    End If
                End If
            End If
        Next j
        Debug.Print ; strPerson
    Next i
End Sub


问:
How to set a font family to an entire Word document in Apache POI XWPF
Is there a way to set a default font family to a word document generated by Apache POI instead of setting the font family to each XWPFRun?

答:
I created a new method

```<code>public static XWPFRun createRun(XWPFParagraph paragraph, String     fontFamily, int fontSize, boolean bold, UnderlinePatterns underline){
    XWPFRun run = paragraph.createRun();
    run.setFontFamily(fontFamily);
    run.setBold(bold);
    run.setUnderline(underline);
    run.setFontSize(fontSize);
    return run;
}
</code>```

Then I call it like that:

```<code>XWPFParagraph paragraphHeader = document.createParagraph();
XWPFRun runTextHeader = createRun(paragraphHeader, WordStyling.FONT_FAMILY_TIMES, WordStyling.FONT_SIZE_14);
</code>```

or more generic:

```<code>public static XWPFRun createRun(XWPFParagraph paragraph){
    XWPFRun run = paragraph.createRun();
    run.setFontSize(12);
    run.setFontFamily("Times New Roman");
    return run;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a new method

public static XWPFRun createRun(XWPFParagraph paragraph, String     fontFamily, int fontSize, boolean bold, UnderlinePatterns underline){
    XWPFRun run = paragraph.createRun();
    run.setFontFamily(fontFamily);
    run.setBold(bold);
    run.setUnderline(underline);
    run.setFontSize(fontSize);
    return run;
}

Then I call it like that:

XWPFParagraph paragraphHeader = document.createParagraph();
XWPFRun runTextHeader = createRun(paragraphHeader, WordStyling.FONT_FAMILY_TIMES, WordStyling.FONT_SIZE_14);

or more generic:

public static XWPFRun createRun(XWPFParagraph paragraph){
    XWPFRun run = paragraph.createRun();
    run.setFontSize(12);
    run.setFontFamily("Times New Roman");
    return run;
}


问:
What event listener should I use to tie my select menu to my calendar and how?
I'm writing a calendar using Javascript, and I can't figure out how to tie my select menu to my calendar. There are two select menus, one for choosing months, the other for years. By default, the calendar shows the current month and year, but when the user selects something from the drop down menu it should change the calendar to the selected date.

After searching the web and trying all the methods that I found, nothing has yet worked for me.

```<code>function listenMonths() {
    let select = document.getElementById('months');
/*
    select.onchange = changeEventHandler('change');

    function changeEventHandler(event) {
        currentMonth = this; // event.target.value;
    }
*/
    select.addEventListener('change', function() {
        currentMonth = this;
    })
}
</code>```

Above is a piece of my code, the listener for Months' select menu. The commented out piece is the second method from MDN.

I'm stuck and I'd really appreciate any help. Thanks.

答:
Assuming you're calling listenMonths() at the appropriate time, what you've posted should work, but it depends on what you want currentMonth to be set to; in this context, this may not be what you're looking for. this.value will return the value you've assigned to the options in your select menu.

This JSfiddle works for me. Feel free to post more of your code if it doesn't address your problem.

Body:
I'm writing a calendar using Javascript, and I can't figure out how to tie my select menu to my calendar. There are two select menus, one for choosing months, the other for years. By default, the calendar shows the current month and year, but when the user selects something from the drop down menu it should change the calendar to the selected date.

After searching the web and trying all the methods that I found, nothing has yet worked for me.

function listenMonths() {
    let select = document.getElementById('months');
/*
    select.onchange = changeEventHandler('change');

    function changeEventHandler(event) {
        currentMonth = this; // event.target.value;
    }
*/
    select.addEventListener('change', function() {
        currentMonth = this;
    })
}

Above is a piece of my code, the listener for Months' select menu. The commented out piece is the second method from MDN.

I'm stuck and I'd really appreciate any help. Thanks.


问:
How can I account for lost time in a while loop when using time.sleep
```<code>import time

def get_time():
    global time_elapsed
    time_elapsed = 0
    time_elapsed = time.time() - last_time
    return time_elapsed

def gear_encoder():
    global gear_counter, run_counter,encoder_running, sensor_state,last_time
    gear_counter = 0
    run_counter = 0
    encoder_running = False
    sensor_state = False

    encoder_running = True

    while encoder_running:
        last_time = time.time()
        if run_counter >= 320:
            print("END")
            break
        if sensor_state == True and gear_counter <= 5:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter += 1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/24) - get_time())

        elif sensor_state == False and gear_counter <= 5:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter += 1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/24) - get_time())

        elif sensor_state == True and gear_counter <= 8:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter +=1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/72) - get_time())

        elif sensor_state == False and gear_counter <= 8:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter +=1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/72) - get_time())

        else:
            gear_counter = 0

start_time = time.time()

gear_encoder()

end_time = time.time() - start_time

print("The sensor changed states " + str(run_counter) + " times")
print(str(end_time))
</code>```

So this is the code that I've got so far. If it runs this is it's output.

```<code>END
The sensor changed states 320 times
10.504526853561401
</code>```

So what I attempted to set up was function called get_time() that will find the difference in time from when the variable last_time is called to when the actual function is called. The goal of this was to account for the time it takes to change the sensor_state and add to the counter variables in the sleep function.

You could do the math yourself but when this loops through 320 times all the time.sleeps that the program runs through add up to 10 seconds. I want the program to end in as close to 10 seconds as possible which is why I tried to account for the extra time with the get_time() function by subtracting the time it took to change sensor state and add to the counters.

My question to you all is, do you know of any methods that could help me lower this time drift? Was my technique to account for lost time even a valid approach? I would like to at some point add variables as arguments into time.sleep and probably lower the sleep to even smaller values than (1.0/72) seconds. Might multi threading be an option here? Any input would be appreciated.

答:
The answer I'd give in code is pretty extensive. Let's see if I can get you on the path. You probably don't want to use sleep, because it blocks and everything becomes serial. That's important because you stated you want to exit in as close to 10 seconds as possible. That's fairly straightforward, if you don't have blocking calls going on. The other timers can be set up similarly. I show some examples below. Set up a timer to exit in 10 seconds. Note that the timer that is set for 11 seconds will not occur because the exit occurs before it triggers. This must be run as a script -- not interactively.</p>

```<code>import sched, time, sys

def myExit():
    # Do stuff here
    sys.exit()

s = sched.scheduler(time.time, time.sleep)
# This causes the program to exit...
s.enter(10, 1, myExit, ())
s.enter(2.0/5, 2, print_answer, (1,))
s.enter(3.0/5, 2, print_answer, (2,))
s.enter(11, 2, print_answer, (3,))
s.run()
</code>```

Body:
import time

def get_time():
    global time_elapsed
    time_elapsed = 0
    time_elapsed = time.time() - last_time
    return time_elapsed

def gear_encoder():
    global gear_counter, run_counter,encoder_running, sensor_state,last_time
    gear_counter = 0
    run_counter = 0
    encoder_running = False
    sensor_state = False

    encoder_running = True

    while encoder_running:
        last_time = time.time()
        if run_counter >= 320:
            print("END")
            break
        if sensor_state == True and gear_counter <= 5:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter += 1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/24) - get_time())

        elif sensor_state == False and gear_counter <= 5:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter += 1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/24) - get_time())

        elif sensor_state == True and gear_counter <= 8:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter +=1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/72) - get_time())

        elif sensor_state == False and gear_counter <= 8:
            sensor_state = not sensor_state
            gear_counter += 1
            run_counter +=1
            #print("State is " + str(sensor_state))
            time.sleep((1.0/72) - get_time())

        else:
            gear_counter = 0

start_time = time.time()

gear_encoder()

end_time = time.time() - start_time

print("The sensor changed states " + str(run_counter) + " times")
print(str(end_time))

So this is the code that I've got so far. If it runs this is it's output.

END
The sensor changed states 320 times
10.504526853561401

So what I attempted to set up was function called get_time() that will find the difference in time from when the variable last_time is called to when the actual function is called. The goal of this was to account for the time it takes to change the sensor_state and add to the counter variables in the sleep function.

You could do the math yourself but when this loops through 320 times all the time.sleeps that the program runs through add up to 10 seconds. I want the program to end in as close to 10 seconds as possible which is why I tried to account for the extra time with the get_time() function by subtracting the time it took to change sensor state and add to the counters.

My question to you all is, do you know of any methods that could help me lower this time drift? Was my technique to account for lost time even a valid approach? I would like to at some point add variables as arguments into time.sleep and probably lower the sleep to even smaller values than (1.0/72) seconds. Might multi threading be an option here? Any input would be appreciated.

Body:
The answer I'd give in code is pretty extensive. Let's see if I can get you on the path. You probably don't want to use sleep, because it blocks and everything becomes serial. That's important because you stated you want to exit in as close to 10 seconds as possible. That's fairly straightforward, if you don't have blocking calls going on. The other timers can be set up similarly. I show some examples below. Set up a timer to exit in 10 seconds. Note that the timer that is set for 11 seconds will not occur because the exit occurs before it triggers. This must be run as a script -- not interactively.

import sched, time, sys

def myExit():
    # Do stuff here
    sys.exit()

s = sched.scheduler(time.time, time.sleep)
# This causes the program to exit...
s.enter(10, 1, myExit, ())
s.enter(2.0/5, 2, print_answer, (1,))
s.enter(3.0/5, 2, print_answer, (2,))
s.enter(11, 2, print_answer, (3,))
s.run()


问:
How to wrap a function with a varying number of default arguments to have only one argument?
I have a template function, let's call it the "client":

```<code>template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
</code>```

Then there are a number of "adaptee" functions that all have an identical type of the first, non-default argument, but the following arguments vary in number and have default values:

```<code>void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
</code>```

The above functions are a given. Now what I want to do is to pass them to the above client<>() function as the first parameter, and I only care about passing the first argument, const std::string&. So I do the following:

```<code>void bindAdapteeOne(const std::string& s) {
    return adaptee_one(s);
}

void bindAdapteeTwo(const std::string& s) {
    return adaptee_two(s);
}
</code>```

And then pass bindAdapteeX() to client<>().

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee. I feel this might be the case for variadics, but have little idea about how to apply them exactly.

C++11 is fine, C++14 is fine if absolutely necessary.

答:
C++11 is fine, C++14 is fine if absolutely necessary.

C++11 solution here.

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee.

I wouldn't do that. You can simply use non-capturing lambdas and let them decay to function pointers:

```<code>client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
</code>```

I don't think that wrapping them in template stuff or whatever would give you a solution that is more readable or easy to use.

As a minimal, working example:

```<code>#include<string>

template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}

void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}

int main() {
    client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
}
</code>```

Body:
I have a template function, let's call it the "client":

template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}

Then there are a number of "adaptee" functions that all have an identical type of the first, non-default argument, but the following arguments vary in number and have default values:

void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}

The above functions are a given. Now what I want to do is to pass them to the above client<>() function as the first parameter, and I only care about passing the first argument, const std::string&. So I do the following:

void bindAdapteeOne(const std::string& s) {
    return adaptee_one(s);
}

void bindAdapteeTwo(const std::string& s) {
    return adaptee_two(s);
}

And then pass bindAdapteeX() to client<>().

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee. I feel this might be the case for variadics, but have little idea about how to apply them exactly.

C++11 is fine, C++14 is fine if absolutely necessary.

Body:
C++11 is fine, C++14 is fine if absolutely necessary.

C++11 solution here.

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee.

I wouldn't do that. You can simply use non-capturing lambdas and let them decay to function pointers:

client (+[](const std::string& s) { return adaptee_one(s); }, "foo");

I don't think that wrapping them in template stuff or whatever would give you a solution that is more readable or easy to use.

As a minimal, working example:

#include<string>

template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}

void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}

int main() {
    client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
}


问:
Flex: Hide (or Remove) Label Text without Changing the Button Size
I have a button with variable-length of label text.  I have a User Setting that can turn on or off the label text on this button.

How can I implement this?

NOTE: the button's background has a gradient color.

I tried using BlendMode.LAYER, no luck;

I tried using Button.resizeHandler

```<code>    private function resizeHandler(event:ResizeEvent):void
    {
        if (event.oldWidth > this.width)
            this.width = event.oldWidth;
        if (event.oldHeight > this.height)
            this.height = event.oldHeight;
    }
</code>```

but it only worked if the initial UserSetting value is true.

How about embedded font? I don't know how to apply it to button

答:
What happens if you just set the button's width?  That way, it should be a constant width no matter what you set as the label.

Most likely width is being calculated in the updateDisplayList method.  So, code in your resize handler may be being reset at the next render event.

Body:
I have a button with variable-length of label text.  I have a User Setting that can turn on or off the label text on this button.

How can I implement this?

NOTE: the button's background has a gradient color.

I tried using BlendMode.LAYER, no luck;

I tried using Button.resizeHandler

    private function resizeHandler(event:ResizeEvent):void
    {
        if (event.oldWidth > this.width)
            this.width = event.oldWidth;
        if (event.oldHeight > this.height)
            this.height = event.oldHeight;
    }

but it only worked if the initial UserSetting value is true.

How about embedded font? I don't know how to apply it to button


问:
How to enable LocalStorage on iOS Safari browser on private mode?
I am working on project SPA angular app which requires localstorage of browser to store values. We came to notice that iOS doesn't allow to access localstorage on private mode.

We fixed the issue by checking the browser compatibility for localstorage. If it's not allowing local storage we use $rootScope object of AngularJS to store values temporarily.

Only challenge of this approach is when page is refreshed data will be cleared which make sense as we are using $rootScope which will be destroyed upon page refresh

Here are my questions:

Is their any way to enable localstorage through javascript?

Is their any better alternative approach? Ideally we want to retain values upon page refresh. How's that possible? (Is it good to use localstorage)

Thanks,
Gokul

答:
Try using cookies instead.

$cookies provides a standard api of getters and setters.

Here is an example of how to use them:

```<code>angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);
</code>```

And here is the full list of methods:

Methods

```<code>get(key);
</code>```

Returns the value of given cookie key

```<code>getObject(key);
</code>```

Returns the deserialized value of given cookie key

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

Returns a key value object with all the cookies

```<code>put(key, value, [options]);
</code>```

Sets a value for given cookie key

```<code>putObject(key, value, [options]);
</code>```

Serializes and sets a value for given cookie key

```<code>remove(key, [options]);
</code>```

Remove given cookie

Body:
Try using cookies instead.

$cookies provides a standard api of getters and setters.

Here is an example of how to use them:

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);

And here is the full list of methods:

Methods

get(key);

Returns the value of given cookie key

getObject(key);

Returns the deserialized value of given cookie key

getAll();

Returns a key value object with all the cookies

put(key, value, [options]);

Sets a value for given cookie key

putObject(key, value, [options]);

Serializes and sets a value for given cookie key

remove(key, [options]);

Remove given cookie


问:
Regular expression in Scala
I want to extract a word from a string and then use that word in my regex.

My string looks like this:

```<code> val s = "null_eci_count"
</code>```

I want to derive the below string from the above string:

```<code>sum(cast((eci is null or eci in ('', '0', 'null', 'NULL')) as int))
</code>```

I used replaceAll and had derived a part of the above expression:

```<code>scala> s.replaceAll("null_", "sum(cast((").replaceAll("_count"," is null) as int))")
res69: String = sum(cast((eci is null) as int))
</code>```

Please suggest a way to derive the whole expression.

答:
How about:</p>

```<code>val eci = s.split("_").drop(1).head
val result = s match {s"sum(cast(($eci is null or $eci in ('', '0', 'null', 'NULL')) as int))"
</code>```

Title: Regular expression in Scala

Body:
I want to extract a word from a string and then use that word in my regex.

My string looks like this:

 val s = "null_eci_count"

I want to derive the below string from the above string:

sum(cast((eci is null or eci in ('', '0', 'null', 'NULL')) as int))

I used replaceAll and had derived a part of the above expression:

scala> s.replaceAll("null_", "sum(cast((").replaceAll("_count"," is null) as int))")
res69: String = sum(cast((eci is null) as int))

Please suggest a way to derive the whole expression.

Body:
How about:

val eci = s.split("_").drop(1).head
val result = s match {s"sum(cast(($eci is null or $eci in ('', '0', 'null', 'NULL')) as int))"


问:
Making permutations in string based on a pattern
Input List: (only if index[1] is having / )

```<code>['A', 'dog,big/small;rat,big/small', '12', '21']
</code>```

Return List:

```<code>['A', 'dog,big;rat,big', '12', '21']
['A', 'dog,small;rat,big', '12', '21']
['A', 'dog,big;rat,small', '12', '21']
['A', 'dog,small;rat,small', '12', '21']
</code>```

答:
This one should work for general input-strings of that type:</p>

```<code>def permute(s):
    a, b = s.split(',')
    return [a + "," + c for c in b.split('/')]

def traverse(s):
    parts = s.split(';', 1)
    if len(parts) == 1:
        return permute(s)
    else:
        return sum([[k + ';' + l for l in traverse(parts[1])] for k in permute(parts[0])], [])

for s in traverse('dog,big/small;rat,big/small'):
    print ['A', s, '12', '21']
</code>```

Body:
Input List: (only if index[1] is having / )

['A', 'dog,big/small;rat,big/small', '12', '21']

Return List:

['A', 'dog,big;rat,big', '12', '21']
['A', 'dog,small;rat,big', '12', '21']
['A', 'dog,big;rat,small', '12', '21']
['A', 'dog,small;rat,small', '12', '21']

Body:
This one should work for general input-strings of that type:

def permute(s):
    a, b = s.split(',')
    return [a + "," + c for c in b.split('/')]

def traverse(s):
    parts = s.split(';', 1)
    if len(parts) == 1:
        return permute(s)
    else:
        return sum([[k + ';' + l for l in traverse(parts[1])] for k in permute(parts[0])], [])

for s in traverse('dog,big/small;rat,big/small'):
    print ['A', s, '12', '21']


答: Select the middle part of the string as a group (i.e. eci) .*?_(.*?)_.* and then return eci with the group reference \1.

Title: Regular expression in Scala


问:
Is there a way to retrieve multi-channel funnel data from google reporting v4 api?
Is there any multichannel funnel querying capabilities in reporting v4 API?

Any documentation I find is on obsolete "v3" Multi-channel API, and I wonder whether it makes sense using it, or there is some new alternative in v4 reporting API?

答: No. The MFC v3 api is far from obsolete or even deprecated. The Analytics reporting API V4 only replaces the Core Reporting API V3. Other parts of the Analytics V3 API, such as the Management API, are still being actively maintained.</p>


问:
App from Xcode works great, but App Store version freezes on load
Has anyone ever heard of this? I'm baffled, and so is Google.

When debugging on iPhone 4 with iOS 4.1, my app shows the splash screen, then shows an animation while it loads and gets the GPS location, and finally goes to the main menu. When I download it from the App Store, it never stops loading. More strange than that, if I hide the forever-loading-app and then restore it, the load animation freezes and the app no longer responds!

I've been trying to make all kinds of guesses about what's going wrong, but nothing is working. How can I get useful information about this failure?

EDIT: App has also been tested on iPhone 3 with iOS 4.0 and iOS 4.2.1, and iPhone 4 with iOS 4.0.2 and 4.2.1.

EDIT EDIT: The problem does not occur if I do not download it from the app store. This makes it extremely difficult to debug, but hopefully narrows it down for somebody out there with more experience than I have.

答:
I agree with Taxman.

First, make sure you tested on different devices with different iOS.

Second, make sure if your app has to connect to servers, those servers are responding in the way you expected.

Third, based on my experience, make sure you tested you app using the Ad Hoc .mobileprovision file other than the Development .mobileprovision file. Xcode will treat binaries differently when compiling.


问:
Use BeautifulSoup to extract table formatted with
 tags
I have an HTML table formatted like this:

```<code><p>
  <strong>A</strong>1<br/>
  <strong>B</strong>2<br/>
</p>
</code>```

I want to use BeautifulSoup to read this into a dictionary of the format {'A': '1', 'B': '2'}. What's the best way to do this? I managed to do something hacky:

```<code>g = list(soup.find('p').childGenerator())
# g == [<strong>A</strong>, '1', <br/>, <strong>B</strong>, '2', </br>]
table = {g[3*i]: g[3*i+1] for i in range(int(len(g)/3))}
</code>```

But this feels vulnerable to slight variations in the table's formation. Is there a better or more canonical way?

答:
I believe the content you posted here is dummy, I'm unsure of your exact requirement. Here is the code you need as per your requirement.</p>

```<code>text_content = [x for x in soup.text.split('\n') if x]
some_dict = {}
i = 0
for abc in soup.find_all('strong'):
    some_dict[abc.text] = text_content[i].replace(abc.text, '')
    i += 1

print(some_dict)

>> {'A': '1', 'B': '2'}
</code>```

Title: Use BeautifulSoup to extract table formatted with <br/> tags

Body:
I have an HTML table formatted like this:

  A1

  B2

I want to use BeautifulSoup to read this into a dictionary of the format {'A': '1', 'B': '2'}. What's the best way to do this? I managed to do something hacky:

g = list(soup.find('p').childGenerator())
# g == [A, '1',
, B, '2',
]
table = {g[3*i]: g[3*i+1] for i in range(int(len(g)/3))}

But this feels vulnerable to slight variations in the table's formation. Is there a better or more canonical way?

Body:
I believe the content you posted here is dummy, I'm unsure of your exact requirement. Here is the code you need as per your requirement.

text_content = [x for x in soup.text.split('\n') if x]
some_dict = {}
i = 0
for abc in soup.find_all('strong'):
    some_dict[abc.text] = text_content[i].replace(abc.text, '')
    i += 1

print(some_dict)

>> {'A': '1', 'B': '2'}


问:
Swagger UI doesn't support uploading a file properly for RestEasy
I use a JAX-RS (RestEasy) along with a Swagger. One of my endpoint can upload a file. Defined way to upload the file (in RestEasy) is to provide a org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput as a parameter.

Here is my endpoint:

```<code>@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(value = "File to register.", required = true, type = "file", name = "apiFile")
        MultipartFormDataInput apiFile) throws AppException;
</code>```

What is the problem?

Unfortunately, swagger-ui generates a schema based on the inner properties of the MultipartFormDataInput instead of a button to upload the file.
I tried use a @FormParam annotation (to indicate that the providing parameter should be interpreted as file) along with the MultipartFormDataInput parameter, but then the app doesn't want to compile.

Question: Is there any solution/workaround to provide the button to upload the file in the swagger-ui?

答:
The solution is removing  @ApiParam from your apiFile argument and adding @ApiImplicitParam (which is not bound to Jax-RS and allows defining parameters manually) above the method :

```<code>@ApiImplicitParams({@ApiImplicitParam (value = "File to register.", required = true, dataType = "file", name = "apiFile", paramType="formData")})
</code>```

Body:
I use a JAX-RS (RestEasy) along with a Swagger. One of my endpoint can upload a file. Defined way to upload the file (in RestEasy) is to provide a org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput as a parameter.

Here is my endpoint:

@PUT
@Path("/apis/{id}/file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Registers a file.", code = 201, nickname = "registerFile")
@ApiResponses(
    value = {
        @ApiResponse(code = 201, message = "File created.",
                     response = FileCreated.class),
        @ApiResponse(code = 400, message = "Invalid parameters."),
        @ApiResponse(code = 404, message = "API is not found.")})
Response registerFile(
    @ApiParam(value = "API ID.", required = true) @PathParam("id") String apiId,
    @ApiParam(value = "File to register.", required = true, type = "file", name = "apiFile")
        MultipartFormDataInput apiFile) throws AppException;

What is the problem?

Unfortunately, swagger-ui generates a schema based on the inner properties of the MultipartFormDataInput instead of a button to upload the file.
I tried use a @FormParam annotation (to indicate that the providing parameter should be interpreted as file) along with the MultipartFormDataInput parameter, but then the app doesn't want to compile.

Question: Is there any solution/workaround to provide the button to upload the file in the swagger-ui?

Body:
The solution is removing  @ApiParam from your apiFile argument and adding @ApiImplicitParam (which is not bound to Jax-RS and allows defining parameters manually) above the method :

@ApiImplicitParams({@ApiImplicitParam (value = "File to register.", required = true, dataType = "file", name = "apiFile", paramType="formData")})


答:
This is one of those times where a macro helps:

```<code>#define WRAP_FN(f) +[](std::string const& s) -> decltype(auto) { return f(s); }
</code>```

Though you could just write the body of that inline instead.

There isn't anything else you could do. The problem is that the default arguments aren't visible in the function's signature, so once you get into the type system, there's no way to differentiate:

```<code>void works(std::string const&, int=0);
void fails(std::string const&, int  );
</code>```

Both of those are void(*)(std::string const&, int). So you can't have a function template or class template wrapper - you need to do it inline with a lambda (or a macro that wraps a lambda).

Title: How to wrap a function with a varying number of default arguments to have only one argument?

Body:
This is one of those times where a macro helps:

#define WRAP_FN(f) +[](std::string const& s) -> decltype(auto) { return f(s); }

Though you could just write the body of that inline instead.

There isn't anything else you could do. The problem is that the default arguments aren't visible in the function's signature, so once you get into the type system, there's no way to differentiate:

void works(std::string const&, int=0);
void fails(std::string const&, int  );

Both of those are void(*)(std::string const&, int). So you can't have a function template or class template wrapper - you need to do it inline with a lambda (or a macro that wraps a lambda).