问:
R nested for loop combining rows within one column
I'm interested in looping over a dataframe and getting all combinations (without repetition) of a certain variable.

This can be stored in a list, and later appended to a new dataframe as a column.
I would like to achieve this using R, but Python would be ok as well.

My current data:

```<code>    idx     A         B        C
    1     name1    val_x1    val_y1
    2     name2    val_x2    val_y2
    3     name3    val_x3    val_y3
    ...
    10    name10   val_x10   val_y10
</code>```

Since n-1 = 9
and 9+8...+1 = 45
my desired data would be, as a list:

```<code>    c("name1_name2","name1_name3","name1_name4",...,"name9_name10")
</code>```

and later on as a dataframe:

```<code>    idy     D
    1    name1_name2
    2    name1_name3
    3    name1_name4
    ...
    45   name9_name10
</code>```

I thought to make a list out of the desired data, with a nested for loop, but it doesn't work as I'm probably doing something (multiple things?) wrong.

```<code>    i <- 1
    j <- 2
    k <- 1
    new_list <- c()

    while (k < 45)
        while (i < 11){
            while (j < 10){
                new_list[[k]] <- paste(df$A[i], df$A[j], sep="_")
                j <- j + 1
                k <- k + 1
            }
            i <- i + 1
        }
</code>```

This is not working as said, any tips are welcome.

PS. I'm relatively new, thanks for your patience :)

答:
We can use expand.grid

```<code>do.call(paste, c(subset(expand.grid(rep(list(df1$A), 2)), Var1 != Var2), sep="_"))
</code>```

Or with combn

```<code>D <- combn(df1$A, 2, FUN = paste, collapse="_")
res <- data.frame(idy = seq_along(D), D, stringsAsFactors=FALSE)
dim(res)
#[1] 45  2

res
#   idy            D
#1    1  name1_name2
#2    2  name1_name3
#3    3  name1_name4
#4    4  name1_name5
#5    5  name1_name6
#6    6  name1_name7
#7    7  name1_name8
#8    8  name1_name9
#9    9 name1_name10
#10  10  name2_name3
#11  11  name2_name4
#12  12  name2_name5
#13  13  name2_name6
#14  14  name2_name7
#15  15  name2_name8
#16  16  name2_name9
#17  17 name2_name10
#18  18  name3_name4
#19  19  name3_name5
#20  20  name3_name6
#21  21  name3_name7
#22  22  name3_name8
#23  23  name3_name9
#24  24 name3_name10
#25  25  name4_name5
#26  26  name4_name6
#27  27  name4_name7
#28  28  name4_name8
#29  29  name4_name9
#30  30 name4_name10
#31  31  name5_name6
#32  32  name5_name7
#33  33  name5_name8
#34  34  name5_name9
#35  35 name5_name10
#36  36  name6_name7
#37  37  name6_name8
#38  38  name6_name9
#39  39 name6_name10
#40  40  name7_name8
#41  41  name7_name9
#42  42 name7_name10
#43  43  name8_name9
#44  44 name8_name10
#45  45 name9_name10
</code>```

Body:
I'm interested in looping over a dataframe and getting all combinations (without repetition) of a certain variable.

This can be stored in a list, and later appended to a new dataframe as a column.
I would like to achieve this using R, but Python would be ok as well.

My current data:

    idx     A         B        C
    1     name1    val_x1    val_y1
    2     name2    val_x2    val_y2
    3     name3    val_x3    val_y3
    ...
    10    name10   val_x10   val_y10

Since n-1 = 9
and 9+8...+1 = 45
my desired data would be, as a list:

    c("name1_name2","name1_name3","name1_name4",...,"name9_name10")

and later on as a dataframe:

    idy     D
    1    name1_name2
    2    name1_name3
    3    name1_name4
    ...
    45   name9_name10

I thought to make a list out of the desired data, with a nested for loop, but it doesn't work as I'm probably doing something (multiple things?) wrong.

    i <- 1
    j <- 2
    k <- 1
    new_list <- c()

    while (k < 45)
        while (i < 11){
            while (j < 10){
                new_list[[k]] <- paste(df$A[i], df$A[j], sep="_")
                j <- j + 1
                k <- k + 1
            }
            i <- i + 1
        }

This is not working as said, any tips are welcome.

PS. I'm relatively new, thanks for your patience :)

Body:
We can use expand.grid

do.call(paste, c(subset(expand.grid(rep(list(df1$A), 2)), Var1 != Var2), sep="_"))

Or with combn

D <- combn(df1$A, 2, FUN = paste, collapse="_")
res <- data.frame(idy = seq_along(D), D, stringsAsFactors=FALSE)
dim(res)
#[1] 45  2

res
#   idy            D
#1    1  name1_name2
#2    2  name1_name3
#3    3  name1_name4
#4    4  name1_name5
#5    5  name1_name6
#6    6  name1_name7
#7    7  name1_name8
#8    8  name1_name9
#9    9 name1_name10
#10  10  name2_name3
#11  11  name2_name4
#12  12  name2_name5
#13  13  name2_name6
#14  14  name2_name7
#15  15  name2_name8
#16  16  name2_name9
#17  17 name2_name10
#18  18  name3_name4
#19  19  name3_name5
#20  20  name3_name6
#21  21  name3_name7
#22  22  name3_name8
#23  23  name3_name9
#24  24 name3_name10
#25  25  name4_name5
#26  26  name4_name6
#27  27  name4_name7
#28  28  name4_name8
#29  29  name4_name9
#30  30 name4_name10
#31  31  name5_name6
#32  32  name5_name7
#33  33  name5_name8
#34  34  name5_name9
#35  35 name5_name10
#36  36  name6_name7
#37  37  name6_name8
#38  38  name6_name9
#39  39 name6_name10
#40  40  name7_name8
#41  41  name7_name9
#42  42 name7_name10
#43  43  name8_name9
#44  44 name8_name10
#45  45 name9_name10


来源: stackexchange

问:
what is the meaning of this line do?MOD=BOK&ACT=Home?
I am looking at a sample jsp project. Can you explain this line:
do?MOD=BOK&ACT=Home

Here is the full code:

```<code><div id="ddblueblockmenu">
      <div class="menutitle"> Fleet Profiles</div>
          <ul>
            <li><a href="do?MOD=BOK&ACT=Home">MyHome</a></li>
            <%
            if(uname != null) {
            %>
            <li><a href="do?MOD=BOK&ACT=Home">Welcome <%= uname %></a></li>
            <li><a href="do?MOD=BOK&ACT=uEdit">Edit Details</a></li>
            <li><a href="do?MOD=BOK&ACT=Logout">LogOut</a></li>
            <li><a href="do?MOD=BOK&ACT=bokUser">Booking Details</a></li>
            <%}else {%>
            <li><a href="do?MOD=BOK&ACT=Reg">Register Now</a></li>
            <li><a href="do?MOD=BOK&ACT=Login">Login Now</a></li>
            <% } %>
            <li><a href="do?MOD=BOK&ACT=Car">Take a Car Trip</a></li>
            <li><a href="do?MOD=BOK&ACT=View&v=lux">Luxury Cars</a></li>
            <li><a href="do?MOD=BOK&ACT=View&v=exe">Executive Cars</a></li>
            <li><a href="do?MOD=BOK&ACT=View&v=muv">MUV's & SUV's</a></li>
            <li><a href="do?MOD=BOK&ACT=View&v=eco">Economy Cars</a></li>
            <li><a href="do?MOD=BOK&ACT=View&v=mini">Mini Vans & Large Coaches</a></li>
          </ul>
          <div class="menutitle"> </div>
    </div>
</code>```

答:
```<code><a href="do?MOD=BOK&ACT=Home">MyHome</a>
</code>```

Here  is anchor tag for hypertext referencing. and in its href property value is "do?MOD=BOK&ACT=Home". In this value do is some other resource related mapping. MOD is first request parameter and the value of this request parameter is "BOK" while ACT is second request parameter and the value of this parameter is HOME.
When a user clicks on this link:

An http request is generated(By default href link generates GET request only) and control is going to the server

The control comes to the servlet container

Servlet container observes the mapped url "do"

Selvlet container seeks in web.xml for any available url-mapping with "do"
For example say:

<servlet-mapping>

```<code>`<servlet-name>`DemoServlet`</servlet-name>`

`<url-pattern>`/do`</url-pattern>`
</code>```

</servlet-mapping>

If it gets any such url-mapping in web.xml, the control goes to the mapped servlet class(In above example control goes to the DemoServlet class)

If no such mapping is available in web.xml, user gets 404 error that means resource not found.

If mapped resource is available and control goes to the DemoServlet, our two request parameters are available there and their values can be accessed as:

request.getParameter("MOD")
&
request.getParameter("ACT")

ContentLicense: CC BY-SA 3.0

Body:
I am looking at a sample jsp project. Can you explain this line:
do?MOD=BOK&ACT=Home

Here is the full code:

 Fleet Profiles

MyHome

            <%
            if(uname != null) {
            %>

Welcome <%= uname %>

Edit Details

LogOut

Booking Details

            <%}else {%>

Register Now

Login Now

            <% } %>

Take a Car Trip

Luxury Cars

Executive Cars

MUV's & SUV's

Economy Cars

Mini Vans & Large Coaches

Body:
<a href="do?MOD=BOK&ACT=Home">MyHome</a>

Here  is anchor tag for hypertext referencing. and in its href property value is "do?MOD=BOK&ACT=Home". In this value do is some other resource related mapping. MOD is first request parameter and the value of this request parameter is "BOK" while ACT is second request parameter and the value of this parameter is HOME.
When a user clicks on this link:

An http request is generated(By default href link generates GET request only) and control is going to the server

The control comes to the servlet container

Servlet container observes the mapped url "do"

Selvlet container seeks in web.xml for any available url-mapping with "do"
For example say:

<servlet-mapping>

`<servlet-name>`DemoServlet`</servlet-name>`

`<url-pattern>`/do`</url-pattern>`

</servlet-mapping>

If it gets any such url-mapping in web.xml, the control goes to the mapped servlet class(In above example control goes to the DemoServlet class)

If no such mapping is available in web.xml, user gets 404 error that means resource not found.

If mapped resource is available and control goes to the DemoServlet, our two request parameters are available there and their values can be accessed as:

request.getParameter("MOD")
&
request.getParameter("ACT")


问:
If- satement and loops in an object arraylist
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

```<code>public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}
</code>```

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

答:
```<code>if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber))
</code>```

You are checking the same element for both cases here (both position i). The accountnumber is probably never accountNumber and newAccountNumber at the same time.

Body:
I'm doing a school project where I simulate a simple banking system where the user creates the account and can put a deposit, transfer money and delete accounts.

The method transaction should go through the arraylist, find the first account and the second account and transfer money but it jumps the code and says the account cannot be found. How is it possible to fix this problem

The code down below shows what happens in the method

public boolean transaction(String accountNumber, String newAccountNumber, double amount){
    for(int i = 0; i < bList.size(); i++){
        if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber)){
            bList.get(i).deposit(-amount);
            deposit(newAccountNumber, amount);
            return true;
        }
        else if(bList.get(i).getBalance()< amount){
            JOptionPane.showMessageDialog(null, "Du har inte tillräckligt med pengar");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber) && bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte ");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(newAccountNumber)){
            JOptionPane.showMessageDialog(null, "kontot finns inte");
            return false;
        }
        else if(!bList.get(i).getAccountNumber().equals(accountNumber)){
            JOptionPane.showMessageDialog(null, "Kontot finns inte");
            return false;
        }

    }
    return false;
}

The first if-statement should check if both accounts exsist and transfer money from the account that has money to the account that the user has selected but it skips the if-statement and says there is no account.

Body:
if(bList.get(i).getAccountNumber().equals(accountNumber)&& bList.get(i).getAccountNumber().equals(newAccountNumber))

You are checking the same element for both cases here (both position i). The accountnumber is probably never accountNumber and newAccountNumber at the same time.


问:
splitting lists and append them to separate lists
I am trying to split a list of 24 objects coming from grasshopper3d,
[poly-lines1][poly-lines2]....[poly-lines24] into 4 parts, so each 6 lists of poly-lines could be appended to different and separate lists- each 6 objects represents faces for a box, so each box which is a seperate list [] has 6 elements in it-, i have been trying to use the itertools library to do that but i am kind of having a problem with function.
i was trying to split the list as well.</p>

```<code>def split(polyLines,list_i,n):
    list_i.append(polyLines[0:len(polyLines):n])
    print list_i
    return list_i

lists_of_rocks = int(len(polyLines)/6)

for i in range(0,lists_of_rocks):
    list_i = []
    print list_i

    #split(polyLines,list_i,n)
    islice(polyLines,6)

def islice(polyLines,6):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(6)
    it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
    nexti = next(it)
    for i, element in enumerate(polyLines):
        if i == nexti:
            yield element
            nexti = next(it)
</code>```

答:
I am trying to split a list of 24 objects [...] into 4 parts [...] so each [...] is a seperate list [] has 6 elements

I am answering that question. I have no idea how anything else you wrote matters to the question, so if I misunderstood you I will delete my answer.

```<code>>>> l = range(24)
>>> result = [l[i:i+6] for i in range(0, len(l), 6)]
>>> for x in result: x
...
[0, 1, 2, 3, 4, 5]
[6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17]
[18, 19, 20, 21, 22, 23]
</code>```

l is your list of 24 arbitrary objects.

Body:
I am trying to split a list of 24 objects coming from grasshopper3d,
[poly-lines1][poly-lines2]....[poly-lines24] into 4 parts, so each 6 lists of poly-lines could be appended to different and separate lists- each 6 objects represents faces for a box, so each box which is a seperate list [] has 6 elements in it-, i have been trying to use the itertools library to do that but i am kind of having a problem with function.
i was trying to split the list as well.

def split(polyLines,list_i,n):
    list_i.append(polyLines[0:len(polyLines):n])
    print list_i
    return list_i

lists_of_rocks = int(len(polyLines)/6)

for i in range(0,lists_of_rocks):
    list_i = []
    print list_i

    #split(polyLines,list_i,n)
    islice(polyLines,6)

def islice(polyLines,6):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(6)
    it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
    nexti = next(it)
    for i, element in enumerate(polyLines):
        if i == nexti:
            yield element
            nexti = next(it)

Body:
I am trying to split a list of 24 objects [...] into 4 parts [...] so each [...] is a seperate list [] has 6 elements

I am answering that question. I have no idea how anything else you wrote matters to the question, so if I misunderstood you I will delete my answer.

>>> l = range(24)
>>> result = [l[i:i+6] for i in range(0, len(l), 6)]
>>> for x in result: x
...
[0, 1, 2, 3, 4, 5]
[6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17]
[18, 19, 20, 21, 22, 23]

l is your list of 24 arbitrary objects.


问:
UDP torrent trackers not replying
I've finally gotten to the stage of getting a response from a UDP tracker.

Here's an exmaple, that I split into an array:

[ 1,   3765366842, 1908, 0, 2, 0 ]

```<code>Action, request ID, interval, leechers, seeders, peers.
</code>```

No matter which torrent I chose, I get 1/2 seeders, which I'm assuming is the server tracking me, and no peers / leechers.

Am I not using the correct info hash?

This is how I retrieve it from a magnet link:

```<code>magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969
</code>```

...

h = 9f9165d9a281a9b8e782cd5176bbcc8256fd1871

Now I split this into chunks of two, and parse them, for hex bytes:

```<code>bytes = [];
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));
</code>```

[153, 153, 102, 221, 170, 136, 170, 187, 238, 136, 204, 85, 119, 187, 204, 136, 85, 255, 17, 119]

There's no need to encode this, so I send it along with my request.

This is the only point causing trouble, yet it seems so simple...

http://xbtt.sourceforge.net/udp_tracker_protocol.html

答:
As the8472 says, your decoding is incorrect:

```<code>for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));
</code>```

i and i++ will have the same value here. (One of the reasons to avoid clever inline stuff.) You can use i and ++i, or maybe expand it all to multiple lines for readability:

```<code>for (var i = 0; i < h.length; i += 2) {
    var hex = h.substr(i, 2);
    bytes.push(parseInt(hex, 16));
}
</code>```

And if you’re using Node, just parse it into a Buffer, which can easily be converted to an array if necessary:

```<code>var bytes = Buffer.from(h, 'hex');
</code>```

Title: UDP torrent trackers not replying

Body:
I've finally gotten to the stage of getting a response from a UDP tracker.

Here's an exmaple, that I split into an array:

[ 1,   3765366842, 1908, 0, 2, 0 ]

Action, request ID, interval, leechers, seeders, peers.

No matter which torrent I chose, I get 1/2 seeders, which I'm assuming is the server tracking me, and no peers / leechers.

Am I not using the correct info hash?

This is how I retrieve it from a magnet link:

magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969

...

h = 9f9165d9a281a9b8e782cd5176bbcc8256fd1871

Now I split this into chunks of two, and parse them, for hex bytes:

bytes = [];
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));

[153, 153, 102, 221, 170, 136, 170, 187, 238, 136, 204, 85, 119, 187, 204, 136, 85, 255, 17, 119]

There's no need to encode this, so I send it along with my request.

This is the only point causing trouble, yet it seems so simple...

http://xbtt.sourceforge.net/udp_tracker_protocol.html

Body:
As the8472 says, your decoding is incorrect:

for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));

i and i++ will have the same value here. (One of the reasons to avoid clever inline stuff.) You can use i and ++i, or maybe expand it all to multiple lines for readability:

for (var i = 0; i < h.length; i += 2) {
    var hex = h.substr(i, 2);
    bytes.push(parseInt(hex, 16));
}

And if you’re using Node, just parse it into a Buffer, which can easily be converted to an array if necessary:

var bytes = Buffer.from(h, 'hex');


问:
Intel OpenCL Compiler: optimize struct usage
I have a question concerning the usage of structs in OpenCL on an Intel CPU. My current kernel accesses two buffers using a struct in the following way:

```<code>struct pair {
    float first;
    float second;
};

inline const float f(const struct pair param) {
    return param.first * param.second;
}

inline const struct pair access_func(__global float const * const a, __global float const * const b, const int i) {
    struct pair res = {
            a[i],
            b[i]
    };
    return res;
}

// slow
__kernel ...(__global float const * const a, __global float const * const b)
{
 // ...

 x = f( access_func( a, b, i ) );

 // ...
}
</code>```

When I alter the kernel in the following way it runs much faster:

```<code>// fast
__kernel ...(__global float const * const a, __global float const * const b)
{
 // ...

 x = a[i] * b[ i ];

 // ...
}
</code>```

Is there a way to let the Intel compiler do this optimization? The NVIDIA compiler seems to be able to do this, since I don't see a difference in runtime on a GPU.

Thanks in advance!

答:
The compiler can't perform optimisations on the memory layout of your data, considering the buffers are shared between the OpenCL device and the host, and/or between multiple kernels on the OpenCL device; the most efficient layout will depend on access patterns in the kernel, and those can obviously be different for each kernel.

You'll need to pick your data's memory layout wisely; this is one of the hardest parts of GPU programming. Refer to the OpenCL optimisation guides for each implementation you target to find out what they prefer. Sometimes, inefficient access patterns can be masked by copying from global memory to local memory, and then working from the local copy.

Body:
I have a question concerning the usage of structs in OpenCL on an Intel CPU. My current kernel accesses two buffers using a struct in the following way:

struct pair {
    float first;
    float second;
};

inline const float f(const struct pair param) {
    return param.first * param.second;
}

inline const struct pair access_func(__global float const * const a, __global float const * const b, const int i) {
    struct pair res = {
            a[i],
            b[i]
    };
    return res;
}

// slow
__kernel ...(__global float const * const a, __global float const * const b)
{
 // ...

 x = f( access_func( a, b, i ) );

 // ...
}

When I alter the kernel in the following way it runs much faster:

// fast
__kernel ...(__global float const * const a, __global float const * const b)
{
 // ...

 x = a[i] * b[ i ];

 // ...
}

Is there a way to let the Intel compiler do this optimization? The NVIDIA compiler seems to be able to do this, since I don't see a difference in runtime on a GPU.

Thanks in advance!


问:
How to extract date time from sql and bind it to datetimePicker
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

```<code>birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");
</code>```

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

答:
The problem is the type of the field Birthday.

You say you have it as a NVARCHAR column. This is wrong for many reasons.

First the database is not able to do appropriate searches on that field. For example: is "28-12-2000" before "14-01-2001"? If you look at it as a string NO because 1 is before 2, but if you look at it as a Date then YES.

Then you will have troubles converting that value back to a datetime variable when loading it. The conversion will assume the CultureInfo of the machine where the conversion occurs. This could work correctly or not depending on the input. For example on my machine the string "04-06-2017" will be converted in the 4th of June, but on a machine where the culture info is set to MM-dd-yyyy the same string will be parsed to the 6th of April.

So you just need to change that field to a datetime type, store values as DateTime variables and read them back with

```<code>birthday_search.Value = Convert.ToDateTime(reader["Birthday"]);
</code>```

or

```<code>birthday_search.Value = (DateTime)reader["Birthday"];
</code>```

No formatting involved here. A field of type datetime is assigned to a property of type DateTime. The formatting to display this value is the job of the Format and CustomFormat of the DateTimePicker. Of course this code doesn't consider the possibility of a NULL value.

Body:
I have saved dates from datetimepicker to sql in my windows form app with the format (dd-MM-yyyy). To edit date, I want to first fetch saved date and show in the datetimepicker control. Like if 28-03-2000 is saved in db then datetimepicker should show this same date and should understand the format dd-MM-yyyy. The code with which I am trying to do is as follows

birthday_search.Text = Convert.ToDateTime(reader["Birthday"]).ToString("dd-MM-yyyy");

birthday_search is the name of datetimepicker. This gives error "String was not recognized as a valid datetime" because its itself picking the format MM-dd-yyyy which is turning out to be wrong.

Body:
The problem is the type of the field Birthday.

You say you have it as a NVARCHAR column. This is wrong for many reasons.

First the database is not able to do appropriate searches on that field. For example: is "28-12-2000" before "14-01-2001"? If you look at it as a string NO because 1 is before 2, but if you look at it as a Date then YES.

Then you will have troubles converting that value back to a datetime variable when loading it. The conversion will assume the CultureInfo of the machine where the conversion occurs. This could work correctly or not depending on the input. For example on my machine the string "04-06-2017" will be converted in the 4th of June, but on a machine where the culture info is set to MM-dd-yyyy the same string will be parsed to the 6th of April.

So you just need to change that field to a datetime type, store values as DateTime variables and read them back with

birthday_search.Value = Convert.ToDateTime(reader["Birthday"]);

or

birthday_search.Value = (DateTime)reader["Birthday"];

No formatting involved here. A field of type datetime is assigned to a property of type DateTime. The formatting to display this value is the job of the Format and CustomFormat of the DateTimePicker. Of course this code doesn't consider the possibility of a NULL value.


问:
XDocument Namespace on root and first child
I'm building an xml file using XDocument

```<code>XDocument single = new XDocument(
                new XDeclaration("1.0", "UTF-8", "true"),
                new XElement(_namespace + "vcards",
                    XElement.Parse(BuildCardEntry(contact))));
</code>```

Inside BuildCardEntry(contact) I'm adding the namespace to every XElement too.
But my code pruduces this

```<code><vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
  <vcard xmlns="urn:ietf:params:xml:ns:vcard-3.0">
</code>```

insted of this

```<code><vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
  <vcard>
</code>```

Does somebody know, how to solve this?

答:
Use SaveOptions.OmitDuplicateNamespaces parameter when saving xml.

```<code>single.Save(..., SaveOptions.OmitDuplicateNamespaces);
</code>```

Body:
I'm building an xml file using XDocument

XDocument single = new XDocument(
                new XDeclaration("1.0", "UTF-8", "true"),
                new XElement(_namespace + "vcards",
                    XElement.Parse(BuildCardEntry(contact))));

Inside BuildCardEntry(contact) I'm adding the namespace to every XElement too.
But my code pruduces this

<vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
  <vcard xmlns="urn:ietf:params:xml:ns:vcard-3.0">

insted of this

<vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
  <vcard>

Does somebody know, how to solve this?

Body:
Use SaveOptions.OmitDuplicateNamespaces parameter when saving xml.

single.Save(..., SaveOptions.OmitDuplicateNamespaces);


问:
Dynamic style on react-native-router-flux TabBar
I have a Scene in react-native-router-flux that is acting as a TabBar in my application, however we need to change the color scheme of the entire tab bar based on some state inside of the application. We are using redux for state management and I had tried to adjust the tabBarStyle property in the <Scene> component, but making changes to the style does not have any affect. The TabBar seems to only be rendered when the component is mounted, and doesn't seem to care if any of the props passed to it are changed.

We are trying to implement different themes into our application, and this has worked great up until we got to the components used by react-native-router-flux.

Does anyone know of a way to make these components update their style in real time?

答:
You should use the "style"-Property on the Scene for that.
This is how i do a black TabBar with white Icons and white font:

```<code>            <Scene key='mainScenes'
                hideNavBar={false}
                navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                leftButtonIconStyle = {{ tintColor:'white'}}
                titleStyle={{color: 'white', fontSize: normalize(14), fontWeight: 'bold'}}
                tabs={true}
                translucent={false}
                style={s.tabbar}
            >
                <Scene icon={TabIcon} key='events' hideNavBar={false} title='Events' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={EventsViewScene} sceneStyle={getScreenContainerStyle()} >

                </Scene>
                <Scene icon={TabIcon} key='locations' hideNavBar={false} title='Locations' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={LocationsViewScene} sceneStyle={getScreenContainerStyle()}
                />
                <Scene icon={TabIcon} key='search' hideNavBar={false} title='Search' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={SearchViewScene} sceneStyle={getScreenContainerStyle()}
                    initial={false}
                />
                <Scene icon={TabIcon} key='more' hideNavBar={false} title='More' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={InfoViewScene} sceneStyle={getScreenContainerStyle()}
                    initial={false}
                />
            </Scene>
</code>```

The StyleSheet:

```<code>const s = StyleSheet.create({
    tabIcon: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    rightButton: {
        justifyContent: 'center',
        alignItems: 'center',
        width: normalize(23),
        height: normalize(23),
    },
    tabbar: {
        backgroundColor: 'black',
        borderTopColor: 'white',
        borderTopWidth: 2,
    },
</code>```

TabIcon:

```<code>const icons = {
    'search': 'search',
    'events': 'calendar',
    'locations': 'map-marker',
    'more': 'info-circle'
}

// Application
class TabIcon extends React.Component {

    render(){
        const {name, title} = this.props;
        const iconName = icons[name] || 'info-circle'

        return (
            <View style={s.tabIcon}>
                <Icon name={iconName} size={TAB_ICON_SIZE} color="white" />
                <Text style={{color: this.props.selected ? 'yellow' :'white'}}>{title}</Text>
            </View>
        );
    }
}
</code>```

Body:
You should use the "style"-Property on the Scene for that.
This is how i do a black TabBar with white Icons and white font:

            <Scene key='mainScenes'
                hideNavBar={false}
                navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                leftButtonIconStyle = {{ tintColor:'white'}}
                titleStyle={{color: 'white', fontSize: normalize(14), fontWeight: 'bold'}}
                tabs={true}
                translucent={false}
                style={s.tabbar}
            >
                <Scene icon={TabIcon} key='events' hideNavBar={false} title='Events' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={EventsViewScene} sceneStyle={getScreenContainerStyle()} >

                </Scene>
                <Scene icon={TabIcon} key='locations' hideNavBar={false} title='Locations' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={LocationsViewScene} sceneStyle={getScreenContainerStyle()}
                />
                <Scene icon={TabIcon} key='search' hideNavBar={false} title='Search' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={SearchViewScene} sceneStyle={getScreenContainerStyle()}
                    initial={false}
                />
                <Scene icon={TabIcon} key='more' hideNavBar={false} title='More' titleStyle={{color:'white'}}
                    navigationBarStyle={{ backgroundColor: COLORS.HEADER_BACKGROUND}}
                    component={InfoViewScene} sceneStyle={getScreenContainerStyle()}
                    initial={false}
                />
            </Scene>

The StyleSheet:

const s = StyleSheet.create({
    tabIcon: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    rightButton: {
        justifyContent: 'center',
        alignItems: 'center',
        width: normalize(23),
        height: normalize(23),
    },
    tabbar: {
        backgroundColor: 'black',
        borderTopColor: 'white',
        borderTopWidth: 2,
    },

TabIcon:

const icons = {
    'search': 'search',
    'events': 'calendar',
    'locations': 'map-marker',
    'more': 'info-circle'
}

// Application
class TabIcon extends React.Component {

    render(){
        const {name, title} = this.props;
        const iconName = icons[name] || 'info-circle'

        return (
            <View style={s.tabIcon}>
                <Icon name={iconName} size={TAB_ICON_SIZE} color="white" />
                <Text style={{color: this.props.selected ? 'yellow' :'white'}}>{title}</Text>
            </View>
        );
    }
}


问:
XPages: Can an SSJS function be reused without putting it in a library?
I have a ssjs function that is only called a couple of times in a self-contained XPages custom control.

Is there a way to keep this function in the XPage/CustomControl itself and call it directly without storing it in a separate javascript library?

答:
This is how it can be done:

Add a ComputedField (e.g. name it 'local_ssjs') and let it generate the desired shared js code as a string value.

E.g.: "function returnFour(){retrun (4)};"

In your event, obtain the shared code and use the eval() function to include it.

var sharedCode = getComponent("local_ssjs").getValue();
eval(sharedCode);
var xFour = returnFour();

Even if the computed field only contains function definitions, this works ok.


问:
Why doesn't my c code work using pointer and struct?
Why doens't it work? There exists address access error. However, I tried to find the problem all over the internet and google, I coudln't. I am doing my assignment. My assistant require us to use

```<code>STUDENT ** list  and Malloc ()
</code>```

However they don't explain perfectly, So I m in hard time. How can I solve this problem? Why am I getting an error?

答:
It seems you are required to use STUDENT **list although that is not the best way to do the job. But seeing as this is an exercise I will stay with it, and STUDENT **list will be an array of pointers to that struct.

Your program has two major faults.

Not allocating memory for each element of the pointer array

Assigning input data to a local struct which is forgotten on
function exit.

The first of those two is deadly when you try to print the data, because you use uninitialised pointers.

There are other things too which you should always check

the value returned by malloc

the result of the scanf functions (the value returned by scanf)

Also, you must

restrict string input from overflowing

free the memory after use

Here is a basic fix of the code, which still needs the other improvements mentioned.

```<code>#include <stdio.h>
#include <stdlib.h>

#define ID_LEN 7
#define NAME_LEN 10

typedef struct{
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void SHOW(STUDENT* list) {
    printf("ID : %s\n", list->id);
    printf("name : %s\n", list->name);
    printf("math : %d\n", list->math);
    printf("eng : %d\n", list->eng);
}

void FirstList(STUDENT *list){
    printf("ID : ");
    scanf("%s", list->id);                  // use the pointer passed
    printf("Name : ");                      // instead of local struct
    scanf("%s", list->name);
    printf("Math score: ");
    scanf("%d",&list->math);
    printf("English score: ");
    scanf("%d",&list->eng);
}

int main(){
    STUDENT **list = NULL;
    int num = 0;
    printf("How many student? ");
    scanf("%d", &num);
    list = malloc(num * sizeof(STUDENT*));
    for(int i=0; i<num; i++) {
        list[i] = malloc(sizeof(STUDENT));  // allocate memory for struct
        FirstList(list[i]);
    }

    for(int i=0; i<num; i++) {
        SHOW(list[i]);
    }
    return 0;
}
</code>```

Body:
Why doens't it work? There exists address access error. However, I tried to find the problem all over the internet and google, I coudln't. I am doing my assignment. My assistant require us to use

STUDENT ** list  and Malloc ()

However they don't explain perfectly, So I m in hard time. How can I solve this problem? Why am I getting an error?

Body:
It seems you are required to use STUDENT **list although that is not the best way to do the job. But seeing as this is an exercise I will stay with it, and STUDENT **list will be an array of pointers to that struct.

Your program has two major faults.

Not allocating memory for each element of the pointer array

Assigning input data to a local struct which is forgotten on
function exit.

The first of those two is deadly when you try to print the data, because you use uninitialised pointers.

There are other things too which you should always check

the value returned by malloc

the result of the scanf functions (the value returned by scanf)

Also, you must

restrict string input from overflowing

free the memory after use

Here is a basic fix of the code, which still needs the other improvements mentioned.

#include <stdio.h>
#include <stdlib.h>

#define ID_LEN 7
#define NAME_LEN 10

typedef struct{
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void SHOW(STUDENT* list) {
    printf("ID : %s\n", list->id);
    printf("name : %s\n", list->name);
    printf("math : %d\n", list->math);
    printf("eng : %d\n", list->eng);
}

void FirstList(STUDENT *list){
    printf("ID : ");
    scanf("%s", list->id);                  // use the pointer passed
    printf("Name : ");                      // instead of local struct
    scanf("%s", list->name);
    printf("Math score: ");
    scanf("%d",&list->math);
    printf("English score: ");
    scanf("%d",&list->eng);
}

int main(){
    STUDENT **list = NULL;
    int num = 0;
    printf("How many student? ");
    scanf("%d", &num);
    list = malloc(num * sizeof(STUDENT*));
    for(int i=0; i<num; i++) {
        list[i] = malloc(sizeof(STUDENT));  // allocate memory for struct
        FirstList(list[i]);
    }

    for(int i=0; i<num; i++) {
        SHOW(list[i]);
    }
    return 0;
}


问:
How to fetch different records in same row in sql?
I have a table structure similar to one given below

```<code>1001    Jon
1002    Jacob
1003    Cayle
</code>```

I want to fetch records from table in a way that it should look like

```<code>1001 – Jon,   1002 – Jacob,  1003 – Cayle
</code>```

Can anybody suggest some easy way.

答:
The easiest way on Oracle to achieve that is listagg. Try something like this:

```<code>create table parameter as
select 1001 as id, cast('Jon' as varchar2(10)) as name from dual union all
select 1002, 'Jacob' from dual union all
select 1003, 'Cayle' from dual
;

select listagg(id||' - '||name, ', ') within group (order by id) as list
from parameter
;

LIST
------------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle
</code>```

Yet another solution on Oracle. I think it will be easy to port to some other RDBMS:

```<code>select
    rtrim(
        xmlagg(
            хmlElement(tag, id||' - '||name, ', ').еxtract('//text()') order by id
        ).getStringVal(), ', ') as list
from parameter
;

LIST
-------------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle
</code>```

If your table is really very small, than you may define your specific function. This function can be easily ported to any RDBMS:

```<code>create or replace function paramList return varchar2 is
    ret  varchar2(1024) := null;
begin
    for row_ in (select id||' - '||name as tag from parameter) loop
        ret := ret||', '||row_.tag;
    end loop;
    return ltrim(ret, ', ');
end paramlist;
/
show errors

col parameters format a40
select paramList parameters from dual;

PARAMETERS
----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle
</code>```

Or more generic function:

```<code>create or replace function concatRows (cursor_ sys_refcursor) return  varchar2 is
    ret  varchar2(32767);
    tmp  varchar2(32767);
begin
    loop fetch cursor_ into tmp;
        exit when cursor_%notfound;
        ret := ret || ', ' || tmp;
    end loop;
    return ltrim(ret, ', ');
end ;
/

select concatRows(cursor(
    select id||' - '||name from parameter
)) parameters from dual
;

PARAMETERS
----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle
</code>```

One more generic function with collect:

```<code>create or replace function arrayagg (arr sys.ODCIVarchar2List, delimiter varchar2 default ', ') return varchar2 is
    ret varchar2(32767);
begin
    for i in arr.first.. arr.last loop
        ret := ret||arr(i)||delimiter;
    end loop;
    return rtrim(ret, delimiter);
end arrayagg;
/

select arrayagg(cast(collect(id||' - '||name) as sys.ODCIVarchar2List)) parameters
from parameter
;

PARAMETERS
-----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle
</code>```

Body:
I have a table structure similar to one given below

1001    Jon
1002    Jacob
1003    Cayle

I want to fetch records from table in a way that it should look like

1001 – Jon,   1002 – Jacob,  1003 – Cayle

Can anybody suggest some easy way.

Body:
The easiest way on Oracle to achieve that is listagg. Try something like this:

create table parameter as
select 1001 as id, cast('Jon' as varchar2(10)) as name from dual union all
select 1002, 'Jacob' from dual union all
select 1003, 'Cayle' from dual
;

select listagg(id||' - '||name, ', ') within group (order by id) as list
from parameter
;

LIST
------------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle

Yet another solution on Oracle. I think it will be easy to port to some other RDBMS:

select
    rtrim(
        xmlagg(
            хmlElement(tag, id||' - '||name, ', ').еxtract('//text()') order by id
        ).getStringVal(), ', ') as list
from parameter
;

LIST
-------------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle

If your table is really very small, than you may define your specific function. This function can be easily ported to any RDBMS:

create or replace function paramList return varchar2 is
    ret  varchar2(1024) := null;
begin
    for row_ in (select id||' - '||name as tag from parameter) loop
        ret := ret||', '||row_.tag;
    end loop;
    return ltrim(ret, ', ');
end paramlist;
/
show errors

col parameters format a40
select paramList parameters from dual;

PARAMETERS
----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle

Or more generic function:

create or replace function concatRows (cursor_ sys_refcursor) return  varchar2 is
    ret  varchar2(32767);
    tmp  varchar2(32767);
begin
    loop fetch cursor_ into tmp;
        exit when cursor_%notfound;
        ret := ret || ', ' || tmp;
    end loop;
    return ltrim(ret, ', ');
end ;
/

select concatRows(cursor(
    select id||' - '||name from parameter
)) parameters from dual
;

PARAMETERS
----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle

One more generic function with collect:

create or replace function arrayagg (arr sys.ODCIVarchar2List, delimiter varchar2 default ', ') return varchar2 is
    ret varchar2(32767);
begin
    for i in arr.first.. arr.last loop
        ret := ret||arr(i)||delimiter;
    end loop;
    return rtrim(ret, delimiter);
end arrayagg;
/

select arrayagg(cast(collect(id||' - '||name) as sys.ODCIVarchar2List)) parameters
from parameter
;

PARAMETERS
-----------------------------------------
1001 - Jon, 1002 - Jacob, 1003 - Cayle

ContentLicense: CC BY-SA 4.0


问:
Link souce folder
I am developping a Java project with Eclipse, using 2 source folders. Is there a way to link them?
If I write in the class file "import source_folder_1.package.class", Eclipse indicates the error "the import source_folder_1 cannot be resolved"
Could you please help me?
Thanke
Eduard</p>

答:
The source folder names are not part of package names.
The package names are formed from the directory elements below the source folder. For example if you have this directory layout in your project:

```<code>.
├── other-src
│   └── com
│       └── example
│           ├── client
│           └── demo
└── src
    └── main
        └── java
            └── org
                └── uni
                    ├── api
                    └── util
</code>```

And in Eclipse you have configured src/main/java and other-src as source directories, then you will have Java packages:

com.example.client

com.example.demo

org.uni.api

org.uni.util

The classes in whichever package will be able to import any of these packages, since Eclipse will find them in the two configured source folders.

Title: Link souce folder

Body:
The source folder names are not part of package names.
The package names are formed from the directory elements below the source folder. For example if you have this directory layout in your project:

.
├── other-src
│   └── com
│       └── example
│           ├── client
│           └── demo
└── src
    └── main
        └── java
            └── org
                └── uni
                    ├── api
                    └── util

And in Eclipse you have configured src/main/java and other-src as source directories, then you will have Java packages:

com.example.client

com.example.demo

org.uni.api

org.uni.util

The classes in whichever package will be able to import any of these packages, since Eclipse will find them in the two configured source folders.


问:
Are incrementers / decrementers (var++, var--) etc thread safe?
Inspired by this question: In Complexity Analysis why is ++ considered to be 2 operations?

Take the following psuedo code:

```<code>class test
{
   int _counter;
   void Increment()
   {
     _counter++;
   }
}
</code>```

Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?

答:
In a word, no.

You can use something like InterlockedIncrement() depending on your platform.  On .NET you can use the Interlocked class methods (Interlocked.Increment() for example).

A Rob Kennedy mentioned, even if the operation is implemented in terms of a single INC instruction, as far as the memory is concerned a read/increment/write set of steps is performed. There is the opportunity on a multi-processor system for corruption.

There's also the volatile issue, which would be a necessary part of making the operation thread-safe - however, marking the variable volatile is not sufficient to make it thread-safe.  Use the interlocked support the platform provides.

This is true in general, and on x86/x64 platforms certainly.

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5

Body:
Inspired by this question: In Complexity Analysis why is ++ considered to be 2 operations?

Take the following psuedo code:

class test
{
   int _counter;
   void Increment()
   {
     _counter++;
   }
}

Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?

LastEditorDisplayName: Josh

OwnerDisplayName: Michael Burr

LastEditorDisplayName: Michael Burr


问:
Objective C version of the unix "finger" command
I'm trying to check the time since last login in my Cocoa app. I would like to do it without having to do something like this:

```<code>NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/finger"];

NSArray *arguments;
arguments = [NSArray arrayWithObject: NSUserName()];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"%@", stringData);
</code>```

For example, the Unix whoami command has the NSUserName Objective C equivalent.

答:
You would probably have to read in that info from the system files where that's stored. Maybe a 'utmp' file on unix.

After all, that's what 'finger' does.

Body:
I'm trying to check the time since last login in my Cocoa app. I would like to do it without having to do something like this:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/finger"];

NSArray *arguments;
arguments = [NSArray arrayWithObject: NSUserName()];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *stringData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"%@", stringData);

For example, the Unix whoami command has the NSUserName Objective C equivalent.


问:
Set up a scheduler that triggers every 10 minutes in C# ASP.NET MVC 5
I'm trying to set up a scheduler that will trigger every 10 minutes, activating a database query. I can't find any good tutorials on this and some advice would be great. Language is C#, web framework is ASP.NET MVC 5.</p>

答: Have a look at HangFire https://www.hangfire.io/ for creating background processing jobs.</p>


问:
Initializing a const array inside a struct
```<code>#define LENGTH 6
typedef char data_t[LENGTH];
struct foo {
    const data_t data;
    ...
}
...
void bar(data_t data) {
    printf("%.6s\n", data);
    struct foo myfoo = {*data};
    printf("%.6s\n", foo.data);
}
</code>```

I'm trying to have this struct which holds directly the data I'm interested in, sizeof(foo) == 6+the rest, not sizeof(foo) == sizeof(void*)+the rest. However I can't find a way to initialize a struct of type foo with a data_t. I think maybe I could remove the const modifier from the field and use memcpy but I like the extra safety and clarity.

I don't get any compile errors but when I run the code I get

```<code>123456
1??
</code>```

so the copy didn't work properly I think.

This is for an arduino (or similar device) so I'm trying to keep it to very portable code.

Is it just not possible ?

EDIT: removing the const modifier on the data_t field doesn't seem to help.

答:
It is possible to do this, for some cost >=0.

```<code>typedef struct
{
    char c[LENGTH];
} data_t; // this struct is freely copyable

struct foo
{
    const data_t data; // but this data member is not
    int what;
};

void foo (char* x) {
    data_t d;                         // declare freely copyable struct instance
    memcpy(d.c, x, sizeof(d.c));      // memcpy it
    struct foo foo = { d, 42 };       // initialise struct instance with const member
    ...
};
</code>```

Some compilers (e.g. clang) are even able to optimise away the redundant copying (from x to d.c and then from d to foo.data ⇒ from x straight to foo.data). Others (gcc I'm looking at you) don't seem to be able to achieve this.

If you pass around pointers to data_t rather than straight char pointers, you won't need this additional memcpy step. OTOH in order to access the char array inside foo you need another level of member access (.data.c instead of just .data; this has no runtime cost though).

Body:
#define LENGTH 6
typedef char data_t[LENGTH];
struct foo {
    const data_t data;
    ...
}
...
void bar(data_t data) {
    printf("%.6s\n", data);
    struct foo myfoo = {*data};
    printf("%.6s\n", foo.data);
}

I'm trying to have this struct which holds directly the data I'm interested in, sizeof(foo) == 6+the rest, not sizeof(foo) == sizeof(void*)+the rest. However I can't find a way to initialize a struct of type foo with a data_t. I think maybe I could remove the const modifier from the field and use memcpy but I like the extra safety and clarity.

I don't get any compile errors but when I run the code I get

123456
1??

so the copy didn't work properly I think.

This is for an arduino (or similar device) so I'm trying to keep it to very portable code.

Is it just not possible ?

EDIT: removing the const modifier on the data_t field doesn't seem to help.

Body:
It is possible to do this, for some cost >=0.

typedef struct
{
    char c[LENGTH];
} data_t; // this struct is freely copyable

struct foo
{
    const data_t data; // but this data member is not
    int what;
};

void foo (char* x) {
    data_t d;                         // declare freely copyable struct instance
    memcpy(d.c, x, sizeof(d.c));      // memcpy it
    struct foo foo = { d, 42 };       // initialise struct instance with const member
    ...
};

Some compilers (e.g. clang) are even able to optimise away the redundant copying (from x to d.c and then from d to foo.data ⇒ from x straight to foo.data). Others (gcc I'm looking at you) don't seem to be able to achieve this.

If you pass around pointers to data_t rather than straight char pointers, you won't need this additional memcpy step. OTOH in order to access the char array inside foo you need another level of member access (.data.c instead of just .data; this has no runtime cost though).


问:
Meteor JS ReactMeteorData - CreateContainer - Super expression must either be null or a function
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

```<code>Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)
</code>```

AppContainer.jsx:

```<code>import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);
</code>```

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;
</code>```

答:
Personnally, for a container data i do like this (from masterchef Base, updated and working as well) :

```<code>/* AppContainer.js */

// import react and proptypes ...
import { Meteor } from 'meteor/meteor';
import container from '../../../modules/container';

// Some code for app layout and proptypes...

export default container((props, onData) => {
  const user= Meteor.user(); // adapted for your case
  onData(null, {
    currentUser:user,
    // and others data ...
  });
}, App);

/* container.js */

import { compose } from 'react-komposer';
import getTrackerLoader from './get-tracker-loader';

export default function container(composer, Component, options = {}) {
  return compose(getTrackerLoader(composer), options)(Component);
}

/* get-tracker-loader.js */

import { Tracker } from 'meteor/tracker';

export default function getTrackerLoader(reactiveMapper) {
  return (props, onData, env) => {
    let trackerCleanup = null;

    const handler = Tracker.nonreactive(() => Tracker.autorun(() => {
      trackerCleanup = reactiveMapper(props, onData, env);
    }));

    return () => {
      if (typeof trackerCleanup === 'function') trackerCleanup();
      return handler.stop();
    };
  };
}
</code>```

Hope it ll be useful.

Body:
After upgrading to Meteor 1.5 from 1.4, createContainer function from react-meteor-data gives the following error:

Uncaught TypeError: Super expression must either be null or a function, not undefined
    at exports.default (modules.js?hash=fb99b6a…:1144)
    at ReactMeteorData.jsx:6
    at ReactMeteorData.jsx:6
    at createContainer (createContainer.jsx:16)
    at AppContainer.jsx (AppContainer.jsx:8)

AppContainer.jsx:

import { Meteor } from 'meteor/meteor';

import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';

import App from '../layouts/App.jsx';

export default AppContainer = createContainer(props => {
  return {
    currentUser: Meteor.user(),
  };
}, App);

App file below, in constructor i am performing super(props) however error is still thrown

App.jsx:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menuOpen: false,
      showConnectionIssue: false,
      headerTitle: null,
    };
    this.setHeaderTitle = this.setHeaderTitle.bind(this);
    this.logout = this.logout.bind(this);
  }

  logout() {
    Meteor.logout();
    this.context.router.replace(`/home`);
  }

  render() {
    ... omitted render function
  }
}

App.propTypes = {
  user: React.PropTypes.object,      // current meteor user
  connected: React.PropTypes.bool,   // server connection status
  loading: React.PropTypes.bool,     // subscription status
  menuOpen: React.PropTypes.bool,    // is side menu open?
  children: React.PropTypes.element, // matched child route component
  location: React.PropTypes.object,  // current router location
  params: React.PropTypes.object,    // parameters of the current route
};

App.contextTypes = {
  router: React.PropTypes.object,
};

export default App;

Body:
Personnally, for a container data i do like this (from masterchef Base, updated and working as well) :

/* AppContainer.js */

// import react and proptypes ...
import { Meteor } from 'meteor/meteor';
import container from '../../../modules/container';

// Some code for app layout and proptypes...

export default container((props, onData) => {
  const user= Meteor.user(); // adapted for your case
  onData(null, {
    currentUser:user,
    // and others data ...
  });
}, App);

/* container.js */

import { compose } from 'react-komposer';
import getTrackerLoader from './get-tracker-loader';

export default function container(composer, Component, options = {}) {
  return compose(getTrackerLoader(composer), options)(Component);
}

/* get-tracker-loader.js */

import { Tracker } from 'meteor/tracker';

export default function getTrackerLoader(reactiveMapper) {
  return (props, onData, env) => {
    let trackerCleanup = null;

    const handler = Tracker.nonreactive(() => Tracker.autorun(() => {
      trackerCleanup = reactiveMapper(props, onData, env);
    }));

    return () => {
      if (typeof trackerCleanup === 'function') trackerCleanup();
      return handler.stop();
    };
  };
}

Hope it ll be useful.


答:
Just use import thepackage.TheClass;.

It doesn't matter if you have one or to source folders, and which of them contains the class you import. When you need to use a class by its simple name, you add an import statement with the flly qualified class name, which is the package followed by the simple class name.

Eclipse will just look in the source folders and in the libraries in the build path to find it.

Title: Link souce folder

Body:
I am developping a Java project with Eclipse, using 2 source folders. Is there a way to link them?
If I write in the class file "import source_folder_1.package.class", Eclipse indicates the error "the import source_folder_1 cannot be resolved"
Could you please help me?
Thanke
Eduard


问:
Array created in a Redux thunk is not being passed properly to the State tree
I'm building a React/Redux project that makes a couple calls to an S3 bucket to grab images, and then render them into the app.

I'm finding that for some reason, I cannot iterate through the array that I set in my state tree as a result of those calls to render them onto the app. I believe that I may be dealing with an array-like object or something within the Promises I created caused this mutation to occur.

First, I have this file in a folder titled utils:

```<code>const bucketName = 'foo';
const roleARN = 'arn:aws:s3:::foo';
const identityPoolId = 'us-west-2:anActualIdHere';

AWS.config.update({
  region: 'us-west-2',
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId
  })
});

const bucket = new AWS.S3({
  params: {
    Bucket: bucketName,
  }
});

const textDecoder = new TextDecoder('utf8');

export function listObjects (callback) {
  return bucket.listObjects((error, data) => {
    if (error) {
      console.error('error: ', error);
      return;
    }

    callback(data.Contents);
  });
}

export function getSingleObject (key) {
  let getObject = new Promise((resolve, reject) => {
    bucket.getObject({
      Bucket: bucketName,
      Key: key
    }, (error, data) => {
      if (error) {
        console.error('error: ', error);
      }

      resolve(data.Body.toString('base64'));
    });
  })

  return getObject.then((result) => {
    return result;
  })
}
</code>```

What happens here is that listObjects will return an array of all items in a specific S3 bucket.

Then, the getSingleObject function grabs a single object's contents based on a key provided in that list of all items, grabbing its Uint8Array and converting it to a base-64 string.

These two functions are called in a thunk action:

```<code>import { listObjects, getSingleObject } from '../utils/index.js';

export function loadPhotos () {
  return function (dispatch) {
    listObjects((results) => {
      let photos = [];

      let mapPhotosToArray = new Promise((resolve, reject) => {
        results.forEach((singlePhoto) => {
          let getSinglePhoto = new Promise((resolve, reject) => {
            resolve(getSingleObject(singlePhoto.Key));
          });

          getSinglePhoto.then((result) => {
            photos.push(result);
          });
        });
        resolve(photos);
      })

      mapPhotosToArray.then((result) => {
        dispatch(savePhotos(result));
      });
    });
  }
}

function savePhotos (photos) {
  return {
    type: 'GET_PHOTOS',
    photos
  }
}
</code>```

loadPhotos is the thunk action exposed to my Redux containers. It returns a function that first calls the listObjects function in the utils file, passing it a callback that creates an array called photos.

Then, it creates a new Promise that loops through the results array returned by the listObjects utility function. In each iteration of this results array, I instantiate another new Promise that calls the getSingleObject utility.

Within that iteration, I push the results of getSingleObject into the photos array created within the callback passed into listObjects.

The last thing I do in the loadPhotos thunk action is call the outer Promise and then dispatch the result to the savePhotos action, which finally dispatches the payload object to the store for my reducer to catch.

This is how my reducer looks:

```<code>const defaultState = {
  photos: []
}

const photos = (state = defaultState, action) => {
  switch (action.type) {
    case 'GET_PHOTOS':
      return Object.assign({}, state, {
        photos: action.photos
      })
    default:
      return state;
  }
};

export default photos;
</code>```

Here is how I've set up the entry point to the app:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, compose, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import photos from './reducers/';

import App from './components/app';

import styles from './styles/styles.css';

const createStoreWithMiddleware = compose(applyMiddleware(thunk))(createStore);

const store = createStoreWithMiddleware(photos, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
  <Provider store={ store }>
    <App />
  </Provider>,
  document.getElementById('root')
)
</code>```

This is the App component rendered:

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import AllPhotos from '../containers/AllPhotos';
import Navbar from './Navbar';

import '../styles/styles.css';

export default class App extends Component {
  constructor (props) {
    super (props);
  }

  render () {
    return (
      <div className="app">
        <Navbar />
        <AllPhotos />
      </div>
    )
  }
}
</code>```

Here is the AllPhotos container it renders:

```<code>import { connect } from 'react-redux';

import AllPhotos from '../components/AllPhotos';

import {
  loadPhotos
} from '../actions/index.js';

const mapDispatchToProps = (dispatch) => {
  return {
    loadPhotos: () => {
      dispatch(loadPhotos());
    }
  }
}

const mapStateToProps = (state) => {
  return {
    photos: state.photos
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AllPhotos);
</code>```

And finally, this is the AllPhotos component:

```<code>import React, { Component } from 'react';
import _ from 'lodash';

export default class AllPhotos extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount () {
    this.props.loadPhotos();
  }

  render () {
    return (
      <div>
        <h1>Test</h1>
        { this._renderImages() }
      </div>
    )
  }

  _renderImages () {
    _.map(this.props.photos, (image) => {
      return (
        <img
          src={ 'data:image/png;base64,' + image }
          width={ 480 }
        />
      )
    })
  }
}
</code>```

This is what happens when I attempt to log this.props.photos within _renderImages:

The first log occurs before the photos array is populated and loaded into my state.

However, if I were to log the length of this.props.photos in the same area that I log just the array itself, this is what I see:

When I call Array.isArray on this.props.photos in that same line, this is what I get:

I have also attempted to convert this into an array using Array.from, but have not been successful.

Going a bit deeper, I attempted to find the length of the photos array from the action payload in my reducer, and still received 0 as the output. I also tried this within the savePhotos action, and found the same result.

As a result, I believe I may have not written my Promises correctly. Could someone help point me in the right direction?

答:
You can try rewriting listObjects and getSingleObject to return Promises and utilising Promise.all.

Then you can write loadPhotos

```<code>export function loadPhotos () {
  return function (dispatch) {
    listObjects().then((results) =>
      Promise.all(results.map((singlePhoto) => getSingleObject(singlePhoto.Key)))
        .then((result) => dispatch(savePhotos(result)))
    )
  }
}
</code>```

Body:
I'm building a React/Redux project that makes a couple calls to an S3 bucket to grab images, and then render them into the app.

I'm finding that for some reason, I cannot iterate through the array that I set in my state tree as a result of those calls to render them onto the app. I believe that I may be dealing with an array-like object or something within the Promises I created caused this mutation to occur.

First, I have this file in a folder titled utils:

const bucketName = 'foo';
const roleARN = 'arn:aws:s3:::foo';
const identityPoolId = 'us-west-2:anActualIdHere';

AWS.config.update({
  region: 'us-west-2',
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: identityPoolId
  })
});

const bucket = new AWS.S3({
  params: {
    Bucket: bucketName,
  }
});

const textDecoder = new TextDecoder('utf8');

export function listObjects (callback) {
  return bucket.listObjects((error, data) => {
    if (error) {
      console.error('error: ', error);
      return;
    }

    callback(data.Contents);
  });
}

export function getSingleObject (key) {
  let getObject = new Promise((resolve, reject) => {
    bucket.getObject({
      Bucket: bucketName,
      Key: key
    }, (error, data) => {
      if (error) {
        console.error('error: ', error);
      }

      resolve(data.Body.toString('base64'));
    });
  })

  return getObject.then((result) => {
    return result;
  })
}

What happens here is that listObjects will return an array of all items in a specific S3 bucket.

Then, the getSingleObject function grabs a single object's contents based on a key provided in that list of all items, grabbing its Uint8Array and converting it to a base-64 string.

These two functions are called in a thunk action:

import { listObjects, getSingleObject } from '../utils/index.js';

export function loadPhotos () {
  return function (dispatch) {
    listObjects((results) => {
      let photos = [];

      let mapPhotosToArray = new Promise((resolve, reject) => {
        results.forEach((singlePhoto) => {
          let getSinglePhoto = new Promise((resolve, reject) => {
            resolve(getSingleObject(singlePhoto.Key));
          });

          getSinglePhoto.then((result) => {
            photos.push(result);
          });
        });
        resolve(photos);
      })

      mapPhotosToArray.then((result) => {
        dispatch(savePhotos(result));
      });
    });
  }
}

function savePhotos (photos) {
  return {
    type: 'GET_PHOTOS',
    photos
  }
}

loadPhotos is the thunk action exposed to my Redux containers. It returns a function that first calls the listObjects function in the utils file, passing it a callback that creates an array called photos.

Then, it creates a new Promise that loops through the results array returned by the listObjects utility function. In each iteration of this results array, I instantiate another new Promise that calls the getSingleObject utility.

Within that iteration, I push the results of getSingleObject into the photos array created within the callback passed into listObjects.

The last thing I do in the loadPhotos thunk action is call the outer Promise and then dispatch the result to the savePhotos action, which finally dispatches the payload object to the store for my reducer to catch.

This is how my reducer looks:

const defaultState = {
  photos: []
}

const photos = (state = defaultState, action) => {
  switch (action.type) {
    case 'GET_PHOTOS':
      return Object.assign({}, state, {
        photos: action.photos
      })
    default:
      return state;
  }
};

export default photos;

Here is how I've set up the entry point to the app:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, compose, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import photos from './reducers/';

import App from './components/app';

import styles from './styles/styles.css';

const createStoreWithMiddleware = compose(applyMiddleware(thunk))(createStore);

const store = createStoreWithMiddleware(photos, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
  <Provider store={ store }>
    <App />
  </Provider>,
  document.getElementById('root')
)

This is the App component rendered:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import AllPhotos from '../containers/AllPhotos';
import Navbar from './Navbar';

import '../styles/styles.css';

export default class App extends Component {
  constructor (props) {
    super (props);
  }

  render () {
    return (

        <Navbar />
        <AllPhotos />

    )
  }
}

Here is the AllPhotos container it renders:

import { connect } from 'react-redux';

import AllPhotos from '../components/AllPhotos';

import {
  loadPhotos
} from '../actions/index.js';

const mapDispatchToProps = (dispatch) => {
  return {
    loadPhotos: () => {
      dispatch(loadPhotos());
    }
  }
}

const mapStateToProps = (state) => {
  return {
    photos: state.photos
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AllPhotos);

And finally, this is the AllPhotos component:

import React, { Component } from 'react';
import _ from 'lodash';

export default class AllPhotos extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount () {
    this.props.loadPhotos();
  }

  render () {
    return (

Test

        { this._renderImages() }

    )
  }

  _renderImages () {
    _.map(this.props.photos, (image) => {
      return (

      )
    })
  }
}

This is what happens when I attempt to log this.props.photos within _renderImages:

The first log occurs before the photos array is populated and loaded into my state.

However, if I were to log the length of this.props.photos in the same area that I log just the array itself, this is what I see:

When I call Array.isArray on this.props.photos in that same line, this is what I get:

I have also attempted to convert this into an array using Array.from, but have not been successful.

Going a bit deeper, I attempted to find the length of the photos array from the action payload in my reducer, and still received 0 as the output. I also tried this within the savePhotos action, and found the same result.

As a result, I believe I may have not written my Promises correctly. Could someone help point me in the right direction?

Body:
You can try rewriting listObjects and getSingleObject to return Promises and utilising Promise.all.

Then you can write loadPhotos

export function loadPhotos () {
  return function (dispatch) {
    listObjects().then((results) =>
      Promise.all(results.map((singlePhoto) => getSingleObject(singlePhoto.Key)))
        .then((result) => dispatch(savePhotos(result)))
    )
  }
}


问:
How do I center the div vertically?

Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

```<code>.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}
</code>```

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

答:
If height of element is fixed, then do following

Css:

```<code>.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
**top:50%;**
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
**margin-top: -(half the height)**
}
</code>```

else to vertically center a div with dynamic height, you would need javascript..

```<code>document.getElementById('myElement').style.marginTop = (-1) * document.getElementById('myElement').offsetHeight / 2
</code>```

Title: How do I center the div vertically?

Body:
Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

Body:
If height of element is fixed, then do following

Css:

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
**top:50%;**
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
**margin-top: -(half the height)**
}

else to vertically center a div with dynamic height, you would need javascript..

document.getElementById('myElement').style.marginTop = (-1) * document.getElementById('myElement').offsetHeight / 2


问:
Is there a queue implementation?
Can anyone suggest Go container for simple and fast FIF/queue, Go has 3 different containers: heap, list and vector. Which one is more suitable to implement a queue?

答:
Slice can be used to implement queue.

```<code>type queue struct {
    values []*int
}

func New() *queue {
   queue := &queue{}
   return queue
}

func (q *queue) enqueue(val *int) {
   q.values = append(q.values, val)
}

//deque function
</code>```

Update:

here is complete implementation on my GitHub page https://github.com/raiskumar/algo-ds/blob/master/tree/queue.go

Title: Is there a queue implementation?

Body:
Slice can be used to implement queue.

type queue struct {
    values []*int
}

func New() *queue {
   queue := &queue{}
   return queue
}

func (q *queue) enqueue(val *int) {
   q.values = append(q.values, val)
}

//deque function

Update:

here is complete implementation on my GitHub page https://github.com/raiskumar/algo-ds/blob/master/tree/queue.go


问:
Environment variable not recognised when deploying to Elastic Beanstalk
I'm trying to deploy my Laravel application to Elastic Beanstalk in development mode. To make the application run in development mode rather than production, I've done the following in my /bootstrap/start.php file:

```<code>$env = $app->detectEnvironment(function() {
    return $_ENV['ENV_NAME'];
});
</code>```

To actually create the environment variable, I've created a .config file in the following path: /.ebextensions/00environmentVariables.config with these contents:

```<code>option_settings:
   - namespace: aws:elasticbeanstalk:application:environment
     option_name: ENV_NAME
     value: development
   - option_name: DB_HOST
     value: [redacted]
   - option_name: DB_PORT
     value: [redacted]
   - option_name: DB_NAME
     value: [redacted]
   - option_name: DB_USER
     value: [redacted]
   - option_name: DB_PASS
     value: [redacted]
</code>```

When I run eb start from the command line, it spins up an EC2 instance and attempts to provision it, at which point it tells me it fails. and to check the logs. In the logs, I can see these entries:

PHP Notice:  Undefined index: ENV_NAME in
  /var/app/ondeck/bootstrap/start.php on line 28

Notice: Undefined index: ENV_NAME in /var/app/ondeck/bootstrap/start.php on line 28

So for some reason, the ENV_NAME environment variable doesn't exist, even though I've specified it in 00environmentVariables.config. What's even weirder, is that I can see the environment variable does exist under the software configuration settings of the EB environment:

To summarize:

I know my .config files are being parsed from looking at the logs

For some reason my Laravel application still doesn't think that ENV_NAME eixsts

ENV_NAME eixsts both in the .config file and in my Elastic Beanstalk settings for this environment

EDIT

Alright so I worked out that the environment variables do work correctly when serving the application over the Apache HTTP server, but the environment variables don't exist when running the PHP CLI.

In the above logs, it's complaining about ENV_NAME not existing when running a /usr/bin/composer.phar install.

So, for some reason, my environment variables don't exist within the PHP CLI but they do work normally when serving over Apache.

FURTHER EDIT

So I SSH'd into the EC2 instance that's hosting my Laravel application on Elastic Beanstalk, and I can see the proper environment variables when I use the ``printenv command`:

```<code>ENV_NAME=development
</code>```

However, if I do a die(var_dump($_SERVER)); and run the PHP CLI, I don't see the environment variables that I've defined. Same story with $_ENV and getenv().

Why can't I access my environment variables within the PHP CLI, when I can access them when Apache processes my PHP scripts?

YET ANOTHER EDIT

I made a test.php file with one line: die(var_dump($_ENV));.

When I run this using php test.php I successfully get my custom environment variables coming out, so this seems like a composer only problem, not a PHP CLI problem.

答:
I created a job that creates .env file every 5 minutes.

Add the following to your .ebextensions

```<code>   "/opt/elasticbeanstalk/hooks/appdeploy/post/91_set_create_app_env_file_job.sh":
  mode: "000755"
  owner: root
  group: root
  content: |
    #!/usr/bin/env bash

    echo "Removing any existing CRON jobs..."
    crontab -r

    APP_ENV=/var/app/current/.env
    EB_ENVVARS=/opt/elasticbeanstalk/support/envvars
    CONSTANTS=/var/app/current/.constants
    CRON_CMD="grep -oE '[^ ]+$' $EB_ENVVARS > $APP_ENV; cat $CONSTANTS >> $APP_ENV"

    echo "Creating .env file...."
    eval $CRON_CMD

    echo "Scheduling .env file updater job to run every 5 minutes..."
    (crontab -l 2>/dev/null; echo "*/5 * * * * $CRON_CMD")| crontab -
</code>```

Reason I did it this way is that you may want to update your environment variables via the AWS UI Console.

This is the best solution in my opinion.

Body:
I'm trying to deploy my Laravel application to Elastic Beanstalk in development mode. To make the application run in development mode rather than production, I've done the following in my /bootstrap/start.php file:

$env = $app->detectEnvironment(function() {
    return $_ENV['ENV_NAME'];
});

To actually create the environment variable, I've created a .config file in the following path: /.ebextensions/00environmentVariables.config with these contents:

option_settings:
   - namespace: aws:elasticbeanstalk:application:environment
     option_name: ENV_NAME
     value: development
   - option_name: DB_HOST
     value: [redacted]
   - option_name: DB_PORT
     value: [redacted]
   - option_name: DB_NAME
     value: [redacted]
   - option_name: DB_USER
     value: [redacted]
   - option_name: DB_PASS
     value: [redacted]

When I run eb start from the command line, it spins up an EC2 instance and attempts to provision it, at which point it tells me it fails. and to check the logs. In the logs, I can see these entries:

PHP Notice:  Undefined index: ENV_NAME in
  /var/app/ondeck/bootstrap/start.php on line 28

Notice: Undefined index: ENV_NAME in /var/app/ondeck/bootstrap/start.php on line 28

So for some reason, the ENV_NAME environment variable doesn't exist, even though I've specified it in 00environmentVariables.config. What's even weirder, is that I can see the environment variable does exist under the software configuration settings of the EB environment:

To summarize:

I know my .config files are being parsed from looking at the logs

For some reason my Laravel application still doesn't think that ENV_NAME eixsts

ENV_NAME eixsts both in the .config file and in my Elastic Beanstalk settings for this environment

EDIT

Alright so I worked out that the environment variables do work correctly when serving the application over the Apache HTTP server, but the environment variables don't exist when running the PHP CLI.

In the above logs, it's complaining about ENV_NAME not existing when running a /usr/bin/composer.phar install.

So, for some reason, my environment variables don't exist within the PHP CLI but they do work normally when serving over Apache.

FURTHER EDIT

So I SSH'd into the EC2 instance that's hosting my Laravel application on Elastic Beanstalk, and I can see the proper environment variables when I use the ``printenv command`:

ENV_NAME=development

However, if I do a die(var_dump($_SERVER)); and run the PHP CLI, I don't see the environment variables that I've defined. Same story with $_ENV and getenv().

Why can't I access my environment variables within the PHP CLI, when I can access them when Apache processes my PHP scripts?

YET ANOTHER EDIT

I made a test.php file with one line: die(var_dump($_ENV));.

When I run this using php test.php I successfully get my custom environment variables coming out, so this seems like a composer only problem, not a PHP CLI problem.

Body:
I created a job that creates .env file every 5 minutes.

Add the following to your .ebextensions

   "/opt/elasticbeanstalk/hooks/appdeploy/post/91_set_create_app_env_file_job.sh":
  mode: "000755"
  owner: root
  group: root
  content: |
    #!/usr/bin/env bash

    echo "Removing any existing CRON jobs..."
    crontab -r

    APP_ENV=/var/app/current/.env
    EB_ENVVARS=/opt/elasticbeanstalk/support/envvars
    CONSTANTS=/var/app/current/.constants
    CRON_CMD="grep -oE '[^ ]+$' $EB_ENVVARS > $APP_ENV; cat $CONSTANTS >> $APP_ENV"

    echo "Creating .env file...."
    eval $CRON_CMD

    echo "Scheduling .env file updater job to run every 5 minutes..."
    (crontab -l 2>/dev/null; echo "*/5 * * * * $CRON_CMD")| crontab -

Reason I did it this way is that you may want to update your environment variables via the AWS UI Console.

This is the best solution in my opinion.


问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答:
Don't.

That is, for most cases you are better off generating the whole string in one go rather then appending to an existing string.

For example, don't do: obj1.name + ":" + str(obj1.count)

Instead: use "%s:%d" % (obj1.name, obj1.count)

That will be easier to read and more efficient.

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.


问:
Preserve Color-Depth of imported Images
When importing Images with the

loadImage("...")
```

<p>Command, iterating over the pixels in like this: </p>

<pre class="lang-java prettyprint-override"><code>img.loadPixels();
int w = img.width;
int h = img.height;
for (int y = 0; y < h; y++) {
  for (int x = 0; x < w; x++) {
    int loc = x + y*w;
    float r = red(img.pixels[loc]);
    float g = green(img.pixels[loc]);
    float b = blue(img.pixels[loc]);
    println(r + ", " + g + ", " + b);
  }
}
</code>```

The R G B Values always seem to be between 0 and 255 even if the image file has a depth of 16 bit per channel, where the values should be between 0 and 65535.
Is it possible to preserve the correct color depth?

答:
You haven't said which library the loadImage command is from.
There might be a 16-bit version, but it's unlikely. 24 bits is a sort of standard, suitable for all but very high end work.

What I suggest you do is take a look at my TIFF loader (which, like loadImage, returns 24 bit images), and modify it to return 16-bit channels. It's not difficult, just  a case of not discarding the lower bits of the larger channel images (float and 16 bit).

Her'e the TIFF loader:
https://github.com/MalcolmMcLean/tiffloader

Title: Preserve Color-Depth of imported Images

Body:
When importing Images with the

loadImage("...")

Command, iterating over the pixels in like this:

img.loadPixels();
int w = img.width;
int h = img.height;
for (int y = 0; y < h; y++) {
  for (int x = 0; x < w; x++) {
    int loc = x + y*w;
    float r = red(img.pixels[loc]);
    float g = green(img.pixels[loc]);
    float b = blue(img.pixels[loc]);
    println(r + ", " + g + ", " + b);
  }
}

The R G B Values always seem to be between 0 and 255 even if the image file has a depth of 16 bit per channel, where the values should be between 0 and 65535.
Is it possible to preserve the correct color depth?


问:
How to use Clarifai crop?
I can recognize image and check for prediction like nsfw,sfw,etc with the following sample code in objective-c.

```<code>  // Initialize the Clarifai app with your app's ID and Secret.
ClarifaiApp *app = [[ClarifaiApp alloc] initWithAppID:@""
                                            appSecret:@""];

// Fetch Clarifai's general model.
[app getModelByName:@"general-v1.3" completion:^(ClarifaiModel *model, NSError *error) {
    // Create a Clarifai image from a uiimage.
    ClarifaiImage *clarifaiImage = [[ClarifaiImage alloc] initWithImage:image];

    // Use Clarifai's general model to pedict tags for the given image.
    [model predictOnImages:@[clarifaiImage] completion:^(NSArray<ClarifaiOutput *> *outputs, NSError *error) {
        if (!error) {
            ClarifaiOutput *output = outputs[0];

            // Loop through predicted concepts (tags), and display them on the screen.
            NSMutableArray *tags = [NSMutableArray array];
            for (ClarifaiConcept *concept in output.concepts) {
                [tags addObject:concept.conceptName];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                self.textView.text = [NSString stringWithFormat:@"Tags:\n%@", [tags componentsJoinedByString:@", "]];
            });
        }

      dispatch_async(dispatch_get_main_queue(), ^{
        self.button.enabled = YES;
      });

    }];
}];
</code>```

For this I can get model and from that model i can predict images.

Question:

How can I make the crop function?
I am not getting a way to reach the crop functionality available in Clarifai .

Any ideas.

答:
You can create a crop using the ClarifaiCrop class and using it to initialize a ClarifaiImage.

```<code>ClarifaiCrop *crop = [[ClarifaiCrop alloc] initWithTop:0.1
                                                  left:0.1
                                                bottom:0.1
                                                 right:0.1];
</code>```

Where top, left, bottom, and right are percentages (between 0 and 1) of the distances from the borders of the image to the region of interest. In the example above the image would be cropped 10% from each margin.

```<code>ClarifaiImage *clarifaiImage = [[ClarifaiImage alloc] initWithImage:image
                                                            andCrop:crop];
</code>```

Title: How to use Clarifai crop?

Body:
I can recognize image and check for prediction like nsfw,sfw,etc with the following sample code in objective-c.

  // Initialize the Clarifai app with your app's ID and Secret.
ClarifaiApp *app = [[ClarifaiApp alloc] initWithAppID:@""
                                            appSecret:@""];

// Fetch Clarifai's general model.
[app getModelByName:@"general-v1.3" completion:^(ClarifaiModel *model, NSError *error) {
    // Create a Clarifai image from a uiimage.
    ClarifaiImage *clarifaiImage = [[ClarifaiImage alloc] initWithImage:image];

    // Use Clarifai's general model to pedict tags for the given image.
    [model predictOnImages:@[clarifaiImage] completion:^(NSArray<ClarifaiOutput *> *outputs, NSError *error) {
        if (!error) {
            ClarifaiOutput *output = outputs[0];

            // Loop through predicted concepts (tags), and display them on the screen.
            NSMutableArray *tags = [NSMutableArray array];
            for (ClarifaiConcept *concept in output.concepts) {
                [tags addObject:concept.conceptName];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                self.textView.text = [NSString stringWithFormat:@"Tags:\n%@", [tags componentsJoinedByString:@", "]];
            });
        }

      dispatch_async(dispatch_get_main_queue(), ^{
        self.button.enabled = YES;
      });

    }];
}];

For this I can get model and from that model i can predict images.

Question:

How can I make the crop function?
I am not getting a way to reach the crop functionality available in Clarifai .

Any ideas.

Body:
You can create a crop using the ClarifaiCrop class and using it to initialize a ClarifaiImage.

ClarifaiCrop *crop = [[ClarifaiCrop alloc] initWithTop:0.1
                                                  left:0.1
                                                bottom:0.1
                                                 right:0.1];

Where top, left, bottom, and right are percentages (between 0 and 1) of the distances from the borders of the image to the region of interest. In the example above the image would be cropped 10% from each margin.

ClarifaiImage *clarifaiImage = [[ClarifaiImage alloc] initWithImage:image
                                                            andCrop:crop];