问:
undefined reference compiling taskwarrior on arm chromebook
I tried to build task-2.5.1 on my armv81 chromebook inside a termux session. It didn't work due build dependencies so I installed them then uncompressed and started in a fresh new directory. When I ran make VERBOSE=1 I got an undefined reference to __atomic_fetch_add_4 when linking...

[ 98%] Linking CXX executable lex
cd /data/data/com.termux/files/home/src/task-2.5.1/src && /data/data/com.termux/files/usr/bin/cmake -E cmake_link_script CMakeFiles/lex_executable.dir/link.txt --verbose=1
/data/data/com.termux/files/usr/bin/c++  -Wall -Wsign-compare -Wreturn-type -std=c++11 -stdlib=libc++  -O3 -DNDEBUG  -rdynamic CMakeFiles/lex_executable.dir/lex.cpp.o  -o lex libtask.a commands/libcommands.a columns/libcolumns.a libtask.a -lgnutls -luuid
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::Nibbler(Nibbler const&)':
Nibbler.cpp:(.text+0x8c): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::operator=(Nibbler const&)':
Nibbler.cpp:(.text+0xe0): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: Nibbler.cpp:(.text+0x104): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::~Nibbler()':
Nibbler.cpp:(.text+0x174): undefined reference to `__atomic_fetch_add_4'
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [src/CMakeFiles/lex_executable.dir/build.make:90: src/lex] Error 1
make[2]: Leaving directory '/data/data/com.termux/files/home/src/task-2.5.1'
make[1]: *** [CMakeFiles/Makefile2:175: src/CMakeFiles/lex_executable.dir/all] Error 2
make[1]: Leaving directory '/data/data/com.termux/files/home/src/task-2.5.1'
make: *** [Makefile:152: all] Error 2
```

I found this discussion about undefined references in arm builds. I tried adding a -latomic to CMakeFiles/task_executable.dir/link.txt but it didn't change the output.

Any ideas how to fix this?

答: Many thanks to wbsch in this issue (posted just after this one) for the link to the known fix which was successful on my machine, removing the three lines from CMakeLists.txt.</p>

Body:
I tried to build task-2.5.1 on my armv81 chromebook inside a termux session. It didn't work due build dependencies so I installed them then uncompressed and started in a fresh new directory. When I ran make VERBOSE=1 I got an undefined reference to __atomic_fetch_add_4 when linking...

[ 98%] Linking CXX executable lex
cd /data/data/com.termux/files/home/src/task-2.5.1/src && /data/data/com.termux/files/usr/bin/cmake -E cmake_link_script CMakeFiles/lex_executable.dir/link.txt --verbose=1
/data/data/com.termux/files/usr/bin/c++  -Wall -Wsign-compare -Wreturn-type -std=c++11 -stdlib=libc++  -O3 -DNDEBUG  -rdynamic CMakeFiles/lex_executable.dir/lex.cpp.o  -o lex libtask.a commands/libcommands.a columns/libcolumns.a libtask.a -lgnutls -luuid
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::Nibbler(Nibbler const&)':
Nibbler.cpp:(.text+0x8c): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::operator=(Nibbler const&)':
Nibbler.cpp:(.text+0xe0): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: Nibbler.cpp:(.text+0x104): undefined reference to `__atomic_fetch_add_4'
/data/data/com.termux/files/usr/bin/arm-linux-androideabi-ld: libtask.a(Nibbler.cpp.o): in function `Nibbler::~Nibbler()':
Nibbler.cpp:(.text+0x174): undefined reference to `__atomic_fetch_add_4'
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [src/CMakeFiles/lex_executable.dir/build.make:90: src/lex] Error 1
make[2]: Leaving directory '/data/data/com.termux/files/home/src/task-2.5.1'
make[1]: *** [CMakeFiles/Makefile2:175: src/CMakeFiles/lex_executable.dir/all] Error 2
make[1]: Leaving directory '/data/data/com.termux/files/home/src/task-2.5.1'
make: *** [Makefile:152: all] Error 2

I found this discussion about undefined references in arm builds. I tried adding a -latomic to CMakeFiles/task_executable.dir/link.txt but it didn't change the output.

Any ideas how to fix this?


来源: stackexchange

问:
Easier way to check for four in row/column/diagonal in connect four game?
I am making a connect four game with X's and O's. The code for checking for four in a row/column/diagonal works but I have a lot of if statements in my code. The game fully works right now but I'm wondering if there is an easier solution to the checking. Below, I have included all my code for context.

I have tried using coordinates. It seems kind of inefficient though. The function for checking is called check.

```<code>namex = input("Player X, enter your name. ") #asks for player 1 name
nameo = input("Player O, enter your name. ") #asks for player 2 name

game = [[".", ".", ".", ".", ".", "."], #gameboard
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."]]

loop = True
def output(matrix):
    str1 = ""
    str2 = ""
    str3 = ""
    str4 = ""
    str5 = ""
    str6 = ""
    print("0 1 2 3 4 5 6 ") #print labels for columns in gameboard
    for a in matrix:
        row = 0
        for b in a: #"a" is a column and "b" is a ./x/o
            row += 1
            if row == 1:
                str1 += b
                str1 += " "
            if row == 2:
                str2 += b
                str2 += " "
            if row == 3:
                str3 += b
                str3 += " "
            if row == 4:
                str4 += b
                str4 += " "
            if row == 5:
                str5 += b
                str5 += " "
            if row == 6:
                str6 += b
                str6 += " "
    print(str1) #print string for row 1
    print(str2) #print string for row 2
    print(str3) #print string for row 3
    print(str4) #print string for row 4
    print(str5) #print string for row 5
    print(str6) #print string for row 6

def check(matrix): #function to check for four in row/column/diagonal to win
    positionx = []
    positiono = []
    x = 0
    for a in matrix:
        y = 5
        for b in a:
            if b == "X":
                positionx.append([x, y])
            if b == "O":
                positiono.append([x, y])
            y -= 1
        x += 1

    for c1 in positionx:
        '''check four in row/column/diagonal for x'''
        for c2 in positionx:
            for c3 in positionx:
                for c4 in positionx:
                    if c4[0]-c3[0] == 1:#check for four in row
                        if c3[0]-c2[0] == 1:
                            if c2[0]-c1[0] == 1:
                                return "xwin"
                    if c4[1]-c3[1] == 1: #check for four in column
                        if c3[1]-c2[1] == 1:
                            if c2[1]-c1[1] == 1:
                                return "xwin"
                    if c4[0]-c3[0] == 1: #check four in diagonal
                        if c4[1]-c3[1] == 1:
                            if c3[0]-c2[0] == 1:
                                if c3[1]-c2[1] == 1:
                                    if c2[0]-c1[0] == 1:
                                        if c2[1]-c1[1] == 1:
                                            return "xwin"
    for d1 in positiono:
        '''check four in row/column/diagonal for o'''
        for d2 in positiono:
            for d3 in positiono:
                for d4 in positiono:
                    if d4[0]-d3[0] == 1: #check for four in row
                        if d3[0]-d2[0] == 1:
                            if d2[0]-d1[0] == 1:
                                return "owin"
                    if d4[1]-d3[1] == 1: #check for four in column
                        if d3[1]-d2[1] == 1:
                            if d2[1]-d1[1] == 1:
                                return "owin"
                    if d4[0]-d3[0] == 1: #check four in diagonal
                        if d4[1]-d3[1] == 1:
                            if d3[0]-d2[0] == 1:
                                if d3[1]-d2[1] == 1:
                                    if d2[0]-d1[0] == 1:
                                        if d2[1]-d1[1] == 1:
                                            return "owin"
while loop == True:

xinput = input(namex + ", you're X. What column do you want to play in? Please enter a number 0-6 ")
xcolumn = int(xinput)
xrow = 5
occupied1 = False
while occupied1 == False:
    if game[xcolumn][xrow] == ".": #if there is a "." change to "X"
        game[xcolumn][xrow] = "X"
        output(game)
        occupied1 = True
    xrow -= 1
if check(game) == "xwin":
    loop = False
    print(namex + " wins!")
    break
if check(game) == "owin":
    loop = False
    print(nameo + " wins!")
    break
oinput = input(nameo + ", you're O. What column do you want to play in? Please enter number 0-6 ")
ocolumn = int(oinput)
orow = 5
occupied2 = False
while occupied2 == False:
    if game[ocolumn][orow] == ".": #if there is a "." change to "O"
        game[ocolumn][orow] = "O"
        output(game)
        occupied2 = True
    orow -= 1
if check(game) == "xwin":
    loop = False
    print(namex + " wins!")
    break
if check(game) == "owin":
    loop = False
    print(nameo + " wins!")
    break
</code>```

I'm also open to any other suggestions to make my code for this game better. Thanks!

答:
A good start would be to write a generalized function that checks for a diagonal at an arbitrary location:

```<code>def diagonal(grid, x, y, piece):
    '''
    Return True if grid contains a four-in-a-row diagonal starting at coordinates
    (x, y) and traveling downwards and to the right.  Otherwise return False.
    '''

    for i in range(x, x+4):
        # if this square does not contain the desired piece, return False
        if grid[x+i][y+i] != piece
            return False
    # if we got all the way through the loop, this must be a diagonal
    return True
</code>```

Then you would call this function for every possible starting coordinate of a four square diagonal, for each player X and O.

To improve this function, you could add a way to check for diagonals that travel the other direction (up and to the right).

ContentLicense: CC BY-SA 4.0

Body:
I am making a connect four game with X's and O's. The code for checking for four in a row/column/diagonal works but I have a lot of if statements in my code. The game fully works right now but I'm wondering if there is an easier solution to the checking. Below, I have included all my code for context.

I have tried using coordinates. It seems kind of inefficient though. The function for checking is called check.

namex = input("Player X, enter your name. ") #asks for player 1 name
nameo = input("Player O, enter your name. ") #asks for player 2 name

game = [[".", ".", ".", ".", ".", "."], #gameboard
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."],
    [".", ".", ".", ".", ".", "."]]

loop = True
def output(matrix):
    str1 = ""
    str2 = ""
    str3 = ""
    str4 = ""
    str5 = ""
    str6 = ""
    print("0 1 2 3 4 5 6 ") #print labels for columns in gameboard
    for a in matrix:
        row = 0
        for b in a: #"a" is a column and "b" is a ./x/o
            row += 1
            if row == 1:
                str1 += b
                str1 += " "
            if row == 2:
                str2 += b
                str2 += " "
            if row == 3:
                str3 += b
                str3 += " "
            if row == 4:
                str4 += b
                str4 += " "
            if row == 5:
                str5 += b
                str5 += " "
            if row == 6:
                str6 += b
                str6 += " "
    print(str1) #print string for row 1
    print(str2) #print string for row 2
    print(str3) #print string for row 3
    print(str4) #print string for row 4
    print(str5) #print string for row 5
    print(str6) #print string for row 6

def check(matrix): #function to check for four in row/column/diagonal to win
    positionx = []
    positiono = []
    x = 0
    for a in matrix:
        y = 5
        for b in a:
            if b == "X":
                positionx.append([x, y])
            if b == "O":
                positiono.append([x, y])
            y -= 1
        x += 1

    for c1 in positionx:
        '''check four in row/column/diagonal for x'''
        for c2 in positionx:
            for c3 in positionx:
                for c4 in positionx:
                    if c4[0]-c3[0] == 1:#check for four in row
                        if c3[0]-c2[0] == 1:
                            if c2[0]-c1[0] == 1:
                                return "xwin"
                    if c4[1]-c3[1] == 1: #check for four in column
                        if c3[1]-c2[1] == 1:
                            if c2[1]-c1[1] == 1:
                                return "xwin"
                    if c4[0]-c3[0] == 1: #check four in diagonal
                        if c4[1]-c3[1] == 1:
                            if c3[0]-c2[0] == 1:
                                if c3[1]-c2[1] == 1:
                                    if c2[0]-c1[0] == 1:
                                        if c2[1]-c1[1] == 1:
                                            return "xwin"
    for d1 in positiono:
        '''check four in row/column/diagonal for o'''
        for d2 in positiono:
            for d3 in positiono:
                for d4 in positiono:
                    if d4[0]-d3[0] == 1: #check for four in row
                        if d3[0]-d2[0] == 1:
                            if d2[0]-d1[0] == 1:
                                return "owin"
                    if d4[1]-d3[1] == 1: #check for four in column
                        if d3[1]-d2[1] == 1:
                            if d2[1]-d1[1] == 1:
                                return "owin"
                    if d4[0]-d3[0] == 1: #check four in diagonal
                        if d4[1]-d3[1] == 1:
                            if d3[0]-d2[0] == 1:
                                if d3[1]-d2[1] == 1:
                                    if d2[0]-d1[0] == 1:
                                        if d2[1]-d1[1] == 1:
                                            return "owin"
while loop == True:

xinput = input(namex + ", you're X. What column do you want to play in? Please enter a number 0-6 ")
xcolumn = int(xinput)
xrow = 5
occupied1 = False
while occupied1 == False:
    if game[xcolumn][xrow] == ".": #if there is a "." change to "X"
        game[xcolumn][xrow] = "X"
        output(game)
        occupied1 = True
    xrow -= 1
if check(game) == "xwin":
    loop = False
    print(namex + " wins!")
    break
if check(game) == "owin":
    loop = False
    print(nameo + " wins!")
    break
oinput = input(nameo + ", you're O. What column do you want to play in? Please enter number 0-6 ")
ocolumn = int(oinput)
orow = 5
occupied2 = False
while occupied2 == False:
    if game[ocolumn][orow] == ".": #if there is a "." change to "O"
        game[ocolumn][orow] = "O"
        output(game)
        occupied2 = True
    orow -= 1
if check(game) == "xwin":
    loop = False
    print(namex + " wins!")
    break
if check(game) == "owin":
    loop = False
    print(nameo + " wins!")
    break

I'm also open to any other suggestions to make my code for this game better. Thanks!

Body:
A good start would be to write a generalized function that checks for a diagonal at an arbitrary location:

def diagonal(grid, x, y, piece):
    '''
    Return True if grid contains a four-in-a-row diagonal starting at coordinates
    (x, y) and traveling downwards and to the right.  Otherwise return False.
    '''

    for i in range(x, x+4):
        # if this square does not contain the desired piece, return False
        if grid[x+i][y+i] != piece
            return False
    # if we got all the way through the loop, this must be a diagonal
    return True

Then you would call this function for every possible starting coordinate of a four square diagonal, for each player X and O.

To improve this function, you could add a way to check for diagonals that travel the other direction (up and to the right).


问:
How to merge two .txt files into one, matching each line by timestamp, using awk
Summary:

I currently have two .txt files imported from a survey system I am testing. Column 1 of each data file is a timestamp of the format "HHMMSS.SSSSSS". In file1, there is a second column of field intensity readings. In file2 there are two additional columns of positional information. I'm attempting to write a script that matches data points between these files by lining the timestamps up. The issue is that at no point are any of the timestamps the exact same value. The script must be able to match data points (lines in each .txt file) based the timestamp of its closest counterpart in the other file (i.e. the time 125051.354948 from file1 should "match" the nearest timestamp in file2, which is 125051.112784).

If anyone with a little bit more awk/sed/join/regex/Unix knowledge could point me in the right direction, I would be very appreciative.

What I have so far:

(Please note that the exact syntax shown here may not make sense for the sample .txt files attached in this question, there are more extensive versions of these files with more columns that were being used for testing scripts.)

I'm new to awk/Unix/shell scripting so please bear with me if some of these trial solutions don't work or don't make a whole lot of sense.

I have already attempted some solutions posted here on stack overflow using join, but it doesn't seem to want to properly sort or join either of these files:

```<code>    ${
      join -o 1.1,2.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1 file2)
      join -v 1 -o 1.1,1.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1
    file2)
    } | sort -k 1
</code>```

Result: only outputs a similar version of the original file2

I attempted to reconfigure existing awk solutions that were posted here as well:

```<code>    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$3]=$2; next} {print $1, (v[$3] ?
    v[$3] : 0)}' file1 file2 > file3

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$1]=$2; next} {print $1, (v[$1] ?
    v[$1] : 0)}' file1 file2 > file3
</code>```

Result: both of these awk commands result in the output of file2's
data with nothing from file1 included (or so it seems).

```<code>awk -F '
FNR == NR {
    time[$3]
    next
}
{   for(i in time)
        if(index($3, i) == 1) {
            print
            next

        }
}' file1 file2 > file3
</code>```

Result: keeps returning a syntax error regarding the "." of ".txt"

I looked into integrating some sort of regex or split command to the script... but was confused as to how to proceed and didn't come up with anything of substance.

Sample Data

```<code>    $ cat file1.txt

    125051.354948 058712.429

    125052.352475 058959.934

    125054.354322 058842.619

    125055.352671 058772.045

    125057.351794 058707.281

    125058.352678 058758.959

    $ cat file2.txt

    125050.105886 4413.34358 07629.87620

    125051.112784 4413.34369 07629.87606

    125052.100811 4413.34371 07629.87605

    125053.097826 4413.34373 07629.87603

    125054.107361 4413.34373 07629.87605

    125055.107038 4413.34375 07629.87604

    125056.093783 4413.34377 07629.87602

    125057.097928 4413.34378 07629.87603

    125058.098475 4413.34378 07629.87606

    125059.095787 4413.34376 07629.87602
</code>```

Expected Result:

(Format: Column1File1 Column1File2 Column2File1 Column2File2 Column3File2)

```<code>    $ cat file3.txt

    125051.354948 125051.112784 058712.429 4413.34358 07629.87620

    125052.352475 125052.100811 058959.934 4413.34371 07629.87605

    125054.354322 125054.107361 058842.619 4413.34373 07629.87605

    125055.352671 125055.107038 058772.045 4413.34375 07629.87604

    125057.351794 125057.097928 058707.281 4413.34378 07629.87603

    125058.352678 125058.098475 058758.959 4413.34378 07629.87606
</code>```

As shown, not every data point from each file will find a match. Only pairs of lines that have the most proximal timestamps to one another will be written over to the new file

As previously mentioned, current solutions result in file3 being entirely blank, or just containing information from one of the two files (but not both)

答:
Please try the following:

```<code>awk '
    # find the closest element in "a" to val and return the index
    function binsearch(a, val, len,
        low, high, mid) {
        if (val < a[1])
            return 1
        if (val > a[len])
            return len

        low = 1
        high = len
        while (low <= high) {
            mid = int((low + high) / 2)
            if (val < a[mid])
                high = mid - 1
            else if (val > a[mid])
                low = mid + 1
            else
                return mid
        }
        return (val - a[low]) < (a[high] - val) ? high : low
    }
    NR == FNR {
        time[FNR] = $1
        position[FNR] = $2
        intensity[FNR] = $3
        len++
        next
    }
    {
        i = binsearch(time, $1, len)
        print $1 " " time[i] " " $2 " " position[i] " " intensity[i]
    }
' file2.txt file1.txt
</code>```

Result:

```<code>125051.354948 125051.112784 058712.429 4413.34369 07629.87606
125052.352475 125052.100811 058959.934 4413.34371 07629.87605
125054.354322 125054.107361 058842.619 4413.34373 07629.87605
125055.352671 125055.107038 058772.045 4413.34375 07629.87604
125057.351794 125057.097928 058707.281 4413.34378 07629.87603
125058.352678 125058.098475 058758.959 4413.34378 07629.87606
</code>```

Note that the 4th and 5th values in your expected result may be wrongly copy-and-pasted.

[How it works]

The key is the binsearch function which finds the closest value in the
array and returns the index to the array. I would not mention about
the algorithm in detail because it is a common "binary search" technique.

Body:
Summary:

I currently have two .txt files imported from a survey system I am testing. Column 1 of each data file is a timestamp of the format "HHMMSS.SSSSSS". In file1, there is a second column of field intensity readings. In file2 there are two additional columns of positional information. I'm attempting to write a script that matches data points between these files by lining the timestamps up. The issue is that at no point are any of the timestamps the exact same value. The script must be able to match data points (lines in each .txt file) based the timestamp of its closest counterpart in the other file (i.e. the time 125051.354948 from file1 should "match" the nearest timestamp in file2, which is 125051.112784).

If anyone with a little bit more awk/sed/join/regex/Unix knowledge could point me in the right direction, I would be very appreciative.

What I have so far:

(Please note that the exact syntax shown here may not make sense for the sample .txt files attached in this question, there are more extensive versions of these files with more columns that were being used for testing scripts.)

I'm new to awk/Unix/shell scripting so please bear with me if some of these trial solutions don't work or don't make a whole lot of sense.

I have already attempted some solutions posted here on stack overflow using join, but it doesn't seem to want to properly sort or join either of these files:

    ${
      join -o 1.1,2.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1 file2)
      join -v 1 -o 1.1,1.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1
    file2)
    } | sort -k 1

Result: only outputs a similar version of the original file2

I attempted to reconfigure existing awk solutions that were posted here as well:

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$3]=$2; next} {print $1, (v[$3] ?
    v[$3] : 0)}' file1 file2 > file3

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$1]=$2; next} {print $1, (v[$1] ?
    v[$1] : 0)}' file1 file2 > file3

Result: both of these awk commands result in the output of file2's
data with nothing from file1 included (or so it seems).

awk -F '
FNR == NR {
    time[$3]
    next
}
{   for(i in time)
        if(index($3, i) == 1) {
            print
            next

        }
}' file1 file2 > file3

Result: keeps returning a syntax error regarding the "." of ".txt"

I looked into integrating some sort of regex or split command to the script... but was confused as to how to proceed and didn't come up with anything of substance.

Sample Data

    $ cat file1.txt

    125051.354948 058712.429

    125052.352475 058959.934

    125054.354322 058842.619

    125055.352671 058772.045

    125057.351794 058707.281

    125058.352678 058758.959

    $ cat file2.txt

    125050.105886 4413.34358 07629.87620

    125051.112784 4413.34369 07629.87606

    125052.100811 4413.34371 07629.87605

    125053.097826 4413.34373 07629.87603

    125054.107361 4413.34373 07629.87605

    125055.107038 4413.34375 07629.87604

    125056.093783 4413.34377 07629.87602

    125057.097928 4413.34378 07629.87603

    125058.098475 4413.34378 07629.87606

    125059.095787 4413.34376 07629.87602

Expected Result:

(Format: Column1File1 Column1File2 Column2File1 Column2File2 Column3File2)

    $ cat file3.txt

    125051.354948 125051.112784 058712.429 4413.34358 07629.87620

    125052.352475 125052.100811 058959.934 4413.34371 07629.87605

    125054.354322 125054.107361 058842.619 4413.34373 07629.87605

    125055.352671 125055.107038 058772.045 4413.34375 07629.87604

    125057.351794 125057.097928 058707.281 4413.34378 07629.87603

    125058.352678 125058.098475 058758.959 4413.34378 07629.87606

As shown, not every data point from each file will find a match. Only pairs of lines that have the most proximal timestamps to one another will be written over to the new file

As previously mentioned, current solutions result in file3 being entirely blank, or just containing information from one of the two files (but not both)

Body:
Please try the following:

awk '
    # find the closest element in "a" to val and return the index
    function binsearch(a, val, len,
        low, high, mid) {
        if (val < a[1])
            return 1
        if (val > a[len])
            return len

        low = 1
        high = len
        while (low <= high) {
            mid = int((low + high) / 2)
            if (val < a[mid])
                high = mid - 1
            else if (val > a[mid])
                low = mid + 1
            else
                return mid
        }
        return (val - a[low]) < (a[high] - val) ? high : low
    }
    NR == FNR {
        time[FNR] = $1
        position[FNR] = $2
        intensity[FNR] = $3
        len++
        next
    }
    {
        i = binsearch(time, $1, len)
        print $1 " " time[i] " " $2 " " position[i] " " intensity[i]
    }
' file2.txt file1.txt

Result:

125051.354948 125051.112784 058712.429 4413.34369 07629.87606
125052.352475 125052.100811 058959.934 4413.34371 07629.87605
125054.354322 125054.107361 058842.619 4413.34373 07629.87605
125055.352671 125055.107038 058772.045 4413.34375 07629.87604
125057.351794 125057.097928 058707.281 4413.34378 07629.87603
125058.352678 125058.098475 058758.959 4413.34378 07629.87606

Note that the 4th and 5th values in your expected result may be wrongly copy-and-pasted.

[How it works]

The key is the binsearch function which finds the closest value in the
array and returns the index to the array. I would not mention about
the algorithm in detail because it is a common "binary search" technique.


问:
I am getting an infinite loop when I run my program. How do I fix it?
Output of the code
This is a finance problem I was working on. I have a loop set up but after it displays all of the correct values, it displays all "0" for every variable infinitely. My Python versions is 3.6.7 running on Ubuntu.

I have tried to set it up so the current_balance is greater than the ending_balance but the problem is still there.

price = float(input("Enter initial price: "))
INTEREST_RATE = 0.12 / 12
DOWN_PAYMENT = price * .9
monthly_payment = 0
ending_balance = 0
interest = 0
principal = 0
month = 0

print("%s%18s%10s%11s%9s%13s" % ("Month", "Current Balance", "Interest", "Principal", "Payment", "End Balance"))

month = 1
current_balance = DOWN_PAYMENT
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal

while ending_balance > 0:
    print("%d%18.2f%10.2f%11.2f%9.2f%13.2f" % (month, current_balance, interest, principal, monthly_payment, ending_balance))
    month += 1
    current_balance = ending_balance
    interest = current_balance * INTEREST_RATE
    monthly_payment = current_balance * 0.05
    principal = monthly_payment - interest
    ending_balance = current_balance - principal
```

There are no errors, just an infinite loop. The program should be over once ending_balance = 0.

答:
Floating point is your problem.  To end the loop use:

```<code>while ending_balance >= 0.005:
</code>```

The current balance is always getting smaller, but you only show two decimal digits.

Body:
Output of the code
This is a finance problem I was working on. I have a loop set up but after it displays all of the correct values, it displays all "0" for every variable infinitely. My Python versions is 3.6.7 running on Ubuntu.

I have tried to set it up so the current_balance is greater than the ending_balance but the problem is still there.

price = float(input("Enter initial price: "))
INTEREST_RATE = 0.12 / 12
DOWN_PAYMENT = price * .9
monthly_payment = 0
ending_balance = 0
interest = 0
principal = 0
month = 0

print("%s%18s%10s%11s%9s%13s" % ("Month", "Current Balance", "Interest", "Principal", "Payment", "End Balance"))

month = 1
current_balance = DOWN_PAYMENT
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal

while ending_balance > 0:
    print("%d%18.2f%10.2f%11.2f%9.2f%13.2f" % (month, current_balance, interest, principal, monthly_payment, ending_balance))
    month += 1
    current_balance = ending_balance
    interest = current_balance * INTEREST_RATE
    monthly_payment = current_balance * 0.05
    principal = monthly_payment - interest
    ending_balance = current_balance - principal

There are no errors, just an infinite loop. The program should be over once ending_balance = 0.

Body:
Floating point is your problem.  To end the loop use:

while ending_balance >= 0.005:

The current balance is always getting smaller, but you only show two decimal digits.


问:
"bios.lua:26: [string "turbinecontrol"]:15: 'then' expected" I have no idea why this is happening
Trying to control my extremereactor turbines with a computer so i dont have to keep managing them, im quite new to lua in general so i would really like some help with this and maybe some extra advice on other things that could go wrong/im doing wrong and i am planning to have a monitor displaying stats from the turbines and be able to turn them on/off once i figure out how to do that</p>

```<code>turbine1 = peripheral.wrap("top")
turbine2 = peripheral.wrap("right") -- i know doing this is probably wrong

turbine1.setActive(true)
turbine2.setActive(true)

turbine1.setVentOverflow(true)
turbine2.setVentOverflow(true)

turbine1.setFluidFlowRateMax(2000)
turbine2.setFluidFlowRateMax(2000)

while true do then
  if turbine1.getRotorSpeed() >= 20000
    turbine1.setInductorEngaged(true) -- line which its complaining about with "bios.lua:26: [string "turbinecontrol"]:15: 'then' expected"
    print("Turbine 1 Inductor Engaged")
    wait(5)
    print("Turbine 1 Generating" ... turbine1.getEnergyProducedLastTick())
  end

  if turbine1.getRotorSpeed() < 10000
    turbine1.setInductorEngaged(false)
    print("Turbine 1 Inductor Disengaged")
  end

  if turbine2.getRotorSpeed() >= 20000
    turbine2.setInductorEngaged(true)
    print("Turbine 2 Inductor Engaged")
    wait(5)
    print("Turbine 2 Generating" ... turbine2.getEnergyProducedLastTick())
  end

  if turbine2.getRotorSpeed() < 10000
    turbine2.setInductorEngaged(false)
    print("Turbine 2 Inductor Disengaged")
  end

end```
</code>```

答:
Your syntax is a little off.
Firstly, you've got while true do then on line 14 when this should only be while true do, secondly, whenever you've got an if statement, eg. if turbine1.getRotorSpeed() >= 20000 you need a then to terminate the condition. Thus this should look like if turbine1.getRotorSpeed() >= 20000 then

Body:
Trying to control my extremereactor turbines with a computer so i dont have to keep managing them, im quite new to lua in general so i would really like some help with this and maybe some extra advice on other things that could go wrong/im doing wrong and i am planning to have a monitor displaying stats from the turbines and be able to turn them on/off once i figure out how to do that

turbine1 = peripheral.wrap("top")
turbine2 = peripheral.wrap("right") -- i know doing this is probably wrong

turbine1.setActive(true)
turbine2.setActive(true)

turbine1.setVentOverflow(true)
turbine2.setVentOverflow(true)

turbine1.setFluidFlowRateMax(2000)
turbine2.setFluidFlowRateMax(2000)

while true do then
  if turbine1.getRotorSpeed() >= 20000
    turbine1.setInductorEngaged(true) -- line which its complaining about with "bios.lua:26: [string "turbinecontrol"]:15: 'then' expected"
    print("Turbine 1 Inductor Engaged")
    wait(5)
    print("Turbine 1 Generating" ... turbine1.getEnergyProducedLastTick())
  end

  if turbine1.getRotorSpeed() < 10000
    turbine1.setInductorEngaged(false)
    print("Turbine 1 Inductor Disengaged")
  end

  if turbine2.getRotorSpeed() >= 20000
    turbine2.setInductorEngaged(true)
    print("Turbine 2 Inductor Engaged")
    wait(5)
    print("Turbine 2 Generating" ... turbine2.getEnergyProducedLastTick())
  end

  if turbine2.getRotorSpeed() < 10000
    turbine2.setInductorEngaged(false)
    print("Turbine 2 Inductor Disengaged")
  end

end```


问:
php large xml parse it with paging
I have a large XML file with 22000 records that I have to import in my DB.

I am looking how to parse the xml with paging, meaning

```<code>parse.php?start=0; //this script get the 0-500 firt records of file
parse.php?start=500 //this script get the 500-1000 records of file
</code>```

This way I can bypass memory problems.

My problem is how to point at record 500 when load the xml file

My code is simple

```<code>$data=simplexml_load_file($xmlFile);

foreach ($data->product as $product) {
   foreach($product->children() as $section) {
       addToDB($section);
   }
}
</code>```

The code above works fine for 1000-2000 records but I want to modify as mentioned to work with large XMLs

答:
That's not possible.

You should use XMLReader to import large files as described in my blog post.

ContentLicense: CC BY-SA 3.0

Title: php large xml parse it with paging

Body:
I have a large XML file with 22000 records that I have to import in my DB.

I am looking how to parse the xml with paging, meaning

parse.php?start=0; //this script get the 0-500 firt records of file
parse.php?start=500 //this script get the 500-1000 records of file

This way I can bypass memory problems.

My problem is how to point at record 500 when load the xml file

My code is simple

$data=simplexml_load_file($xmlFile);

foreach ($data->product as $product) {
   foreach($product->children() as $section) {
       addToDB($section);
   }
}

The code above works fine for 1000-2000 records but I want to modify as mentioned to work with large XMLs


问:
How to accomodate different arguments for entity class
I am calling my entity class in an if/else-if statement for 2 different conditions and the values I pass into the parameters depend on the condition.  In the if block, I am passing 3 parameters and in the else-if block, I am passing 4.  The entity's object is throwing an error because it is expecting 4 parameters.  I want the first parameter to be optional and I'd like to know if there is a way to do that in Kotlin.

This is my entity class:

```<code>@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null,

    val username: String? = null,
    val hint: String? = null,
    val password: String? = null)
</code>```

And this is the if/else-if block where I'm inserting values into the entity object:

```<code>if (requestCode == ADD_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(username, hint, password)
            ...

        } else if (requestCode == EDIT_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(id, username, hint, password)
            ...

        }
</code>```

In Java, you could solve this problem by creating 2 constructors with matching number of parameters but I wonder if we can do the same in Kotlin or if there is a different approach.

答:
You can try moving the id to the end, like so:

```<code>@Entity(tableName = "entry_table")
data class Entry(
    val username: String? = null,
    val hint: String? = null,
    val password: String? = null,
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null)
</code>```

And then creating it like:

```<code>val entry = Entry(username, hint, password, id)
</code>```

Or, if you want to keep the id as the first parameter, you can use named arguments like this:

```<code>val entry = Entry(username = username, hint = hint, password = password)
</code>```

Hope that helps!

Body:
I am calling my entity class in an if/else-if statement for 2 different conditions and the values I pass into the parameters depend on the condition.  In the if block, I am passing 3 parameters and in the else-if block, I am passing 4.  The entity's object is throwing an error because it is expecting 4 parameters.  I want the first parameter to be optional and I'd like to know if there is a way to do that in Kotlin.

This is my entity class:

@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null,

    val username: String? = null,
    val hint: String? = null,
    val password: String? = null)

And this is the if/else-if block where I'm inserting values into the entity object:

if (requestCode == ADD_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(username, hint, password)
            ...

        } else if (requestCode == EDIT_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(id, username, hint, password)
            ...

        }

In Java, you could solve this problem by creating 2 constructors with matching number of parameters but I wonder if we can do the same in Kotlin or if there is a different approach.

Body:
You can try moving the id to the end, like so:

@Entity(tableName = "entry_table")
data class Entry(
    val username: String? = null,
    val hint: String? = null,
    val password: String? = null,
    @PrimaryKey(autoGenerate = true)
    var id: Int? = null)

And then creating it like:

val entry = Entry(username, hint, password, id)

Or, if you want to keep the id as the first parameter, you can use named arguments like this:

val entry = Entry(username = username, hint = hint, password = password)

Hope that helps!


问:
How can I paste data from one spreadsheet to the last column of another?
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

EDIT: Error occurs on this line:

```<code>Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues
</code>```

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

```<code>Dest.Cells(1, colDest) = "Test"
</code>```

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

答:
```<code>  Set Dest = Workbooks("Master.xlsm").Worksheets(1)
  colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
  wb.Worksheets(1).Range("b3:u83").Copy
  Dest.Cells(1, colDest).PasteSpecial Paste:=xlPasteValues
</code>```

Correctly inputs the Data where I need it, the 'ToLeft' made a difference but 'Range' wouldn't allow me to paste where 'Cells' does

Body:
Im trying to copy data from a whole bunch of different workbooks into one master sheet, pasting just the values in the next blank column. It all seems to be functional but always fails when it attempts to paste into the master sheet. I've tried looking at similar problems elsewhere but i cant seem to get them to work with what I am trying to do.

I have grabbed the bulk of this code off somewhere else and modified to suit, as you may be able to tell from some of the left over comments

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim colDest As Long
Dim Dest As Worksheet

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(fileName:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Change First Worksheet's Background Fill Blue this is where the work occurs
      Set Dest = Workbooks("Master.xlsm").Worksheets(1)
      colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToRight).Column
      wb.Worksheets(1).Range("b3:u83").Copy
      Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

EDIT: Error occurs on this line:

Dest.Range(1, colDest).PasteSpecial Paste:=xlPasteValues

Run-time error '1004':
Method 'Range' of object '_Worksheet' failed.

EDIT2: Changing the attempt to Paste with an attempt to write a value to the cell ie:

Dest.Cells(1, colDest) = "Test"

Correctly types "Test" into the next available column on the master sheet for every workbook that was opened from the directory.
Apparently changing 'Range' to 'Cells' works, which i thought i tried yesterday but was throwing a different error complaining i wasn't selecting the correct size cell

Body:
  Set Dest = Workbooks("Master.xlsm").Worksheets(1)
  colDest = Dest.Cells(1, Dest.Columns.Count).End(xlToLeft).Column + 1
  wb.Worksheets(1).Range("b3:u83").Copy
  Dest.Cells(1, colDest).PasteSpecial Paste:=xlPasteValues

Correctly inputs the Data where I need it, the 'ToLeft' made a difference but 'Range' wouldn't allow me to paste where 'Cells' does


问:
UPDATE to remove duplicates from comma-separated list
In my Postgres db, I have a table with some columns where one column B has values as follows:

```<code>A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5
</code>```

My expected output should be like this:

```<code>A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5
</code>```

Is there a simple UPDATE in Postgres to do this?

答:
There are two ways you could achieve this:

An UPDATE statement that unnests the elements and aggregates them back while removing duplicates:

```<code>update bad_design
  set b = t.b
from (
  select a, string_agg(distinct trim(t.w), ',') b
  from bad_design
    cross join unnest(string_to_array(b, ',')) as t(w)
  group by a
) t
where t.a = bad_design.a;
</code>```

The other option if you need to do that very often, is to create a function that removes duplicates and use that in an UPDATE:

```<code>create or replace function cleanup(p_list text)
  returns text
as
$$
  select string_agg(distinct trim(t.w), ',')
  from unnest(string_to_array(p_list, ',')) as t(w);
$$
language SQL;
</code>```

Then you can use that like this:

```<code>update bad_design
  set b = cleanup(b);
</code>```

The reason why this is so complicated is the fact that you did not properly normalize your data model. With a properly normalized model, you could simply create a UNIQUE index and prevent duplicates from being inserted in the first place.

Body:
In my Postgres db, I have a table with some columns where one column B has values as follows:

A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5

My expected output should be like this:

A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5

Is there a simple UPDATE in Postgres to do this?

Body:
There are two ways you could achieve this:

An UPDATE statement that unnests the elements and aggregates them back while removing duplicates:

update bad_design
  set b = t.b
from (
  select a, string_agg(distinct trim(t.w), ',') b
  from bad_design
    cross join unnest(string_to_array(b, ',')) as t(w)
  group by a
) t
where t.a = bad_design.a;

The other option if you need to do that very often, is to create a function that removes duplicates and use that in an UPDATE:

create or replace function cleanup(p_list text)
  returns text
as
$$
  select string_agg(distinct trim(t.w), ',')
  from unnest(string_to_array(p_list, ',')) as t(w);
$$
language SQL;

Then you can use that like this:

update bad_design
  set b = cleanup(b);

The reason why this is so complicated is the fact that you did not properly normalize your data model. With a properly normalized model, you could simply create a UNIQUE index and prevent duplicates from being inserted in the first place.


问:
Find all PHP Variables with preg_match
How can I find all PHP variables with preg_match. I made the following regular expression:

```<code>$string = 'Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable';
$instring = array();
preg_match_all('/\$(.*?)/', $string, $instring);
print_r($instring);
</code>```

I just don't understand how regular expressions work.

答:
Thanks for the answer by hakre. I combined it with a little bit more to also match PHP array variables and object oriented variables:

```<code>\$(([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(->)*)*(\[[^\]]*\])*)
</code>```

That should match the following variables:

```<code>$this->that
$this["sure"]["thing"][0]
$var
$_GET["id"]
</code>```

Title: Find all PHP Variables with preg_match

Body:
How can I find all PHP variables with preg_match. I made the following regular expression:

$string = 'Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable';
$instring = array();
preg_match_all('/\$(.*?)/', $string, $instring);
print_r($instring);

I just don't understand how regular expressions work.

Body:
Thanks for the answer by hakre. I combined it with a little bit more to also match PHP array variables and object oriented variables:

\$(([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(->)*)*(\[[^\]]*\])*)

That should match the following variables:

$this->that
$this["sure"]["thing"][0]
$var
$_GET["id"]


答:
I had some spare time, so I rewrote your program. It's much more efficient now. Read the comments to understand how it works

cols = [[] for x in range(6)]
# I opted to have a matrix of COLUMNS rather than rows because you can easily
# append items to the end of the list to simulate a real tile being placed there
# it's more intuitive and saves us time, as you'll see

def checkWin(cols):
    for i in range(6): # Each column
        for j in range(6): # Each row
            try: #check if the element at these coordinates exists yet
                cols[i][j]
            except IndexError:
                break
                # go back to next i - impossible that there's anything with a higher
                # j because if a list is n items long, and we go to j (which is one
                # higher than n and doesn't exist) then there can't be an element at
                # index j + someNumber.
            ret = False
            try: #vertical: j is the index in each column, so this goes up the column
                if cols[i][j] == cols[i][j+1] == cols[i][j+2] == cols[i][j+3] is not None:
                    ret = True
            except IndexError: #one of the elements of the comparison doesn't exist
                pass #We can't be sure that none of the other trials will return True
            try: #horizontal
                if cols[i][j] == cols[i+1][j] == cols[i+2][j] == cols[i+3][j] is not None:
                    ret = True
            except IndexError:
                pass
            try: #diagonal
                if cols[i][j] == cols[i+1][j+1] == cols[i+2][j+2] == cols[i+3][j+3] is not None:
                    ret = True
            except IndexError:
                pass
            try: #other diagonal
                if cols[i][j] == cols[i-1][j+1] == cols[i-2][j+2] == cols[i-3][j+3] is not None:
                    ret = True
            except IndexError:
                pass
            if ret:
                return cols[i][j]
    return None # We've gone through every single possible element and there are NO matches
def printBoard(cols):
    # Pretty intuitive function IMO - we swap i and j to go through rows.
    returnstr = '\n1 2 3 4 5 6\n'
    for i in range(6):
        for j in range(6):
            try:
                cols[j][5-i]
            except IndexError:
                returnstr += '_ '
                continue
            returnstr += cols[j][5-i]+' '
        returnstr += '\n'
    print(returnstr)
playerX = input('Player X, input your name: ')
playerO = input('Player O, input your name: ')
if playerX == playerO:
    print("Cannot have the same name!")
    exit()
count = 0
while not checkWin(cols):
    printBoard(cols)
    i = input('{}, input your column (1-6): '.format(playerO if count else playerX))
    try:
        target = cols[int(i)-1]
        if len(target) == 6:
            print("Column {} is already full! Please pick another.".format(i))
            continue
        target.append('O' if count else 'X')
    except ValueError:
        print("'{}' is not a number! Try again.".format(i))
        continue
    except IndexError:
        print("{} is not a valid column number! Please pick another.".format(i))
        continue
    count = (count+1) % 2
printBoard(cols)
if checkWin(cols) == 'X':
    print('{} (Player X), you win!'.format(playerX))
else:
    print('{} (Player O), you win!'.format(playerO))
```

Title: Easier way to check for four in row/column/diagonal in connect four game?


问:
How to use a dynamic property from an object from store as a v-model?
I've been wrapping my head around this one and I can't quite figure out the way to do this.

How can I have input data-binding to a store object property?
Meaning: my component only knows the store object, but it does not know in advance which properties the object contains.

Take this example:

Vue.component('os-choice', {
  template: `

Select OS

          <input type="checkbox" value="linux" v-model="linux">
            Linux

          <input type="checkbox" value="macos" v-model="macos">
            MacOS

          <input type="checkbox" value="windows" v-model="windows">
            Windows

  `,
  computed: {
    linux: {
      get() {
        return store.state.linux;
      },
      set(val) {
        store.commit('updateLinux', {
          linux: val
        });
      }
    },
    macos: {
      get() {
        return store.state.macos;
      },
      set(val) {
        store.commit('updateMacos', {
          macos: val
        });
      }
    },
    windows: {
      get() {
        return store.state.windows;
      },
      set(val) {
        store.commit('updateWindows', {
          windows: val
        });
      }
    },
  }
});

Vue.component('os-choice2', {
  template: `

Select OS

            <input type="checkbox" value="index" v-model="value">
              {{index}}

  `,
  computed: {
    os: {
      get(){ return store.state.os; },
      set(event){
        var name = event.target.value;
        var value = event.target.checked;
        store.commit('updateOs', {name: name, value: value});
      }
    },
  }
});

 const store = new Vuex.Store({
  state: {
    // initial state
    linux: true,
    macos: true,
    windows: false,
    os: {
      linux: true,
      macos: true,
      windows: false,
    }
  },
  mutations: {
    updateLinux(state, payload) {
      console.log('STORE: updated linux');
      state.linux = payload.linux;
    },
    updateMacos(state, payload) {
      console.log('STORE: updated MacOS');
      state.macos = payload.macos;
    },
    updateWindows(state, payload) {
      console.log('STORE: updated Windows');
      state.windows = payload.windows;
    },
    updateOs(state, payload) {
      console.log('STORE: updated OS');
      state.os[payload.name] = payload.value;
    }
  }
});

var app = new Vue({
  el: "#app",

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.row{
  width: 100%;
}
.column{
  width: 50%;
}</code>```

      <os-choice></os-choice>

      <os-choice2></os-choice2>

```

The first component works great.
The second component does not update the store: it generates error "[vuex] Do not mutate vuex store state outside mutation handlers."

I believe I understand why it is happening: Since the computed property of the component points to the object (and not the property being changed), v-model will try to change the deep property, thus forcing a change on the store which will throw an error before the component even calls the set() method on the object, right?

So what I would like to know is how would be the proper way to go about this?

My real-world scenario is that I'm building a dynamic filter with checkboxes and at runtime I do not know how many options it will have. This means I'll loop through my options to create the checkboxes, but then the data-binding would have to be in the form of "values[]". And this is where my headaches start.

Thank you all in advance

答:
From VueJs documentation:

Custom events can also be used to create custom inputs that work with
  v-model. Remember that:

```<code> <input v-model="searchText">
</code>```

does the same thing as:

```<code> <input   v-bind:value="searchText"   v-on:input="searchText =
 $event.target.value"
 >
</code>```

When used on a component, v-model instead does this:

```<code> <custom-input   v-bind:value="searchText"   v-on:input="searchText =
 $event"
 ></custom-input>
</code>```

So, instead of using v-model, you could use value as the v-bind:value="value" and map the event to update the store appropriately, something like: v-on:input="store.commit('store.commit('updateOs', event.target.value)"

The other component works since you are following exactly what Vuex recommend doing: https://vuex.vuejs.org/guide/forms.html

But on the v-for, you are using the store model directly.

Body:
I've been wrapping my head around this one and I can't quite figure out the way to do this.

How can I have input data-binding to a store object property?
Meaning: my component only knows the store object, but it does not know in advance which properties the object contains.

Take this example:

Vue.component('os-choice', {
  template: `

Select OS

          <input type="checkbox" value="linux" v-model="linux">
            Linux

          <input type="checkbox" value="macos" v-model="macos">
            MacOS

          <input type="checkbox" value="windows" v-model="windows">
            Windows

  `,
  computed: {
    linux: {
      get() {
        return store.state.linux;
      },
      set(val) {
        store.commit('updateLinux', {
          linux: val
        });
      }
    },
    macos: {
      get() {
        return store.state.macos;
      },
      set(val) {
        store.commit('updateMacos', {
          macos: val
        });
      }
    },
    windows: {
      get() {
        return store.state.windows;
      },
      set(val) {
        store.commit('updateWindows', {
          windows: val
        });
      }
    },
  }
});

Vue.component('os-choice2', {
  template: `

Select OS

            <input type="checkbox" value="index" v-model="value">
              {{index}}

  `,
  computed: {
    os: {
      get(){ return store.state.os; },
      set(event){
        var name = event.target.value;
        var value = event.target.checked;
        store.commit('updateOs', {name: name, value: value});
      }
    },
  }
});

 const store = new Vuex.Store({
  state: {
    // initial state
    linux: true,
    macos: true,
    windows: false,
    os: {
      linux: true,
      macos: true,
      windows: false,
    }
  },
  mutations: {
    updateLinux(state, payload) {
      console.log('STORE: updated linux');
      state.linux = payload.linux;
    },
    updateMacos(state, payload) {
      console.log('STORE: updated MacOS');
      state.macos = payload.macos;
    },
    updateWindows(state, payload) {
      console.log('STORE: updated Windows');
      state.windows = payload.windows;
    },
    updateOs(state, payload) {
      console.log('STORE: updated OS');
      state.os[payload.name] = payload.value;
    }
  }
});

var app = new Vue({
  el: "#app",

})

.row{
  width: 100%;
}
.column{
  width: 50%;
}

      <os-choice></os-choice>

      <os-choice2></os-choice2>

The first component works great.
The second component does not update the store: it generates error "[vuex] Do not mutate vuex store state outside mutation handlers."

I believe I understand why it is happening: Since the computed property of the component points to the object (and not the property being changed), v-model will try to change the deep property, thus forcing a change on the store which will throw an error before the component even calls the set() method on the object, right?

So what I would like to know is how would be the proper way to go about this?

My real-world scenario is that I'm building a dynamic filter with checkboxes and at runtime I do not know how many options it will have. This means I'll loop through my options to create the checkboxes, but then the data-binding would have to be in the form of "values[]". And this is where my headaches start.

Thank you all in advance

Body:
From VueJs documentation:

Custom events can also be used to create custom inputs that work with
  v-model. Remember that:

 <input v-model="searchText">

does the same thing as:

 <input   v-bind:value="searchText"   v-on:input="searchText =
 $event.target.value"
 >

When used on a component, v-model instead does this:

 <custom-input   v-bind:value="searchText"   v-on:input="searchText =
 $event"
 ></custom-input>

So, instead of using v-model, you could use value as the v-bind:value="value" and map the event to update the store appropriately, something like: v-on:input="store.commit('store.commit('updateOs', event.target.value)"

The other component works since you are following exactly what Vuex recommend doing: https://vuex.vuejs.org/guide/forms.html

But on the v-for, you are using the store model directly.


答:
Make use of the JSON functions.

First query:

SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'nom' AS name
FROM my_table;
```

<p>Second query:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'genre' AS genre,
    count(*)
FROM my_table
GROUP BY 1;
</code>```

Title: How to display elements of a JSON array?

Body:
I've created a small table with json column and I want to display all the names in the table like this:

 id_test |                                                                              test
---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------
       1 | {"clients":{"nbr":"2","info":[{"nom":"med","genre":"male","age":"25"},{"nom":"aicha","genre":"female","age":"24"}]}}
       3 | {"clients":{"nbr":"3","info":[{"nom":"yns","genre":"male","age":"23"},{"nom":"oussama","genre":"male","age":"24"},{"nom":"sara","genre":"female","age":"27"}]}}
       2 | {"clients":{"nbr":"1","info":{"nom":"kenza","genre":"female","age":"26"}}}

Desired output:

  name
---------
 med
 aicha
 yns
 oussama
 sara
 kenza

Also i want to list the number of gender each genre

Desired output:

 genre  | count
--------+-------
 female |     3
 male   |     3

Body:
Make use of the JSON functions.

First query:

SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'nom' AS name
FROM my_table;

Second query:

SELECT
    json_array_elements(CASE
        WHEN json_typeof(test->'clients'->'info') = 'array' THEN test->'clients'->'info'
        ELSE json_build_array(test->'clients'->'info')
    END)->>'genre' AS genre,
    count(*)
FROM my_table
GROUP BY 1;


问:
Changing of HTML form element in python
i want to replace the html form action with another text using python not django

i tried this

```<code>import requests
import re
main_input = input()
get_input = requests.get(main_input).read()
get_inputtxt = get_input.text
re_pattern = re.search('^action.*"$', get_inputtxt)
open_file = open('hello.htm', 'w')
print(get_inputtxt, file=open_file)
if (re_pattern):
  re_pattern = re_pattern.replace(re_pattern, "action='hello.php'")
  open_file.close()

normal action = "www.me.html"
expected action = "hello.php"
</code>```

答:
Here is how you would do it using BeautifulSoup:

from bs4 import BeautifulSoup
HTML = """
<form id="some_id" action="www.me.html" method="post">
   <input name="nothing" value="">
</form>
"""
soup = BeautifulSoup(HTML, 'html.parser')
print(soup)
```

```<form action="www.me.html" id="some_id" method="post">
<input name="nothing" value=""/> </form>
```

<pre class="lang-py prettyprint-override"><code>for form in soup('form'):
    print(form)
    form['action'] = "hello.php"

print(soup)
</code>```

```<code><form action="hello.php" id="some_id" method="post">
<input name="nothing" value=""/> </form>
</code>```

You would just need to add the url request:

```<code>import requests
main_input = input()
HTML = requests.get(main_input).text
</code>```

Title: Changing of HTML form element in python

Body:
i want to replace the html form action with another text using python not django

i tried this

import requests
import re
main_input = input()
get_input = requests.get(main_input).read()
get_inputtxt = get_input.text
re_pattern = re.search('^action.*"$', get_inputtxt)
open_file = open('hello.htm', 'w')
print(get_inputtxt, file=open_file)
if (re_pattern):
  re_pattern = re_pattern.replace(re_pattern, "action='hello.php'")
  open_file.close()

normal action = "www.me.html"
expected action = "hello.php"

Body:
Here is how you would do it using BeautifulSoup:

from bs4 import BeautifulSoup
HTML = """
<form id="some_id" action="www.me.html" method="post">
   <input name="nothing" value="">
</form>
"""
soup = BeautifulSoup(HTML, 'html.parser')
print(soup)

<form action="www.me.html" id="some_id" method="post">
<input name="nothing" value=""/> </form>

for form in soup('form'):
    print(form)
    form['action'] = "hello.php"

print(soup)

<form action="hello.php" id="some_id" method="post">
<input name="nothing" value=""/> </form>

You would just need to add the url request:

import requests
main_input = input()
HTML = requests.get(main_input).text


问:
How can insert loop for check each value in array [mongoDB,Node.js]
I want to check my input with DB. If input == Data in collection then go to next page

I try success but it only check first value in array.

This code is create data to DB [Success]

```<code>app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});
    res.render('whatsub');
});
</code>```

This code is my problem to insert for loop

```<code>app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      console.log("Wrong email/password");
    }
    db.close();
  });
 });
 });
</code>```

Can I use a forEach to check all data in my collection?

答:
It is not good practice to select all records from Mongo and then compare with your userName and password.

your code is selecting the first one record in mongo as long as you call findOne so it doesn't even make any loops as it returns only one record (the first one in the db)

But instead, It is better to do something like the following, select from mongo where userName equals the passed userName then compare the password you sent in the request with the one stored in the DB.

```<code>//select from mongo collection where email equals the one being passed in req's body [make sure you spell names correctly]
dbo.collection("Register").findOne({email:  req.body.email} , function(err, result) {
  //make sure result is not null, compare Password stored in mongo with the one passed in req's body
  if (result && result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      console.log("Wrong email/password");
    }

});
</code>```

Body:
I want to check my input with DB. If input == Data in collection then go to next page

I try success but it only check first value in array.

This code is create data to DB [Success]

app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});
    res.render('whatsub');
});

This code is my problem to insert for loop

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      console.log("Wrong email/password");
    }
    db.close();
  });
 });
 });

Can I use a forEach to check all data in my collection?

Body:
It is not good practice to select all records from Mongo and then compare with your userName and password.

your code is selecting the first one record in mongo as long as you call findOne so it doesn't even make any loops as it returns only one record (the first one in the db)

But instead, It is better to do something like the following, select from mongo where userName equals the passed userName then compare the password you sent in the request with the one stored in the DB.

//select from mongo collection where email equals the one being passed in req's body [make sure you spell names correctly]
dbo.collection("Register").findOne({email:  req.body.email} , function(err, result) {
  //make sure result is not null, compare Password stored in mongo with the one passed in req's body
  if (result && result.Password == req.body.psw) {
      console.log("Correct go next page");
    }
    else{
      console.log("Wrong email/password");
    }

});


问:
Error when building Qt app in a recent Docker
I am building a Qt c++ app in a Docker on Travis.
I am trying to update the base Docker image from Cosmic to Disco.

I did these updates:
Travis dist: Trusty => Xenial
Docker image: Cosmic => Disco

Now I get this error when building:

clang: error: no such file or directory: 'src/native/moc_qgsnative.cpp'

This seems to be a known issue in Qt 5.10+ which requires statx calls:

From the Qt release notes:

Qt uses the statx(2) system call for obtaining file information on kernels 4.12 and later. Some older container systems install system call protection rules that do not include this system call. If you experience problems running Qt applications inside containers (such as the report of a file not existing when it does), ensure the statx(2) is allowed in the container configuration.

I found some information saying that this could be solved by using the privileged mode when doing docker run.
But in our case, th build is made within the Docker build (and not docker run).
From the Docker docs, it seems that building has full capabilities.

答:
This is indeed due to statx calls.

This has been fixed in 18.04 (host).

For 16.04, one can install a more recent libseccomp and it fixes the issue:

```<code>wget https://launchpad.net/ubuntu/+archive/primary/+files/libseccomp2_2.4.1-0ubuntu0.16.04.2_amd64.deb
sudo dpkg -i libseccomp2_2.4.1-0ubuntu0.16.04.2_amd64.deb
sudo apt-get install -f
</code>```

Body:
This is indeed due to statx calls.

This has been fixed in 18.04 (host).

For 16.04, one can install a more recent libseccomp and it fixes the issue:

wget https://launchpad.net/ubuntu/+archive/primary/+files/libseccomp2_2.4.1-0ubuntu0.16.04.2_amd64.deb
sudo dpkg -i libseccomp2_2.4.1-0ubuntu0.16.04.2_amd64.deb
sudo apt-get install -f


问:
Why Nginx sends requests to upstream servers sequentially
I use Nginx as Load Balancer with the following config:

```<code>http {
upstream backend {
    server 127.0.0.1:8010;
    server 127.0.0.1:8011;
}
server {
    listen 80;

    location / {
        proxy_pass http://backend;
    }
}
}
</code>```

So I have 2 local servers which are Flask apps:

```<code>#app1.py
from flask import Flask, jsonify, abort, request, make_response
import time

@app.route("/", methods=['GET'])
def root():
    time.sleep(5)
    return jsonify({"response": "Hello, world!"})

app.run(debug=False, port=8010) # for app2.py the only diff is port=8011
</code>```

When I do 4 calls simultaneously (in different tabs) localhost:80, then I need to wait for 20 seconds to see "Hello, world!" in all 4 tabs (instead of 10 as I expected, because it should be distributed to 2 servers, for each it should take 10 seconds, but instead it just processes it sequentially one-by-one). Can you explain why? And how could it be fixed?

答: I've played around with it a bit more and realized that this behavior is only reproducible, when I open several tabs in Chromium. For my other browser (Firefox) everything works as expected. Also, if I do curl requests, everything works as expected as well.

Body:
I use Nginx as Load Balancer with the following config:

http {
upstream backend {
    server 127.0.0.1:8010;
    server 127.0.0.1:8011;
}
server {
    listen 80;

    location / {
        proxy_pass http://backend;
    }
}
}

So I have 2 local servers which are Flask apps:

#app1.py
from flask import Flask, jsonify, abort, request, make_response
import time

@app.route("/", methods=['GET'])
def root():
    time.sleep(5)
    return jsonify({"response": "Hello, world!"})

app.run(debug=False, port=8010) # for app2.py the only diff is port=8011

When I do 4 calls simultaneously (in different tabs) localhost:80, then I need to wait for 20 seconds to see "Hello, world!" in all 4 tabs (instead of 10 as I expected, because it should be distributed to 2 servers, for each it should take 10 seconds, but instead it just processes it sequentially one-by-one). Can you explain why? And how could it be fixed?


问:
new migrations are generated but are not applied to Db
I have 2 migrations created and already applied to db, but my new migration (just inserts) is not being applied when release and up to the server.

I'm running the ExecuteSqlFilesWithinMigrationsFolder () from DbMigrationBase

https://i.imgur.com/Fu3LrQn.png

```<code>    public partial class testando123 :DbMigrationBase {
        public override void Up() {
            ExecuteSqlFilesWithinMigrationsFolder(@"201905282356499_testando123\up");
        }

        public override void Down() { }
    }
</code>```

答:
In packege manger console write this command
update-database</p>

Body:
I have 2 migrations created and already applied to db, but my new migration (just inserts) is not being applied when release and up to the server.

I'm running the ExecuteSqlFilesWithinMigrationsFolder () from DbMigrationBase

https://i.imgur.com/Fu3LrQn.png

    public partial class testando123 :DbMigrationBase {
        public override void Up() {
            ExecuteSqlFilesWithinMigrationsFolder(@"201905282356499_testando123\up");
        }

        public override void Down() { }
    }


问:
Comparing lists within lists and counting occurrences
If I have a list of lists a, I want a function f()

```<code>a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]
</code>```

that gives the output:

```<code>out = f(a)
out
>> {[1,2,3]:2,[0,5,6]:1,[0,5,4]:1]}
</code>```

The order matters too, I need it to be completely similar
I was going to use  Counter but it does not work with lists. Sets are also out of the question. Is there some sort of 'easier' method than doing the whole thing from scratch maybe using something like Counter?

答:
Since dictionary keys can't have mutable objects, you would need to convert them to a tuple (a immutable object), then do Counter:

```<code>from collections import Counter
a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]
print(Counter(map(tuple, a)))
</code>```

Which outputs:

```<code>Counter({(1, 2, 3): 2, (0, 5, 6): 1, (0, 5, 4): 1})
</code>```

Body:
If I have a list of lists a, I want a function f()

a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]

that gives the output:

out = f(a)
out
>> {[1,2,3]:2,[0,5,6]:1,[0,5,4]:1]}

The order matters too, I need it to be completely similar
I was going to use  Counter but it does not work with lists. Sets are also out of the question. Is there some sort of 'easier' method than doing the whole thing from scratch maybe using something like Counter?

Body:
Since dictionary keys can't have mutable objects, you would need to convert them to a tuple (a immutable object), then do Counter:

from collections import Counter
a = [[1,2,3],[1,2,3],[0,5,6],[0,5,4]]
print(Counter(map(tuple, a)))

Which outputs:

Counter({(1, 2, 3): 2, (0, 5, 6): 1, (0, 5, 4): 1})


问:
Draw Drop Shadow Outside UIView

Background

I have a UIView with the following properties:

alpha = 1

backgroundColor = white, with 0.35 opacity

rounded corners

drop shadow

Code

This is how I create the drop shadow: (UIView extension)

```<code>self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.darkGrayColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 5)
self.layer.shadowOpacity = 0.35
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).CGPath
</code>```

Results

This results in the following:

...while I do not want to see the shadow beneath the view like this:

Question

How can I draw the shadow outside the view only so it is not visible below it?

Thanks in advance!

答:
I usually solve this kind of situation using composition of views. Instead of setting the shadow in the target view, I create a ShadowView and I put it behind the target view, with the same frame.

Doing so, we can mask the shadow view in order to only draw the shadow outside its frame.

The code for the shadow's mask is (full code above):

```<code>      let maskLayer = CAShapeLayer()
      let path = CGMutablePath()
      path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets.zero), cornerRadius: CGFloat(cornerRadius)).cgPath)
      path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets(top: -offset.height - radius*2, left: -offset.width - radius*2, bottom: -offset.height - radius*2, right: -offset.width - radius*2)), cornerRadius: CGFloat(cornerRadius)).cgPath)
      maskLayer.backgroundColor = UIColor.black.cgColor
      maskLayer.path = path;
      maskLayer.fillRule = .evenOdd
      self.layer.mask = maskLayer
</code>```

The result is the following:

Full playground available here:
https://gist.github.com/llinardos/d1ede3b491efc8edac940c5ea8631c6f

This kind of effect looks really nice with blurred backgrounds.

Title: Draw Drop Shadow Outside UIView

Body:
Background

I have a UIView with the following properties:

alpha = 1

backgroundColor = white, with 0.35 opacity

rounded corners

drop shadow

Code

This is how I create the drop shadow: (UIView extension)

self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.darkGrayColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 5)
self.layer.shadowOpacity = 0.35
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).CGPath

Results

This results in the following:

...while I do not want to see the shadow beneath the view like this:

Question

How can I draw the shadow outside the view only so it is not visible below it?

Thanks in advance!

Body:
I usually solve this kind of situation using composition of views. Instead of setting the shadow in the target view, I create a ShadowView and I put it behind the target view, with the same frame.

Doing so, we can mask the shadow view in order to only draw the shadow outside its frame.

The code for the shadow's mask is (full code above):

      let maskLayer = CAShapeLayer()
      let path = CGMutablePath()
      path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets.zero), cornerRadius: CGFloat(cornerRadius)).cgPath)
      path.addPath(UIBezierPath(roundedRect: bounds.inset(by: UIEdgeInsets(top: -offset.height - radius*2, left: -offset.width - radius*2, bottom: -offset.height - radius*2, right: -offset.width - radius*2)), cornerRadius: CGFloat(cornerRadius)).cgPath)
      maskLayer.backgroundColor = UIColor.black.cgColor
      maskLayer.path = path;
      maskLayer.fillRule = .evenOdd
      self.layer.mask = maskLayer

The result is the following:

Full playground available here:
https://gist.github.com/llinardos/d1ede3b491efc8edac940c5ea8631c6f

This kind of effect looks really nice with blurred backgrounds.


问:
Does ag-grid supports column virtualization?
Its specially important in scenarios with lots of columns which most of them are not in viewable area.</p>

答:
Yes, as stated on the documentation,

By default the grid uses virtualisation; a technique whereby the grid
  draws columns and rows as the user scrolls.

However, if you wish to disable column virtualization, you may choose to set the suppressColumnVirtualisation input property as true. You may refer to the column/row properties over here.

There may be 2 scenarios when you may wish to disable column virtualization.

1) Auto-sizing of all columns. This will ensure that all columns, and not just the columns which are rendered on the screen, will be resized.

2) Support for a11y. This is to prevent any potential issues for keyboard navigation and screen readers.


问:
Parsing input to get specific values
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

```<code>my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}
</code>```

Maybe I should be using a different approach.  Could someone help me, please?

答:
In shell script:

```<code>#!/bin/bash

MAXVAL=$(cat /tmp/data | tr [ "\\n" | cut -d"|" -f1 | sort -n | tail -1)
cat /tmp/data | tr [] "\\n" | grep ^$MAXVAL
</code>```

The first line cuts your big mass of data into lines, extracts just the first field, sorts it and takes the max. The second line cuts the data into lines again and greps for that max val.

If you have a LOT of data, this could be slow, so you could put the "lined" data into a temp file or something.

Title: Parsing input to get specific values

Body:
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}

Maybe I should be using a different approach.  Could someone help me, please?

Body:
In shell script:

#!/bin/bash

MAXVAL=$(cat /tmp/data | tr [ "\\n" | cut -d"|" -f1 | sort -n | tail -1)
cat /tmp/data | tr [] "\\n" | grep ^$MAXVAL

The first line cuts your big mass of data into lines, extracts just the first field, sorts it and takes the max. The second line cuts the data into lines again and greps for that max val.

If you have a LOT of data, this could be slow, so you could put the "lined" data into a temp file or something.


问:
New Typescript 1.8.4 build error: " Build: Property 'result' does not exist on type 'EventTarget'. "
I am New to typescript. In my Durandal application I migrated to VS-2012 to VS-2015 means typescript 0.9 to typescript 1.8.4. After migrated I got so many build errors. I resolved all those except one. I am getting below build error on types of Events.

ERROR: " Build: Property 'result' does not exist on type 'EventTarget' "

And the code was exactly like this below:

```<code>var reader:any,
target:EventTarget;

reader= new FileReader();
reader.onload = function (imgsrc){
    var fileUrl = imgsrc.target.result;
}
</code>```

"Imgsrc" is taking type event.

It's working fine with typescript 0.9 but with 1.8.4 it's throwing error as 'result' does not exist on type 'EventTarget'.
Can any one help on this to resolve.

Note: "target:EventTarget" is getting from lib.d.ts

答:
The target object can be accessed as below to prevent error until fix:

```<code>reader= new FileReader();
reader.onload = function (imgsrc){
    var fileUrl = imgsrc.target["result"];
}
</code>```

Treating the target as a Javascript Object

Body:
I am New to typescript. In my Durandal application I migrated to VS-2012 to VS-2015 means typescript 0.9 to typescript 1.8.4. After migrated I got so many build errors. I resolved all those except one. I am getting below build error on types of Events.

ERROR: " Build: Property 'result' does not exist on type 'EventTarget' "

And the code was exactly like this below:

var reader:any,
target:EventTarget;

reader= new FileReader();
reader.onload = function (imgsrc){
    var fileUrl = imgsrc.target.result;
}

"Imgsrc" is taking type event.

It's working fine with typescript 0.9 but with 1.8.4 it's throwing error as 'result' does not exist on type 'EventTarget'.
Can any one help on this to resolve.

Note: "target:EventTarget" is getting from lib.d.ts

Body:
The target object can be accessed as below to prevent error until fix:

reader= new FileReader();
reader.onload = function (imgsrc){
    var fileUrl = imgsrc.target["result"];
}

Treating the target as a Javascript Object


问:
pandas - set value based on NOT being a particular index integer and column value
suppose I have a datafrate df1:

```<code>   Color Saturation Letter
0  red        90       B
7  green      90       B
2  blue       90       A
7  red        90       B
2  green      90       B
7  red        90       A
</code>```

and I want to set the value of Saturation equal to 1 only for rows where the index is not equal to 7 and Letter is equal to A

So that we get:

```<code>  Color Saturation Letter
    0  red        90       B
    7  green      90       B
    2  blue       1        A
    7  red        90       B
    2  green      90       B
    7  red        90       A
</code>```

How might one do this?
I've attempted
    df.loc[df['Letter']=='A' & df.index != 7, 'Saturation'] =1 and !df.iloc[7] but I cannot seem to pinpoint the 'non-indices' properly.

答:
Using .loc

```<code>df.loc[(df.Letter=='A')&~(df.index==7),'Saturation ']=1
</code>```

Body:
suppose I have a datafrate df1:

   Color Saturation Letter
0  red        90       B
7  green      90       B
2  blue       90       A
7  red        90       B
2  green      90       B
7  red        90       A

and I want to set the value of Saturation equal to 1 only for rows where the index is not equal to 7 and Letter is equal to A

So that we get:

  Color Saturation Letter
    0  red        90       B
    7  green      90       B
    2  blue       1        A
    7  red        90       B
    2  green      90       B
    7  red        90       A

How might one do this?
I've attempted
    df.loc[df['Letter']=='A' & df.index != 7, 'Saturation'] =1 and !df.iloc[7] but I cannot seem to pinpoint the 'non-indices' properly.

Body:
Using .loc

df.loc[(df.Letter=='A')&~(df.index==7),'Saturation ']=1


答:
just as soon as I post the question, I've determined the answer:</p>

```<code>df.loc[df['Letter']==A & ~df.index.isin([7]), "Saturation"] =1
</code>```

Title: pandas - set value based on NOT being a particular index integer and column value

Body:
just as soon as I post the question, I've determined the answer:

df.loc[df['Letter']==A & ~df.index.isin([7]), "Saturation"] =1


问:
how to change "ImageView" opacity in kotlin
I want to change the opacity of an image View.
I know how to change opacity in Java but how should I do in kotlin?</p>

答:
This should work:  </p>

```<code>val imageView = ImageView(context)
imageView.alpha = 0.75f
</code>```

Body:
This should work:

val imageView = ImageView(context)
imageView.alpha = 0.75f


问:
How to find and replace text in CKEditor using Javascript?
How could I find and replace text in CKEditor using Javascript?
Thanks for your suggestion!</p>

答:
try this

```<code>editor = CKEDITOR.instances.fck; //fck is just my instance name you will need to replace that with yours

var edata = editor.getData();

var replaced_text = edata.replace("idontwant", "iwant this instead"); // you could also use a regex in the replace

editor.setData(replaced_text);
</code>```

you may want to put that in a blur event or soemthing

Body:
try this

editor = CKEDITOR.instances.fck; //fck is just my instance name you will need to replace that with yours

var edata = editor.getData();

var replaced_text = edata.replace("idontwant", "iwant this instead"); // you could also use a regex in the replace

editor.setData(replaced_text);

you may want to put that in a blur event or soemthing


问:
How to fix React Native error "jest-haste-map: Haste module naming collision"?
When I installed react-native-popup-menu, I faced such error.

This is error code

Looking for JS files in

  E:\react-native\.............\

Loading dependency graph...(node:9460)
  UnhandledPromiseRejectionWarning: Error: jest-haste-map: Haste module
  naming collision:   Duplicate module name: react-native   Paths:
  E:\react-native\.............\node_modules\react-native-twitter-signin\node_modules\react-native\package.json
  collides with
  E:\react-native\.............\node_modules\react-native\package.json

This error is caused by hasteImpl returning the same name for
  different files.
      at setModule (E:\react-native\.............\node_modules\jest-haste-map\build\index.js:551:17)
      at workerReply (E:\react-native\.............\node_modules\jest-haste-map\build\index.js:613:9)
      at process._tickCallback (internal/process/next_tick.js:68:7) (node:9460) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 2) (node:9460) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code. (node:9460)
  UnhandledPromiseRejectionWarning: Error: jest-haste-map: Haste module
  naming collision:   Duplicate module name: react-native   Paths:
  E:\react-native\.............\node_modules\react-native-twitter-signin\node_modules\react-native\package.json
  collides with
  E:\react-native\.............\heybuddy\node_modules\react-native\package.json

This error is caused by hasteImpl returning the same name for
  different files.
      at setModule (E:\react-native\.............\node_modules\jest-haste-map\build\index.js:551:17)
      at workerReply (E:\react-native\.............\node_modules\jest-haste-map\build\index.js:613:9)
      at process._tickCallback (internal/process/next_tick.js:68:7) (node:9460) UnhandledPromiseRejectionWarning: Unhandled promise
  rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 3)

I tried to find the way to solve this error, but I can't find any solution.

答:
I solved it by adding a new file named "rn-cli.config.js" in the project root folder, with the following contents.</p>

```<code>const blacklist = require('metro-config/src/defaults/blacklist');
module.exports = {
    resolver: {
        blacklistRE: blacklist([
            /node_modules\/.*\/node_modules\/react-native\/.*/,
        ])
    },
};
</code>```

Body:
I solved it by adding a new file named "rn-cli.config.js" in the project root folder, with the following contents.

const blacklist = require('metro-config/src/defaults/blacklist');
module.exports = {
    resolver: {
        blacklistRE: blacklist([
            /node_modules\/.*\/node_modules\/react-native\/.*/,
        ])
    },
};