问:
How to apply Dynamic Programming in SPOJ Feynman?
I was solving this problem -> http://www.spoj.com/problems/SAMER08F/ (A very simple problem) ... Got AC at my first go... My solution was like this (pretty straight-forward) :

```<code>#include<iostream>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
    while(n!=0)
    {
    printf("%d",((n)*(n+1)*((2*n)+1))/6);
    printf("\n");
    scanf("%d",&n);
    }
    return 0;
}
</code>```

I was going through this list http://ahmed-aly.com/Category.jsp?ID=33 and I found Feynman listed as a DP problem... I am a beginer in DP and cannot figure out how can this problem consists of sub-problems. Any help or hint in finding the recurrence relations will be very helpful.

答:
Just use simple DP. If you observe the pattern you can notice that if You take 1 square it possible to make 64 square. if you take 2 size square it is possible to make (8-1) = 7*7 = 49 size square .
so you can follow -> (8*8) + (7*7) + ........+(1*1) </p>

```<code>int feyn[1000];
 long long Feynman(long long x)
 {
if(x==1)return 1 ;

feyn[x]= (x*x)+Feynman(x-1);

return feyn[x];

 }
</code>```

Body:
I was solving this problem -> http://www.spoj.com/problems/SAMER08F/ (A very simple problem) ... Got AC at my first go... My solution was like this (pretty straight-forward) :

#include<iostream>
using namespace std;
int main()
{
int n;
scanf("%d",&n);
    while(n!=0)
    {
    printf("%d",((n)*(n+1)*((2*n)+1))/6);
    printf("\n");
    scanf("%d",&n);
    }
    return 0;
}

I was going through this list http://ahmed-aly.com/Category.jsp?ID=33 and I found Feynman listed as a DP problem... I am a beginer in DP and cannot figure out how can this problem consists of sub-problems. Any help or hint in finding the recurrence relations will be very helpful.

Body:
Just use simple DP. If you observe the pattern you can notice that if You take 1 square it possible to make 64 square. if you take 2 size square it is possible to make (8-1) = 7*7 = 49 size square .
so you can follow -> (8*8) + (7*7) + ........+(1*1)

int feyn[1000];
 long long Feynman(long long x)
 {
if(x==1)return 1 ;

feyn[x]= (x*x)+Feynman(x-1);

return feyn[x];

 }


来源: stackexchange

问:
Connection error when running docker commands
On running docker images, I am getting error

```<code>error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.40/images/json:
open //./pipe/docker_engine: The system cannot find the file specified.
In the default daemon configuration on Windows, the docker client must be
run elevated to connect. This error may also indicate that the docker
daemon is not running.
</code>```

I am on Windows 10 Home and have tried to install/reinstall Docker but I keep getting the error. Things were working fine an hour back!

答:
Can you check if you have a VM running under docker-machine? You can run the below command:

```<code>docker-machine ls
</code>```

And if you haven't installed docker-machine, please install it.

Ref:- https://docs.docker.com/toolbox/toolbox_install_windows/

Note:- Make sure enabled the BIOS virtualization.

ContentLicense: CC BY-SA 4.0

Body:
On running docker images, I am getting error

error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.40/images/json:
open //./pipe/docker_engine: The system cannot find the file specified.
In the default daemon configuration on Windows, the docker client must be
run elevated to connect. This error may also indicate that the docker
daemon is not running.

I am on Windows 10 Home and have tried to install/reinstall Docker but I keep getting the error. Things were working fine an hour back!

Body:
Can you check if you have a VM running under docker-machine? You can run the below command:

docker-machine ls

And if you haven't installed docker-machine, please install it.

Ref:- https://docs.docker.com/toolbox/toolbox_install_windows/

Note:- Make sure enabled the BIOS virtualization.


问:
Template Matching using PyOpenCl
I was moving ahead with more complicated aspects in image processing using opencl. Now what I tried was template matching and I am getting some results but not sure is it is correct. I think the template is matched anyway.. here are the scripts and images used by me...

python file:

```<code>import pyopencl as cl
import numpy as np
from PIL import Image
from time import time
import cv2

def getAssets(platform,device):
    plat = cl.get_platforms()[platform]
    dev = plat.get_devices()[device]
    ctx = cl.Context([dev])
    q = cl.CommandQueue(ctx)
    return ctx,q

def getKernel():
    string = "F:\Image processing\Template\matchTemplate.c"
    krnl = open(string).read()
    return krnl

def execution(image,template):

    cntx,queue = getAssets(0,0)

    img = np.asarray(image).astype(np.int32)
    temp = np.asarray(template).astype(np.int32)

    mf = cl.mem_flags

    inp = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=img)
    tmp = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=temp)
    out = cl.Buffer(cntx,mf.WRITE_ONLY,img.nbytes)

    task = cl.Program(cntx,getKernel()%(x,y)).build()

    val = task.matchTmp(queue,img.shape,None,inp,tmp,out)

    output = np.empty_like(img)

    cl.enqueue_copy(queue,output,out)

    output = output.astype(np.uint8)
    print(output,output.min(),output.max())
    return np.array(output)

def showResult(image,template):
    result = execution(image,template)
    result = Image.fromarray(result)
    result.show()

if __name__ == '__main__':
    image = cv2.imread("F:\Image processing\Template\cam.jpg",0)
    template = cv2.imread("F:\Image processing\Template\Template.jpg",0)
    global x,y
    x = image.shape[1]
    y = image.shape[0]
    # print(image.shape)
    # cv2.imshow("image",template)
    # cv2.waitKey(0)
    showResult(image,template)

</code>```

kernel file:

```<code>#pragma OPENCL EXTENSION cl_khr_fp64 : enable
__kernel void matchTmp(__global int *inp,__global int *tmp,__global int *out){
      int j = get_global_id(1);
      int i = get_global_id(0);
      int x = get_global_id(3);
      int y = get_global_id(2);
      int Iwidth = %d;
      int rown = %d;
      int w = 48;
      int r= 48;
      int value = 0,value1,value2,value3;

          value1 = value1 + half_powr((tmp[x*48 + y] - inp[(i+x)*Iwidth + (j+y)]),2);
          value2 = value2 + half_powr(tmp[x*48 + y],2);
          value3 = value3 + half_powr(inp[(i+x)*Iwidth + (j+y)],2);
          value = (value1/half_sqrt(value2*value3))*50;

          value = (value < 0   ? 0   : value);
          value = (value > 255 ? 255 : value);
          out[i*Iwidth + j] = value;

  }

</code>```

The image:
The image used

The template:
the template to be matched

The result:
this is the result

I used the method=CV_TM_SQDIFF_NORMED as shown at this site OpenCV doc. I am indeed getting high value near the object but, why is everything else black? The actual result should something like as shown here... Can anyone help me this please!

答:
I do not know pyopencl. But here is a demonstration of template matching in Python/OpenCV for your images showing the correspondence of the best match in the input image and in the correlation image resulting from matchTemplate().

The template is moved over the image one pixel shift at a time and the template is then compared pixel-by-pixel with the current location in the image and a metric score is computed and recorded in a new image. So the location in the output image corresponds to the upper left corner of the template as it moves across the input image.

Input:

Template:

```<code>import cv2
import numpy as np

# read image
img = cv2.imread('airplane.jpg')

# read template
tmplt = cv2.imread('airplane_tail.jpg')
hh, ww = tmplt.shape[:2]

# do template matching
# move template across image 1 pixe shift at a time and compute the correlation metric at each shift position as an image
corrimg = cv2.matchTemplate(img,tmplt,cv2.TM_CCOEFF_NORMED)

# get location of best match corresponding to the upper left corner of template from the brightest spot in corrimg
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(corrimg)
max_val_ncc = '{:.3f}'.format(max_val)
print("normalize_cross_correlation: " + max_val_ncc)
xx = max_loc[0]
yy = max_loc[1]
print('x_match_loc =',xx,'y_match_loc =',yy)

# draw template bounds in red onto img and corrimg scaled to 8-bit range
result1 = img.copy()
result2 = (255*corrimg).clip(0,255).astype(np.uint8)
result2 = cv2.merge([result2,result2,result2])
cv2.rectangle(result1, (xx, yy), (xx+ww, yy+hh), (0, 0, 255), 1)
cv2.rectangle(result2, (xx, yy), (xx+ww, yy+hh), (0, 0, 255), 1)

# save results
cv2.imwrite('airplane_template_match_location.jpg', result1)
cv2.imwrite('airplane_correlation_image_location.jpg', result2)

# show images
cv2.imshow('image', img)
cv2.imshow('template', tmplt)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Match location in input image:

Match location in correlation image:

Text output:

```<code>normalize_cross_correlation: 0.996
x_match_loc = 216 y_match_loc = 190
</code>```

Title: Template Matching using PyOpenCl

Body:
I was moving ahead with more complicated aspects in image processing using opencl. Now what I tried was template matching and I am getting some results but not sure is it is correct. I think the template is matched anyway.. here are the scripts and images used by me...

python file:

import pyopencl as cl
import numpy as np
from PIL import Image
from time import time
import cv2

def getAssets(platform,device):
    plat = cl.get_platforms()[platform]
    dev = plat.get_devices()[device]
    ctx = cl.Context([dev])
    q = cl.CommandQueue(ctx)
    return ctx,q

def getKernel():
    string = "F:\Image processing\Template\matchTemplate.c"
    krnl = open(string).read()
    return krnl

def execution(image,template):

    cntx,queue = getAssets(0,0)

    img = np.asarray(image).astype(np.int32)
    temp = np.asarray(template).astype(np.int32)

    mf = cl.mem_flags

    inp = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=img)
    tmp = cl.Buffer(cntx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=temp)
    out = cl.Buffer(cntx,mf.WRITE_ONLY,img.nbytes)

    task = cl.Program(cntx,getKernel()%(x,y)).build()

    val = task.matchTmp(queue,img.shape,None,inp,tmp,out)

    output = np.empty_like(img)

    cl.enqueue_copy(queue,output,out)

    output = output.astype(np.uint8)
    print(output,output.min(),output.max())
    return np.array(output)

def showResult(image,template):
    result = execution(image,template)
    result = Image.fromarray(result)
    result.show()

if __name__ == '__main__':
    image = cv2.imread("F:\Image processing\Template\cam.jpg",0)
    template = cv2.imread("F:\Image processing\Template\Template.jpg",0)
    global x,y
    x = image.shape[1]
    y = image.shape[0]
    # print(image.shape)
    # cv2.imshow("image",template)
    # cv2.waitKey(0)
    showResult(image,template)

kernel file:

#pragma OPENCL EXTENSION cl_khr_fp64 : enable
__kernel void matchTmp(__global int *inp,__global int *tmp,__global int *out){
      int j = get_global_id(1);
      int i = get_global_id(0);
      int x = get_global_id(3);
      int y = get_global_id(2);
      int Iwidth = %d;
      int rown = %d;
      int w = 48;
      int r= 48;
      int value = 0,value1,value2,value3;

          value1 = value1 + half_powr((tmp[x*48 + y] - inp[(i+x)*Iwidth + (j+y)]),2);
          value2 = value2 + half_powr(tmp[x*48 + y],2);
          value3 = value3 + half_powr(inp[(i+x)*Iwidth + (j+y)],2);
          value = (value1/half_sqrt(value2*value3))*50;

          value = (value < 0   ? 0   : value);
          value = (value > 255 ? 255 : value);
          out[i*Iwidth + j] = value;

  }

The image:
The image used

The template:
the template to be matched

The result:
this is the result

I used the method=CV_TM_SQDIFF_NORMED as shown at this site OpenCV doc. I am indeed getting high value near the object but, why is everything else black? The actual result should something like as shown here... Can anyone help me this please!

Body:
I do not know pyopencl. But here is a demonstration of template matching in Python/OpenCV for your images showing the correspondence of the best match in the input image and in the correlation image resulting from matchTemplate().

The template is moved over the image one pixel shift at a time and the template is then compared pixel-by-pixel with the current location in the image and a metric score is computed and recorded in a new image. So the location in the output image corresponds to the upper left corner of the template as it moves across the input image.

Input:

Template:

import cv2
import numpy as np

# read image
img = cv2.imread('airplane.jpg')

# read template
tmplt = cv2.imread('airplane_tail.jpg')
hh, ww = tmplt.shape[:2]

# do template matching
# move template across image 1 pixe shift at a time and compute the correlation metric at each shift position as an image
corrimg = cv2.matchTemplate(img,tmplt,cv2.TM_CCOEFF_NORMED)

# get location of best match corresponding to the upper left corner of template from the brightest spot in corrimg
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(corrimg)
max_val_ncc = '{:.3f}'.format(max_val)
print("normalize_cross_correlation: " + max_val_ncc)
xx = max_loc[0]
yy = max_loc[1]
print('x_match_loc =',xx,'y_match_loc =',yy)

# draw template bounds in red onto img and corrimg scaled to 8-bit range
result1 = img.copy()
result2 = (255*corrimg).clip(0,255).astype(np.uint8)
result2 = cv2.merge([result2,result2,result2])
cv2.rectangle(result1, (xx, yy), (xx+ww, yy+hh), (0, 0, 255), 1)
cv2.rectangle(result2, (xx, yy), (xx+ww, yy+hh), (0, 0, 255), 1)

# save results
cv2.imwrite('airplane_template_match_location.jpg', result1)
cv2.imwrite('airplane_correlation_image_location.jpg', result2)

# show images
cv2.imshow('image', img)
cv2.imshow('template', tmplt)
cv2.imshow('result1', result1)
cv2.imshow('result2', result2)
cv2.waitKey(0)
cv2.destroyAllWindows()

Match location in input image:

Match location in correlation image:

Text output:

normalize_cross_correlation: 0.996
x_match_loc = 216 y_match_loc = 190


问:
How to create an array for storing x and y coordinates in Python
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

```<code>#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)
</code>```

答:
Here, I defined a function that will take in the lengths of the polygon, starting at the line at the vertical line of length 17.5, and progressing clockwise:

```<code>def cord(lst):
    lst2 = [[0,0]] # First coordinate is at (0,0)
    d = 'up' # The lines go either up of right (down and left will be negative numbers)
    c = [0,0]
    for n in lst:
        if d == 'up': # if the direction is up, we add the value to the y cor
            c[1]+=n
            lst2.append(c.copy())
            d = 'right' # After up, we go right

        else: # if the direction is right, we add the value to the x cor
            c[0]+=n
            lst2.append(c.copy())
            d = 'up' # After right, we go up
    return lst2
</code>```

With the coordinates of each point, we can use this function I defined to find the area:

```<code>def polygon(lst2):
    area = 0
    for v in range(len(lst2)):
        if v+1 == len(lst2):
            i = 0
        else:
            i = v+1
        area += (lst2[v][0]*lst2[i][1]-lst2[v][1]*lst2[i][0])
    return abs(area/2)

c = cord([17.5,20.4,-25,7.6,-10,-56,17.5,28])

print(polygon(c))
</code>```

Output:

```<code>1280.0
</code>```

Body:
I am trying to read the description of a polygon from a file and compute the area of the polygon according to the description.

So far my approach:

#Function for computing area of a polygen
def polygonArea(A):
    n = len(A)  # of corners
    area = 0.0
    j = n - 1
    for i in range(n):
        area += (A[0][j] + A[0][i]) * (A[1][j] - A[1][i])
    area = abs(area) / 2.0

#reading from the file and connecting the polygen in a vector array in terms of X and Y coordinates
file = input('Enter file name:')
with open(file, 'r') as f:
    file = f.read()
    fileContent =file
    A = [[],[]] #trying to create an vector of x and y ordinates
    xa = 0.0
    yb = 0.0
    data = ""
    if fileContent > data and data == "(":
        data.join(fileContent)
        if data == "N":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file>temp:
                yb += temp
                A[1].append(yb) #Storing the value in y co ordinate of vector A
                A[0].append(xa) #Storing the value in x co ordinate of vector A
         if data == "W":
             data.join(fileContent)
             if data != ",":
                 print("Description is wrong!")
             if file > temp:
                 xa -= temp
                 A[1].append(yb)
                 A[0].append(xa)
        if data == "E":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa += temp
                A[1].append(yb)
                A[0].append(xa)
        if data == "S":
            data.join(fileContent)
            if data != ",":
                print("Description is wrong!")
            if file > temp:
                xa -= temp
                A[1].append(yb)
                A[0].append(xa)

#If polygon is complete A CONDITION on completeion of polygen in c++ if(x.back()==0 && y.back()==0)
p= polygonArea(A)
print ("area = ",p)

Body:
Here, I defined a function that will take in the lengths of the polygon, starting at the line at the vertical line of length 17.5, and progressing clockwise:

def cord(lst):
    lst2 = [[0,0]] # First coordinate is at (0,0)
    d = 'up' # The lines go either up of right (down and left will be negative numbers)
    c = [0,0]
    for n in lst:
        if d == 'up': # if the direction is up, we add the value to the y cor
            c[1]+=n
            lst2.append(c.copy())
            d = 'right' # After up, we go right

        else: # if the direction is right, we add the value to the x cor
            c[0]+=n
            lst2.append(c.copy())
            d = 'up' # After right, we go up
    return lst2

With the coordinates of each point, we can use this function I defined to find the area:

def polygon(lst2):
    area = 0
    for v in range(len(lst2)):
        if v+1 == len(lst2):
            i = 0
        else:
            i = v+1
        area += (lst2[v][0]*lst2[i][1]-lst2[v][1]*lst2[i][0])
    return abs(area/2)

c = cord([17.5,20.4,-25,7.6,-10,-56,17.5,28])

print(polygon(c))

Output:

1280.0


问:
Why should I use asserts?
I never got the idea of asserts -- why should you ever use them?

I mean, let's say I were a formula driver and all the asserts were things like security belt, helmet, etc.

The tests (in debug) were all okay, but now we want to do racing (release)!
Should we drop all security, because there were no issues while testing?

I will never ever remove them. I think most of the guys that claim that removing something comparable to asserts never profiled their code or the asserts were absolute displaced.
I've never seen any real performance advantage especially regarding the 80 / 20 rule.

So, am I missing the point somehow, or could anybody tell me, why I should use asserts?
By the way, I'm using unit tests.

答:
For other answers to this question

assert() macro is used to test the conditions or assumptions that
  should not occur in a program. For example, the array index should
  always be > 0. Another assumption can be 2+2 == 3+1.

So using assert () we can test such assumptions and as long as they
  evaluate to true, our program runs normally. When they are false, the
  program is terminated.

more here
https://www.softwaretestinghelp.com/assert-in-cpp/

OwnerDisplayName: jan

ContentLicense: CC BY-SA 3.0

Title: Why should I use asserts?


问:
Want to use redissql giving error node.js
while running this example https://github.com/JakSprats/node_Redisql/blob/master/examples/redisql_examples.js

gives me this error ,

```<code>~/rahul$ node redissql.js

node.js:178
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
ReferenceError: len is not defined
    at check_argc (/usr/local/lib/node/.npm/redisql/0.0.1/package/index.js:18:62)
    at RedisClient.<anonymous> (/usr/local/lib/node/.npm/redisql/0.0.1/package/index.js:102:9)
    at Object.<anonymous> (/home/reach121/rahul/redissql.js:4:8)
    at Module._compile (module.js:404:26)
    at Object..js (module.js:410:10)
    at Module.load (module.js:336:31)
    at Function._load (module.js:297:12)
    at Array.<anonymous> (module.js:423:10)
    at EventEmitter._tickCallback (node.js:170:26)
</code>```

I dont understand this point in this link https://github.com/JakSprats/node_Redisql
This test calls "FLUSHDB" on database 15 of redisql -> you will lose data in DB 15

what is to do with this and how we are going to do ?

答: I would say that you should rather use node_redis module for communicating with Redis DB, because it looks like it's more actively maintained, it has bigger user base and better documentation unlike Redisql.</p>

Body:
while running this example https://github.com/JakSprats/node_Redisql/blob/master/examples/redisql_examples.js

gives me this error ,

~/rahul$ node redissql.js

node.js:178
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
ReferenceError: len is not defined
    at check_argc (/usr/local/lib/node/.npm/redisql/0.0.1/package/index.js:18:62)
    at RedisClient.<anonymous> (/usr/local/lib/node/.npm/redisql/0.0.1/package/index.js:102:9)
    at Object.<anonymous> (/home/reach121/rahul/redissql.js:4:8)
    at Module._compile (module.js:404:26)
    at Object..js (module.js:410:10)
    at Module.load (module.js:336:31)
    at Function._load (module.js:297:12)
    at Array.<anonymous> (module.js:423:10)
    at EventEmitter._tickCallback (node.js:170:26)

I dont understand this point in this link https://github.com/JakSprats/node_Redisql
This test calls "FLUSHDB" on database 15 of redisql -> you will lose data in DB 15

what is to do with this and how we are going to do ?


问:
Convert csv file to json which has two colums in a row and has multiple lines
I have a csv file and in one row i have two columns with multiple values .I want to convert that as a list

Example:
 CSV data

```<code>Id     name      parentid
1       sam         12-george
                    24-jennifer
</code>```

Json Data

[{ id:1, name:sam, parentid:[{ id:12, name:george }, { id:24, name:jennifer }] } ]

答:
```<code>class Program
{
    const string CSV =
        @"Id     name      parentid
        1       sam         12-george
                            24-jennifer";

    static void Main(string[] args)
    {
        var csvArray = new JArray();

        // Split to lines
        string[] lines = CSV.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        // Ignore header line
        JArray currentParentArray = null;
        for (int i = 1; i < lines.Length; i++)
        {
            string[] items = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length == 3)
            {
                var line = new JObject();
                csvArray.Add(line);

                line["id"] = int.Parse(items[0]);
                line["name"] = items[1];

                currentParentArray = new JArray();
                line["parentid"] = currentParentArray;

                ParseParentId(items[2], currentParentArray);
            }

            if (items.Length == 1 && currentParentArray != null)
                ParseParentId(items[0], currentParentArray);
        }

        var ser = JsonSerializer.CreateDefault();

        string json = csvArray.ToString();
        Console.WriteLine(json);
        Console.ReadKey();
    }

    static void ParseParentId(string parentId, JArray parentArray)
    {
        int idx = parentId.IndexOf("-");
        string id = parentId.Substring(0, idx);
        string name = parentId.Substring(1 + idx);

        var obj = new JObject();
        obj["id"] = int.Parse(id);
        obj["name"] = name;

        parentArray.Add(obj);
    }
}
</code>```

This C# source should work.  The array of parentid is remembered between lines and added to if the next line contains only another parentid.

Add a Nuget reference to Newtonsoft.Json to compile.

Body:
I have a csv file and in one row i have two columns with multiple values .I want to convert that as a list

Example:
 CSV data

Id     name      parentid
1       sam         12-george
                    24-jennifer

Json Data

[{ id:1, name:sam, parentid:[{ id:12, name:george }, { id:24, name:jennifer }] } ]

Body:
class Program
{
    const string CSV =
        @"Id     name      parentid
        1       sam         12-george
                            24-jennifer";

    static void Main(string[] args)
    {
        var csvArray = new JArray();

        // Split to lines
        string[] lines = CSV.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

        // Ignore header line
        JArray currentParentArray = null;
        for (int i = 1; i < lines.Length; i++)
        {
            string[] items = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length == 3)
            {
                var line = new JObject();
                csvArray.Add(line);

                line["id"] = int.Parse(items[0]);
                line["name"] = items[1];

                currentParentArray = new JArray();
                line["parentid"] = currentParentArray;

                ParseParentId(items[2], currentParentArray);
            }

            if (items.Length == 1 && currentParentArray != null)
                ParseParentId(items[0], currentParentArray);
        }

        var ser = JsonSerializer.CreateDefault();

        string json = csvArray.ToString();
        Console.WriteLine(json);
        Console.ReadKey();
    }

    static void ParseParentId(string parentId, JArray parentArray)
    {
        int idx = parentId.IndexOf("-");
        string id = parentId.Substring(0, idx);
        string name = parentId.Substring(1 + idx);

        var obj = new JObject();
        obj["id"] = int.Parse(id);
        obj["name"] = name;

        parentArray.Add(obj);
    }
}

This C# source should work.  The array of parentid is remembered between lines and added to if the next line contains only another parentid.

Add a Nuget reference to Newtonsoft.Json to compile.


问:
Convert string of integer ranges into a list
I would like to convert a string into an integer list using python. Some examples might be:

```<code>"1-4, 7, 9-11" into [1,2,3,4,7,9,10,11]
"5-9" into [5,6,7,8,9]
"1,2,3,10,11" into [1,2,3,10,11]
"1-3,5,6,7" into [1,2,3,5,6,7]
</code>```

Is there a quick and easy way to do this?

Body:
I would like to convert a string into an integer list using python. Some examples might be:

"1-4, 7, 9-11" into [1,2,3,4,7,9,10,11]
"5-9" into [5,6,7,8,9]
"1,2,3,10,11" into [1,2,3,10,11]
"1-3,5,6,7" into [1,2,3,5,6,7]

Is there a quick and easy way to do this?

Body:
You can use re module for the task.

For example:

import re

strings = ["1-4, 7, 9-11",
"5-9",
"1,2,3,10,11",
"1-3,5,6,7"]

for s in strings:
    out = []
    for a, b in re.findall(r'(\d+)-?(\d*)', s):
        out.extend(range(int(a), int(a)+1 if b=='' else int(b)+1))
    print('Input = {:<20} Output = {}'.format(s, out))

Prints:

Input = 1-4, 7, 9-11         Output = [1, 2, 3, 4, 7, 9, 10, 11]
Input = 5-9                  Output = [5, 6, 7, 8, 9]
Input = 1,2,3,10,11          Output = [1, 2, 3, 10, 11]
Input = 1-3,5,6,7            Output = [1, 2, 3, 5, 6, 7]


问:
What is the best place for uploading files when spilt frontend and backend?
hi i working to spilt backend (laravel) and frontend(nuxt.js)
and i want to know best place to upload dynamic images or files on the.

backend (laravel): public folder.

or

frontend (nuxtjs): asstes/images folder.

and i want when i finished my project upload it on same server with different port.

thank you

答:
If those are static files used in the frontend, then in the assets/images from nuxtjs.
If those are files uploaded to the server, then in the laravel backend.</p>


问:
Print HTML table with header row from array which has rows with missing columns
I have an array with following format:

```<code>Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)
</code>```

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

```<code> $row = 0;
$table  = '<table border="1" id="datatable">';
foreach($data as $value){
    $table .= '<tr>';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= '<td>'.$innerkey.'</td>';
        }
    }
    $table .= '</tr><tr>';
    foreach($value as $innerkey=>$innervalue){
        $table .= '<td>'.$innervalue.'</td>';
    }
    $table .= '</tr>';
    $row++;
}
$table .= '</table>';

 print_r($table);
</code>```

The output of the table should be as follows:

But is is showing like this

First problem is the header row is continue printing only upto avalable data in first data row. Secondly If any data cell is unavailable then it is filled by next cell data. but it is supposed to be remain bank cell.
Please help me to sort out the problem. Thanks in advance

答:
<?php declare(strict_types=1);

/**
 * Flatting the uniqueness of all headers, which might be different
 * from the different arrays
 */
function uniqueHeaders(array $allArrays): array
{
    return array_unique(
        call_user_func_array('array_merge', // flatting one level all keys
            array_map(function (array $a): array {
                return array_keys($a);
            }, $allArrays)
        )
    );
}

/**
 * Normalize that all arrays contain the same headers.
 * Filling with an empty string the headers that don't exists from
 * the others.
 */
function normalizeHeaders(array $allArrays): array
{
    $headers = uniqueHeaders($allArrays);
    foreach ($allArrays as &$array) {
        foreach ($headers as $header) {
            if (!isset($array[$header])) {
                $array[$header] = '';
            }
        }
    }
    array_map('ksort', $allArrays);

    return $allArrays;
}

/**
 * This function generates the table as HTML with all array
 * values as they come. No special "business logic" behind.
 */
function generateTable(array $allArrays): string
{
    $headers = uniqueHeaders($allArrays);
    $table = '
';
    $table .= '
';
    // first the headers
    foreach ($headers as $header) {
        $table .= '' . $header . '	';
    }
    $table .= '
';
    // then the values
    foreach ($allArrays as $value) {
        $table .= '
';
        foreach ($value as $innervalue) {
            $table .= '' . $innervalue . '	';
        }
        $table .= '
';
    }
    $table .= '
';

    return $table;
}

// Usage example using different headers from each array:
$allArrays = [
    [
        'header1' => 'value11',
        'header2' => 'value12',
        'header3' => 'value13',
        'header4' => 'value14',
        'header7' => 'value17',
    ],
    [
        'header1' => 'value21',
        'header2' => 'value22',
        'header5' => 'value25',
        'header6' => 'value26',
    ],
];

$normalized = normalizeHeaders($allArrays);
$table = generateTable($normalized);
print $table . PHP_EOL;

// Unit test:
$result = <<<HTML

        header1	header2	header3	header4	header5	header6	header7

        value11	value12	value13	value14			value17

        value21	value22			value25	value26

HTML;
// Result removing all spaces per line and unifying everything in one line (as the generateTable())
$expected = implode('', array_map('trim', explode(PHP_EOL, $result)));
assert($expected === $table);

```

Body:
I have an array with following format:

Array
(
    [0] => Array
        (
            [Push to Web] => Yes
            [attribute_set] => laminate_flooring
            [category] => Accessories/Underlay
            [name] => Under Pad Feather Light Foam
            [sku] => 123-1028
            [description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
            [image] => 123-1028.jpg
            [gallery_Image] => 9095307460638-424-424.jpg
            [price] => 0.24
            [qty_ca] => 16
            [weight] => 3
            [meta_description] => 51-1001
            [meta_title] => Under Pad Feather Light Foam
            [status] => 1
            [flooring_coverage] => 200
            [is_flooring_product] => 1
            [web_price_comparative] => 0.31
        )

    [1] => Array
        (
            [Push to Web] => Yes
            [category] => Accessories
            [name] => Vent Maple Flush 4x10
            [sku] => 089-1000
            [description] => Vent Flush Mount Maple 4 x 10
            [short_description] => Vent Flush Mount Maple 4 x 10
            [image] => 089-1000.jpg
            [price] => 17.05
            [qty_ca] => 63
            [qty_us] => 41
            [meta_description] => 10-1023
            [meta_title] => Vent Maple Flush 4x10
            [status] => 1
            [flooring_coverage] => 1
            [min_order_qty] => 400
            [web_price_comparative] => 22.16
        )
)

I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.

I wrote the following but its not working.

 $row = 0;
$table  = '
';
foreach($data as $value){
    $table .= '
';
    if ($row == 0) {
        foreach($value as $innerkey=>$innervalue){
            $table .= ''.$innerkey.'	';
        }
    }
    $table .= '

';
    foreach($value as $innerkey=>$innervalue){
        $table .= ''.$innervalue.'	';
    }
    $table .= '
';
    $row++;
}
$table .= '
';

 print_r($table);

The output of the table should be as follows:

But is is showing like this

First problem is the header row is continue printing only upto avalable data in first data row. Secondly If any data cell is unavailable then it is filled by next cell data. but it is supposed to be remain bank cell.
Please help me to sort out the problem. Thanks in advance

Body:
<?php declare(strict_types=1);

/**
 * Flatting the uniqueness of all headers, which might be different
 * from the different arrays
 */
function uniqueHeaders(array $allArrays): array
{
    return array_unique(
        call_user_func_array('array_merge', // flatting one level all keys
            array_map(function (array $a): array {
                return array_keys($a);
            }, $allArrays)
        )
    );
}

/**
 * Normalize that all arrays contain the same headers.
 * Filling with an empty string the headers that don't exists from
 * the others.
 */
function normalizeHeaders(array $allArrays): array
{
    $headers = uniqueHeaders($allArrays);
    foreach ($allArrays as &$array) {
        foreach ($headers as $header) {
            if (!isset($array[$header])) {
                $array[$header] = '';
            }
        }
    }
    array_map('ksort', $allArrays);

    return $allArrays;
}

/**
 * This function generates the table as HTML with all array
 * values as they come. No special "business logic" behind.
 */
function generateTable(array $allArrays): string
{
    $headers = uniqueHeaders($allArrays);
    $table = '<table border="1" id="datatable">';
    $table .= '<tr>';
    // first the headers
    foreach ($headers as $header) {
        $table .= '<th>' . $header . '</th>';
    }
    $table .= '</tr>';
    // then the values
    foreach ($allArrays as $value) {
        $table .= '<tr>';
        foreach ($value as $innervalue) {
            $table .= '<td>' . $innervalue . '</td>';
        }
        $table .= '</tr>';
    }
    $table .= '</table>';

    return $table;
}

// Usage example using different headers from each array:
$allArrays = [
    [
        'header1' => 'value11',
        'header2' => 'value12',
        'header3' => 'value13',
        'header4' => 'value14',
        'header7' => 'value17',
    ],
    [
        'header1' => 'value21',
        'header2' => 'value22',
        'header5' => 'value25',
        'header6' => 'value26',
    ],
];

$normalized = normalizeHeaders($allArrays);
$table = generateTable($normalized);
print $table . PHP_EOL;

// Unit test:
$result = <<<HTML
<table border="1" id="datatable">
    <tr>
        <th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th>header7</th>
    </tr>
    <tr>
        <td>value11</td><td>value12</td><td>value13</td><td>value14</td><td></td><td></td><td>value17</td>
    </tr>
    <tr>
        <td>value21</td><td>value22</td><td></td><td></td><td>value25</td><td>value26</td><td></td>
    </tr>
</table>
HTML;
// Result removing all spaces per line and unifying everything in one line (as the generateTable())
$expected = implode('', array_map('trim', explode(PHP_EOL, $result)));
assert($expected === $table);


问:
New Telegram bot return almost empty JSON to API
I want to create a Telegram bot, so I followed the instructions and got:

Done! Congratulations on your new bot. You will find it at
  t.me/RonGuruBot. You can now add a description, about section and
  profile picture for your bot, see /help for a list of commands. By the
  way, when you've finished creating your cool bot, ping our Bot Support
  if you want a better username for it. Just make sure the bot is fully
  operational before you do this.

Use this token to access the HTTP API:
  318659684:AAFdR9YE4DEwg1NQitSIuifPotoA-3f6cUw

However, when I enter the following URL into Chrome:

https://api.telegram.org/bot318659684:AAFdR9YE4DEwg1NQitSIuifPotoA-3f6cUw/getUpdates

The returned JSON is:

{"ok":true,"result":[]}

And the documentation led me to believe that there should be more in the JSON reply.

Should there be more?

What should I change to get a correct JSON reply?

答:
if you do not change the privacy settings,

the bot only receives messages beginning with / e.g. /start,

this can be painful research, especially in multi-user chats

a good strategy is to mention the bot in the group

(e.g. /start @mybot_bot )


问:
Instance member getUrl can't be accessed using static access
I'm trying to use a cloud function that I built on GCP as follows. The objective is to obtain a JSON containing timestamps, images and sources, which will be converted to a Map object. SourceController, datetime and _imageUrl are the outputs, the input is supposed to be the url function parameter:

```<code> parser(String url) async {
    var function_url = <CLOUD FUNCTION URL>;
    try {
      var request = await HttpClient.getUrl(Uri.parse(function_url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.ok) {
        var json = await response.transform(utf8.decoder).join();
        Map data = jsonDecode(json) as Map;
        sourceController = data['source'];
        publishedAt = data['datetime'];
        _imageUrl = data['image'];
      } else {
         print('Error running parser:\nHttp status ${response.statusCode}');
      }
    } catch (exception) {
      print('Failed invoking the parser function.');
    }
</code>```

I keep getting the following error, in spite of changing the data type of request to dynamic, var, etc.

```<code>Instance member 'getUrl' can't be accessed using static access
</code>```

I would really appreciate some help on why the getUrl does not work, although I've checked other codes where it works alright.

Also, I don't understand where do we pass our arguments to our cloud function if at all?

Also, if there is a solution involving the cloud_functions package, I'm fine with that too - I tried that method too but had not luck there either.

答:
According to here, you need to instantiate the HttpClient in order to access that method as it is not a static method:

```<code>HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
</code>```

Body:
I'm trying to use a cloud function that I built on GCP as follows. The objective is to obtain a JSON containing timestamps, images and sources, which will be converted to a Map object. SourceController, datetime and _imageUrl are the outputs, the input is supposed to be the url function parameter:

 parser(String url) async {
    var function_url = <CLOUD FUNCTION URL>;
    try {
      var request = await HttpClient.getUrl(Uri.parse(function_url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.ok) {
        var json = await response.transform(utf8.decoder).join();
        Map data = jsonDecode(json) as Map;
        sourceController = data['source'];
        publishedAt = data['datetime'];
        _imageUrl = data['image'];
      } else {
         print('Error running parser:\nHttp status ${response.statusCode}');
      }
    } catch (exception) {
      print('Failed invoking the parser function.');
    }

I keep getting the following error, in spite of changing the data type of request to dynamic, var, etc.

Instance member 'getUrl' can't be accessed using static access

I would really appreciate some help on why the getUrl does not work, although I've checked other codes where it works alright.

Also, I don't understand where do we pass our arguments to our cloud function if at all?

Also, if there is a solution involving the cloud_functions package, I'm fine with that too - I tried that method too but had not luck there either.

Body:
According to here, you need to instantiate the HttpClient in order to access that method as it is not a static method:

HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))


问:
Bootstrap close modal not working
I have two button here that are being used to close the modal. The first is the close icon and the other one is cancel button, both use data-dismiss to close the modal. However, both of them are not working. I am using the same code for another modal and there they are working fine. Any guesses? </p>

```<code><div id="timeSelectModal{{entry.position - 1}}" style="display: none" class="modal">
    <div class="modal-dialog">
        <div id="timeSelectModalContent" class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <label>
                <input id="checkbox8pm{{entry.position - 1}}" type="checkbox" value="first_checkbox">
                <label class="checkbox-label">Thursday, 08:00 pm.</label>
            </label>
            <br>
            <label>
                <input id="checkbox9pm{{entry.position - 1}}" type="checkbox" value="second_checkbox">
                <label class="checkbox-label">Thursday, 09:30 pm.</label>
            </label>
            <div id="time-modal-footer" class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="timeSaveButton{{entry.position - 1}}" v-on:click="setTime(entry.position - 1)">Save</button>
            </div>
        </div>
    </div>
</div>
</code>```

答:
In my case I was missing the data-target attribute on the link that calls the modal.

```<code><a href="#getResults"
   class="results-link"
   data-toggle="modal"
   data-target="#results-modal"
   data-providerName="${providerName}"
   data-individualID="${individualID}"
   data-reportID="@Model.ReportID">Results
</a>
</code>```

Title: Bootstrap close modal not working

Body:
I have two button here that are being used to close the modal. The first is the close icon and the other one is cancel button, both use data-dismiss to close the modal. However, both of them are not working. I am using the same code for another modal and there they are working fine. Any guesses?

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

                <input id="checkbox8pm{{entry.position - 1}}" type="checkbox" value="first_checkbox">
                Thursday, 08:00 pm.

                <input id="checkbox9pm{{entry.position - 1}}" type="checkbox" value="second_checkbox">
                Thursday, 09:30 pm.

                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="timeSaveButton{{entry.position - 1}}" v-on:click="setTime(entry.position - 1)">Save</button>

Body:
In my case I was missing the data-target attribute on the link that calls the modal.

<a href="#getResults"
   class="results-link"
   data-toggle="modal"
   data-target="#results-modal"
   data-providerName="${providerName}"
   data-individualID="${individualID}"
   data-reportID="@Model.ReportID">Results
</a>


问:
Increment hex string
I'm trying to increment an hex string like this:

```
#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;
```

Here's my procedure:

```<code>var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;
</code>```

Whith this procedure, only the second byte increment.
The result is:

```
#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1
```

Thanks

答:
I think I see what's really going on here:

I believe this is Delphi 2009.  Char is actually a UnicodeChar which is a TWO byte variable.

Increment the 4th byte and what are you really changing?  The low order byte of the second character--producing exactly the output shown.  Had you caused it to wrap past $FF you would have seen a very different result!

Sorry I can't provide more info, I haven't upgraded yet.

ContentLicense: CC BY-SA 2.5

Title: Increment hex string

Body:
I'm trying to increment an hex string like this:

#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;

Here's my procedure:

var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;

Whith this procedure, only the second byte increment.
The result is:

#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1

Thanks

LastEditorDisplayName: Tomalak

OwnerDisplayName: Loren Pechtel

LastEditorDisplayName: Rob Kennedy


问:
Passing parameters to a Bash function
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass parameters within my script. I tried:

```<code>myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}
</code>```

But the syntax is not correct. How can I pass a parameter to my function?

答:
Drop the parentheses and commas:

```<code> myBackupFunction ".." "..." "xx"
</code>```

And the function should look like this:

```<code>function myBackupFunction() {
    # Here $1 is the first parameter, $2 the second, etc.
}
</code>```

Title: Passing parameters to a Bash function

Body:
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass parameters within my script. I tried:

myBackupFunction("..", "...", "xx")

function myBackupFunction($directory, $options, $rootPassword) {
     ...
}

But the syntax is not correct. How can I pass a parameter to my function?

Body:
Drop the parentheses and commas:

 myBackupFunction ".." "..." "xx"

And the function should look like this:

function myBackupFunction() {
    # Here $1 is the first parameter, $2 the second, etc.
}


问:
Octave return sorted array of string with values altered
I'm trying to ordering by name a list of files, but when I used sort Octave function the returned array has values altered, see code bellow:

```<code>files = dir('*.ASC');
newFiles;

for i = 1:length(files(:,1))
    newFiles = [newFiles; files(i, 1).name];
endfor;
</code>```

newFiles =

```<code>ALA0.ASC
ALA15.ASC
ALA150.ASC
ALA30.ASC
ALA45.ASC
ALA60.ASC
ALA90.ASC
</code>```

sort(newFiles)

```<code>ans =

ALA0...A
ALA10.ACC
ALA10.ASC
ALA30.ASC
ALA45.ASC
ALA650ASC
ALA95ASSSC
</code>```

How can I get my column vector sorted with the originals values? or if is there other way to sorted the filenames gotten from dir function?

答:
Try using a cell:

```<code>files = dir('*.*');
newFiles={};

for i = 1:length(files(:,1))
    newFiles(i)=files(i, 1).name;
endfor;
</code>```

For what I see dir already produces a sorted list

```<code>octave:30> newFiles
newFiles =
{
  [1,1] = ALA01.asc
  [1,2] = ALA20.asc
  [1,3] = ALA33.asc
  [1,4] = ALA41.asc
}

octave:31> sort(newFiles)
ans =
{
  [1,1] = ALA01.asc
  [1,2] = ALA20.asc
  [1,3] = ALA33.asc
  [1,4] = ALA41.asc
}
</code>```

Body:
I'm trying to ordering by name a list of files, but when I used sort Octave function the returned array has values altered, see code bellow:

files = dir('*.ASC');
newFiles;

for i = 1:length(files(:,1))
    newFiles = [newFiles; files(i, 1).name];
endfor;

newFiles =

ALA0.ASC
ALA15.ASC
ALA150.ASC
ALA30.ASC
ALA45.ASC
ALA60.ASC
ALA90.ASC

sort(newFiles)

ans =

ALA0...A
ALA10.ACC
ALA10.ASC
ALA30.ASC
ALA45.ASC
ALA650ASC
ALA95ASSSC

How can I get my column vector sorted with the originals values? or if is there other way to sorted the filenames gotten from dir function?

Body:
Try using a cell:

files = dir('*.*');
newFiles={};

for i = 1:length(files(:,1))
    newFiles(i)=files(i, 1).name;
endfor;

For what I see dir already produces a sorted list

octave:30> newFiles
newFiles =
{
  [1,1] = ALA01.asc
  [1,2] = ALA20.asc
  [1,3] = ALA33.asc
  [1,4] = ALA41.asc
}

octave:31> sort(newFiles)
ans =
{
  [1,1] = ALA01.asc
  [1,2] = ALA20.asc
  [1,3] = ALA33.asc
  [1,4] = ALA41.asc
}


问:
Jenkinsfile: How to parameterise Credential Id as per branch name?
I am using credentials plugin in my Jenkinsfile like below-

```<code>stage("stage name"){
    steps{
        withCredentials([usernamePassword(credentialsId: 'credId', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}
</code>```

As per new requirement, I need to different credentials id as per branch name. That means if branch name is master, I should use credentialsId:'mastercred' and for other branches, I should use credentialsId:'othercred'. The code in "withCredentials" block will be the same for, the only change will be with credentialsId.

I don't want to duplicate code. Is there any way to parameterise this credentialsId?

答:
You can read the branch name variable, and set the a credentialId variable to use on withCredentials would the work. For example:

```<code>stage("stage name"){
    steps{

        if (env.BRANCH_NAME == "master"){
            credentialId = "mastercred"
        }else
            credentialId = "othercred"
        }

        withCredentials([usernamePassword(credentialsId: "${credentialId}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}

</code>```

Body:
I am using credentials plugin in my Jenkinsfile like below-

stage("stage name"){
    steps{
        withCredentials([usernamePassword(credentialsId: 'credId', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}

As per new requirement, I need to different credentials id as per branch name. That means if branch name is master, I should use credentialsId:'mastercred' and for other branches, I should use credentialsId:'othercred'. The code in "withCredentials" block will be the same for, the only change will be with credentialsId.

I don't want to duplicate code. Is there any way to parameterise this credentialsId?

Body:
You can read the branch name variable, and set the a credentialId variable to use on withCredentials would the work. For example:

stage("stage name"){
    steps{

        if (env.BRANCH_NAME == "master"){
            credentialId = "mastercred"
        }else
            credentialId = "othercred"
        }

        withCredentials([usernamePassword(credentialsId: "${credentialId}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
            sh'''
                statement 1
                statement 2
             '''
        }
    }
}


问:
The getter 'uid' was called on null.Flutter
My App flow is like that:

Wrapper->Authenticate->Login

But when I run the app it gives me red screen and this exception:

```<code>    The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [InheritedProvider<User>], state: _WrapperState#fd39b):
The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
</code>```

I used to run it before and it was working good but I do not why now it show this exception:

Here is main:

```<code>class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
        child: MaterialApp(
          title: 'Sayarty',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.green,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: Wrapper(),
        ),
    );
  }
}
</code>```

And here is the Wrapper class:

```<code>    class Wrapper extends StatefulWidget {
  @override
  _WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {
  int _currentTab = 1;

  final _page = [
    Search(),
    Home(),
    Account(),
  ];

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user.uid);

    if (user == null) {
      return Authenticate();
    } else {
      return
//        Home();
       }
}
</code>```

答:
probably because now you added  print(user.uid); before testing if user is == null

Put it inside the else:

```<code>//print(user.uid);

if (user == null) {
  return Authenticate();
} else {
  print(user.uid);
  return
    Home();
}
</code>```

Body:
My App flow is like that:

Wrapper->Authenticate->Login

But when I run the app it gives me red screen and this exception:

    The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [InheritedProvider<User>], state: _WrapperState#fd39b):
The getter 'uid' was called on null.
Receiver: null
Tried calling: uid

I used to run it before and it was working good but I do not why now it show this exception:

Here is main:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value(
      value: AuthService().user,
        child: MaterialApp(
          title: 'Sayarty',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.green,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: Wrapper(),
        ),
    );
  }
}

And here is the Wrapper class:

    class Wrapper extends StatefulWidget {
  @override
  _WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {
  int _currentTab = 1;

  final _page = [
    Search(),
    Home(),
    Account(),
  ];

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user.uid);

    if (user == null) {
      return Authenticate();
    } else {
      return
//        Home();
       }
}

Body:
probably because now you added  print(user.uid); before testing if user is == null

Put it inside the else:

//print(user.uid);

if (user == null) {
  return Authenticate();
} else {
  print(user.uid);
  return
    Home();
}


问:
Docker Wordpress not connecting with docker Mysql Compose
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

```<code>version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy
</code>```

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.

答:
I have isolated the issue. It was the first time I was playing the docker volumes. I forgot to clear out the volumes when I updated the database information. So I was connecting to the old database with the new information which was leading to the error (This is why your don't try to learn something new late into the night on little sleep). Once I removed the volumes recomposed the docker containers it works perfectly. </p>

<p>Thank you for every one who assisted me with this. </p>

Body:
I am trying to set up multiple WordPress sites being hosting on the same server using docker using nginx reverse proxy server. I have a network setup with the nginx proxy listening on port 80 called nginx-proxy. I confirmed they are all on the same docker network. However, I am still getting WordPress is unable to communicate with the database. I can confirm that the credentials are correct and that MySQL is running on the other docker container.

With my testing, the forwarding proxy is working if I update the virtual host and open it in the web browser it does open the error message on that page. I can ping both the containers from within their shell. I am not sure what I am doing wrong I am newer to dockers networking within version 3. I don't believe docker has differenced between platforms, but in case it does I am running it on Mac OS.

I know there are other posts similar to this using Link and version 2 however, I was not able to find a version 3 with information that fixed my issue.

version: "3.3"

    services:
       db_node_domain:
         image: mysql:5.7
         volumes:
           - db_data:/var/lib/mysql
         restart: always
         environment:
           MYSQL_ROOT_PASSWORD: PASSWORD
           MYSQL_DATABASE: wordpress
           MYSQL_USER: wordpress
           MYSQL_PASSWORD: PASSWORD
         container_name: wordpress_db

       wordpress:
         depends_on:
           - db_node_domain
         image: wordpress:latest
         expose:
           - 80
         restart: always
         environment:
           VIRTUAL_HOST: domain.com
           WORDPRESS_DB_HOST: db_node_domain:3306
           WORDPRESS_DB_USER: wordpress
           WORDPRESS_DB_PASSWORD: PASSWORD
         container_name: wordpress
    volumes:
        db_data: {}

    networks:
      default:
        external:
          name: nginx-proxy

Please let me know if any more information is required. Thank you for any assistance you might be able to provide.

Body:
I have isolated the issue. It was the first time I was playing the docker volumes. I forgot to clear out the volumes when I updated the database information. So I was connecting to the old database with the new information which was leading to the error (This is why your don't try to learn something new late into the night on little sleep). Once I removed the volumes recomposed the docker containers it works perfectly.

Thank you for every one who assisted me with this.


答:
This should do the trick! I used an example you gave, you may use it in a loop for example for the rest of the strings.
We split each part by commas. If the part has "-" in it, then it must be a range so we find the location of the "-" sign and take the number before it as the start and the num after it as the end of the range. Note that range(N) gives you all numbers until N-1 so we used plus 1. </p>

```<code>nums = "1-4, 7, 9-11"  # example list
nums_list = nums.split(",")  # seperate to parts

total_list = []

for part in nums_list:
    part = part.strip()
    if "-" in part:  # if it is a range of nums
        mid = part.find("-")
        for i in range(int(part[:mid]), int(part[mid+1:])+1): # append the range
            total_list.append(i)
    else:
        total_list.append(int(part))  # else append the num

print(total_list)
</code>```

Title: Convert string of integer ranges into a list

Body:
I would like to convert a string into an integer list using python. Some examples might be:

"1-4, 7, 9-11" into [1,2,3,4,7,9,10,11]
"5-9" into [5,6,7,8,9]
"1,2,3,10,11" into [1,2,3,10,11]
"1-3,5,6,7" into [1,2,3,5,6,7]

Is there a quick and easy way to do this?

Body:
This should do the trick! I used an example you gave, you may use it in a loop for example for the rest of the strings.
We split each part by commas. If the part has "-" in it, then it must be a range so we find the location of the "-" sign and take the number before it as the start and the num after it as the end of the range. Note that range(N) gives you all numbers until N-1 so we used plus 1.

nums = "1-4, 7, 9-11"  # example list
nums_list = nums.split(",")  # seperate to parts

total_list = []

for part in nums_list:
    part = part.strip()
    if "-" in part:  # if it is a range of nums
        mid = part.find("-")
        for i in range(int(part[:mid]), int(part[mid+1:])+1): # append the range
            total_list.append(i)
    else:
        total_list.append(int(part))  # else append the num

print(total_list)


问:
What happened to `cp -t`?
I was reading up some ways of copying files from a directory with the use of a wildcard operator but excluding one file, and I saw that cp -t came into play when used in conjunction with find. However, whenever I try to run cp -t, I get cp: illegal option -- t, which to me means that the flag supplied is not implemented. Is this something that was taken out in more recent versions of bash? For some additional information, I am on macOS Catalina.

答:
What happened to cp -t?

I am on macOS Catalina.

You were reading GNU version of cp from GNU coreutils that has -t option as an extension. And macOS has its own versions of standard utils and macOS cp doesn't have -t.

Is this something that was taken out in more recent versions of bash?

cp isn't a builtin command, it's not part of bash.

Title: What happened to `cp -t`?


问:
Bittrex REST API for Python, I want to create an order using API v3 https://api.bittrex.com/v3/orders
I need help to create orders using the bittrex version 3 REST API. I have the code below and I can't understand what is missing to work.
I can make other GET calls, but I cannot make this POST request.
I don't know how to deal with the passing of parameters.

Official documentation at https://bittrex.github.io/api/v3#tag-Orders.

```<code>def NewOrder(market, amount, price):
#print 'open sell v3', market
market = 'HEDG-BTC'#'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders?'
params = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

timestamp = str(int(time.time()*1000))
Content = ""
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
uri2 = buildURI(uri, params)
#uri2 = 'https://api.bittrex.com/v3/orders?direction=BUY&limit=0.00021&marketSymbol=HEDG-BTC&quantity=1.1&timeInForce=POST_ONLY_GOOD_TIL_CANCELLED&type=LIMIT&useAwards=True'
#print uri2
PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
#print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri2, data={}, headers=headers, timeout=11)
return json.loads(r.content)
</code>```

NewOrder('HEDG', 1.1, 0.00021)

And my error message:

```<code>{u'code': u'BAD_REQUEST', u'data': {u'invalidRequestParameter': u'direction'}, u'detail': u'Refer to the data field for specific field validation failures.'}
</code>```

答:
I made the following modifications to the code but started to give error in 'Content-Hash'

I'm assuming that some parameters are optional so they are commented.

```<code>def NewOrder(market, amount, price):
market = 'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders'

payload = {
    'marketSymbol': market,
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    #"ceiling": "number (double)",
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    #"clientOrderId": "string (uuid)",
    'useAwards': True
}
#ceiling (optional, must be included for ceiling orders and excluded for non-ceiling orders)
#clientOrderId (optional) client-provided identifier for advanced order tracking

timestamp = str(int(time.time()*1000))
Content = ''+json.dumps(payload, separators=(',',':'))
print Content
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
#uri2 = buildURI(uri, payload)#line not used
print uri
#PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
PreSign = timestamp + uri + Method + contentHash# + subaccountId
print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri, json=payload, headers=headers, timeout=11)
print(r.json())

return json.loads(r.content)
</code>```

NewOrder('HEDG', 1.5, 0.00021)

{u'code': u'INVALID_CONTENT_HASH'}

Body:
I need help to create orders using the bittrex version 3 REST API. I have the code below and I can't understand what is missing to work.
I can make other GET calls, but I cannot make this POST request.
I don't know how to deal with the passing of parameters.

Official documentation at https://bittrex.github.io/api/v3#tag-Orders.

def NewOrder(market, amount, price):
#print 'open sell v3', market
market = 'HEDG-BTC'#'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders?'
params = {
    'marketSymbol': 'BTC-HEDG',#'HEDG-BTC', #market
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    'useAwards': True
}

timestamp = str(int(time.time()*1000))
Content = ""
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
uri2 = buildURI(uri, params)
#uri2 = 'https://api.bittrex.com/v3/orders?direction=BUY&limit=0.00021&marketSymbol=HEDG-BTC&quantity=1.1&timeInForce=POST_ONLY_GOOD_TIL_CANCELLED&type=LIMIT&useAwards=True'
#print uri2
PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
#print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri2, data={}, headers=headers, timeout=11)
return json.loads(r.content)

NewOrder('HEDG', 1.1, 0.00021)

And my error message:

{u'code': u'BAD_REQUEST', u'data': {u'invalidRequestParameter': u'direction'}, u'detail': u'Refer to the data field for specific field validation failures.'}

Body:
I made the following modifications to the code but started to give error in 'Content-Hash'

I'm assuming that some parameters are optional so they are commented.

def NewOrder(market, amount, price):
market = 'BTC-'+market
uri = 'https://api.bittrex.com/v3/orders'

payload = {
    'marketSymbol': market,
    'direction': 'BUY',
    'type': 'LIMIT',
    'quantity': amount,
    #"ceiling": "number (double)",
    'limit': price,
    'timeInForce': 'POST_ONLY_GOOD_TIL_CANCELLED',
    #"clientOrderId": "string (uuid)",
    'useAwards': True
}
#ceiling (optional, must be included for ceiling orders and excluded for non-ceiling orders)
#clientOrderId (optional) client-provided identifier for advanced order tracking

timestamp = str(int(time.time()*1000))
Content = ''+json.dumps(payload, separators=(',',':'))
print Content
contentHash = hashlib.sha512(Content.encode()).hexdigest()

Method = 'POST'
#uri2 = buildURI(uri, payload)#line not used
print uri
#PreSign = timestamp + uri2 + Method + contentHash# + subaccountId
PreSign = timestamp + uri + Method + contentHash# + subaccountId
print PreSign
Signature = hmac.new(apisecret, PreSign.encode(), hashlib.sha512).hexdigest()

headers = {
      'Api-Key' : apikey,
      'Api-Timestamp' : timestamp,
      'Api-Content-Hash': contentHash,
      'Api-Signature' : Signature
}

r = requests.post(uri, json=payload, headers=headers, timeout=11)
print(r.json())

return json.loads(r.content)

NewOrder('HEDG', 1.5, 0.00021)

{u'code': u'INVALID_CONTENT_HASH'}


问:
AWS Config API returning 403: Forbidden Error
I am testing AWS Config APIs using postman and cannot figure out root cause of 403 forbidden error. The authorization is setup using AWS Signature (4) with the awsAccessKeyId and awsSecretAccessKey of the user who has following policies attached:

AWSConfigRoleForOrganizations, AWSConfigRole, AWSConfigUserAccess
and AWSConfigRulesExecutionRole

```<code>curl --location --request POST 'https://config.us-west-2.amazonaws.com/?Action=ListDiscoveredResources&AUTHPARAMS&Version=2010-05-08' \
--header 'X-Amz-Content-Sha256: {generatedHash}' \
--header 'X-Amz-Date: 20200531T194002Z' \
--header 'Authorization: AWS4-HMAC-SHA256 Credential={accessKeyId}/20200531/us-west-2/config/aws4_request, SignedHeaders=content-length;host;x-amz-content-sha256;x-amz-date, Signature={signature}' \
--header 'Content-Type: text/plain' \
--data-raw '{
    "resourceType": "AWS::EC2::Instance"
}
</code>```

I cannot find any example of URL parameter or HTTP header requirements for AWS Config API online. Has anyone been able to successfully authentication with AWS Config API if so, provide an example of Parameters or Request Header?

答:
I was able to successfully fix the 403 forbidden error. The Parameter and HTTP header blow work properly and return the response 200:

curl --location --request POST 'https://config.us-west-2.amazonaws.com/?Action=ListDiscoveredResources&AUTHPARAMS&Version=2010-05-08' \
--header 'Content-Type: application/x-amz-json-1.1' \
--header 'X-Amz-Target: StarlingDoveService.ListDiscoveredResources' \

(omitted rest of header for simplicity)

Having said that, I am still not sure about 'X-Amz-Target: StarlingDoveService.ListDiscoveredResources'. There is no mention of it in in AWS documentation for AWS Config API. Stumbled upon it from the AWS discuss forum by luck.

Body:
I am testing AWS Config APIs using postman and cannot figure out root cause of 403 forbidden error. The authorization is setup using AWS Signature (4) with the awsAccessKeyId and awsSecretAccessKey of the user who has following policies attached:

AWSConfigRoleForOrganizations, AWSConfigRole, AWSConfigUserAccess
and AWSConfigRulesExecutionRole

curl --location --request POST 'https://config.us-west-2.amazonaws.com/?Action=ListDiscoveredResources&AUTHPARAMS&Version=2010-05-08' \
--header 'X-Amz-Content-Sha256: {generatedHash}' \
--header 'X-Amz-Date: 20200531T194002Z' \
--header 'Authorization: AWS4-HMAC-SHA256 Credential={accessKeyId}/20200531/us-west-2/config/aws4_request, SignedHeaders=content-length;host;x-amz-content-sha256;x-amz-date, Signature={signature}' \
--header 'Content-Type: text/plain' \
--data-raw '{
    "resourceType": "AWS::EC2::Instance"
}

I cannot find any example of URL parameter or HTTP header requirements for AWS Config API online. Has anyone been able to successfully authentication with AWS Config API if so, provide an example of Parameters or Request Header?


问:
Angular material chip list with autocomplete show on add button click
I have an Angular material chip list with autocomplete but in the example it shows drop-down when you place cursor near the last added chip but I want to show an add button near to the lastly added chip and show autocomplete only after user has clicked on plus icon

Like this - https://angular-zqijrv.stackblitz.io
but here, when I remove all chips, there is a weird border/outline which I cant remove and input box should be shown only when add is clicked.

答:
I think what you can do is

you can try to show chips in read only text box and when

```<code> <input
      placeholder="New fruit..."
      #fruitInput
      [formControl]="fruitCtrl"
      [readonly]="readonl"   -- // add a readonly attribute
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      (matChipInputTokenEnd)="add($event)">
</code>```

as user select the chip

```<code>// html file event
    (optionSelected)="selectChip()" this event is fired when you select something from the dropdown.

  // ts file
    selectChip(){
    // your code
  this.readonl = true;
    }
</code>```

// user is not able to type anything

and from your add button you can make this readonl flag to false and set focus in input box so that user can type and see dropdown.

2nd approach
have a 2 variable one with master data variable and other is copy of master data in autocomplete data variable.

```<code> // ts file
    masterData = [x,y,z]
    autoComplete = [...this.master]

// html file event
    (optionSelected)="selectChip()" this event is fired when you select something from the dropdown.

  // ts file
    selectChip(){
    // your code
    this.autocomplete.length = 0; // make autocomplete length to 0 items and add a logic to move focus to some other element.
    }

    // when u click on add button
    addButton() {
    autoComplete = [...this.master]
    }
    // now the dropdown have items and will appear again.
</code>```

Body:
I think what you can do is

you can try to show chips in read only text box and when

 <input
      placeholder="New fruit..."
      #fruitInput
      [formControl]="fruitCtrl"
      [readonly]="readonl"   -- // add a readonly attribute
      [matAutocomplete]="auto"
      [matChipInputFor]="chipList"
      [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
      (matChipInputTokenEnd)="add($event)">

as user select the chip

// html file event
    (optionSelected)="selectChip()" this event is fired when you select something from the dropdown.

  // ts file
    selectChip(){
    // your code
  this.readonl = true;
    }

// user is not able to type anything

and from your add button you can make this readonl flag to false and set focus in input box so that user can type and see dropdown.

2nd approach
have a 2 variable one with master data variable and other is copy of master data in autocomplete data variable.

 // ts file
    masterData = [x,y,z]
    autoComplete = [...this.master]

// html file event
    (optionSelected)="selectChip()" this event is fired when you select something from the dropdown.

  // ts file
    selectChip(){
    // your code
    this.autocomplete.length = 0; // make autocomplete length to 0 items and add a logic to move focus to some other element.
    }

    // when u click on add button
    addButton() {
    autoComplete = [...this.master]
    }
    // now the dropdown have items and will appear again.


问:
Allow anonymous Authentication based on policy in ASP.NET Core
I have a service where retrieving https://myService.com/data?date={utc.yesterday} is allowed for anonymous (unauthenticated) users, however in certain circumstances https://myService.com/data?date={utc.today} is only allowed for authenticated users.

Basically, an admin needs to approve the preview data before anonymous users can see it. The approval is via another api and is not relevant to this question.

How can I set up an authorization policy, which can result in a challenge when our DB indicates this data has not been approved. Is it possible at policy authorization time to enforce authentication?

答:
A similar situation is when a login endpoint can't be performed under some conditions (the system is under maintenance or the browser is not supported).

I created a custom AuthorizationHandler that performs different checks based on the context as well as querying the database and then calls Succeed or Fail on the context object.

```<code>[Authorize(Policy = nameof(LoginRequirement))]
public class LoginController : ControllerBase
{
}

public sealed class LoginRequirement : IAuthorizationRequirement { }

public class LoginAuthorizationHandler : AuthorizationHandler<LoginRequirement>
{
    private LoginService _service;
    public LoginAuthorizationHandler(LoginService service) {
        _service = service;
    }

    public override async Task HandleAsync(AuthorizationHandlerContext context) {
        if (!context.PendingRequirements.Any(req => req is LoginRequirement)) {
            await base.HandleAsync(context);
            return;
        }

        var httpContext = (HttpContext)context.Resource;
        if (_service.CheckLoginConstraints(httpContext)) {
           var requirement = context.PendingRequirements.First();
           context.Succeed(requirement);
        } else  {
           context.Fail();
        }
    }

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, LoginRequirement requirement)
    {
        var httpContext = (HttpContext)context.Resource;
        if (_service.CheckLoginConstraints(httpContext)) {
           context.Succeed(requirement);
        } else  {
           context.Fail();
        }
    }
}
</code>```

Body:
A similar situation is when a login endpoint can't be performed under some conditions (the system is under maintenance or the browser is not supported).

I created a custom AuthorizationHandler that performs different checks based on the context as well as querying the database and then calls Succeed or Fail on the context object.

[Authorize(Policy = nameof(LoginRequirement))]
public class LoginController : ControllerBase
{
}

public sealed class LoginRequirement : IAuthorizationRequirement { }

public class LoginAuthorizationHandler : AuthorizationHandler<LoginRequirement>
{
    private LoginService _service;
    public LoginAuthorizationHandler(LoginService service) {
        _service = service;
    }

    public override async Task HandleAsync(AuthorizationHandlerContext context) {
        if (!context.PendingRequirements.Any(req => req is LoginRequirement)) {
            await base.HandleAsync(context);
            return;
        }

        var httpContext = (HttpContext)context.Resource;
        if (_service.CheckLoginConstraints(httpContext)) {
           var requirement = context.PendingRequirements.First();
           context.Succeed(requirement);
        } else  {
           context.Fail();
        }
    }

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, LoginRequirement requirement)
    {
        var httpContext = (HttpContext)context.Resource;
        if (_service.CheckLoginConstraints(httpContext)) {
           context.Succeed(requirement);
        } else  {
           context.Fail();
        }
    }
}


问:
Get a file from the same folder when importing (without hardcoding the path)
I'd like to know how I can access important_file.txt without hardcoding the path.
I run main.py that imports some code from myfile.py, where I need to read important_file.txt
Any ideas on how I can do this?

Files:

```<code>main.py
mydir/
    mydir2/
        myfile.py
        important_file.txt
</code>```

main.py

from mydir.mydir2.myfile import MyClass
MyClass.dostuff()
```

<p>mydir/mydir2/myfile.py</p>

<pre class="lang-py prettyprint-override"><code>class MyClass:
    def dostuff():
        pass
        # something to read important_file.txt
        # without hardcoding it (writing mydir/mydir2/important_file.txt)

</code>```

Command

python3 main.py
```

答:
You can use __file__ to read the path of your module. Since myfile.py and important_file.txt are on the same directory you can then use os.path.dirname to get the name of the directory and join it with your file name to get an absolute path to your .txt file. In your myfile.py do:

```<code>import os

class MyClass:
    def dostuff():
        dirname = os.path.dirname(__file__)
        with open(os.path.join(dirname, "important_file.txt")) as f:
            print(f.read())
</code>```

Body:
I'd like to know how I can access important_file.txt without hardcoding the path.
I run main.py that imports some code from myfile.py, where I need to read important_file.txt
Any ideas on how I can do this?

Files:

main.py
mydir/
    mydir2/
        myfile.py
        important_file.txt

main.py

from mydir.mydir2.myfile import MyClass
MyClass.dostuff()

mydir/mydir2/myfile.py

class MyClass:
    def dostuff():
        pass
        # something to read important_file.txt
        # without hardcoding it (writing mydir/mydir2/important_file.txt)

Command

python3 main.py

Body:
You can use __file__ to read the path of your module. Since myfile.py and important_file.txt are on the same directory you can then use os.path.dirname to get the name of the directory and join it with your file name to get an absolute path to your .txt file. In your myfile.py do:

import os

class MyClass:
    def dostuff():
        dirname = os.path.dirname(__file__)
        with open(os.path.join(dirname, "important_file.txt")) as f:
            print(f.read())


问:
How much does Google Apps Script overlap with ECMAscript 5?
I'm starting to incorporate more and more "advanced" Javascript features into Google Apps Script. But I see on Wikipedia that GAS does not include the whole ECMAscript functionality..

What isn't included?

** Update from comment below:

It looks like every aspect of the language that doesn't relate to client side features such as the DOM and the window object is available

答:
Starting May 2020, Google Apps Script is supported by the V8 runtime which takes advantage of modern ECMAScript.

Here's a list of V8 syntax examples. Please note that ES6 Modules are not yet supported at the time of writing (2020/05/31).

If your script is not yet taking advantage of V8 you can always migrate it to V8.


问:
Web Application to know database update
My web application (ASP.NET 4) connects to a database (SQL Server 2005). For every new row inserted in a certain table, I want the web app can do some process (like send  an email to me with new data).

How do I implement the system? My first though is having web app check the table SN column, and have a variable lastProcessedSN. And keep polling every minute. Is it possible to have DB notify web app when there's a new row being inserted?

Please advise, thanks.

EDIT:
Sending an email is just an example, not the exact thing I want to do. So this question is focusing on how to implement the trigger on MSSQL table insert to call my program.

答:
For every new row inserted in a
  certain table, I want the web app can
  do some process (like send an email to
  me with new data).

For this implementation, According to my knowledge you should use the window application.

Is it possible to have DB notify web
  app when there's a new row being
  inserted?

Window application will use System.Windows.Forms.Timer. Below is the sample code.

```<code>System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = Mention the time interval in milliseconds;
myTimer.Start();
</code>```

Timers can be following as well.

System.Threading.Timer

System.Timers.Timer

For more information about the Selection of Timer, you should follow this link

System.Windows.Forms.Timer vs. System.Threading.Timer vs. System.Timers.Timer

```<code>private void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
{
   using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
        con.Open();
        using (SqlCommand cmd = new SqlCommand()) {
            string expression = "Parameter value";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Your Stored Procedure";
            cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
            cmd.Connection = con;
            using (IDataReader dr = cmd.ExecuteReader()) {
                if (dr.Read()) {
                    //Your functionality
                }
            }
        }
    }

}
</code>```

Title: Web Application to know database update

Body:
For every new row inserted in a
  certain table, I want the web app can
  do some process (like send an email to
  me with new data).

For this implementation, According to my knowledge you should use the window application.

Is it possible to have DB notify web
  app when there's a new row being
  inserted?

Window application will use System.Windows.Forms.Timer. Below is the sample code.

System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = Mention the time interval in milliseconds;
myTimer.Start();

Timers can be following as well.

System.Threading.Timer

System.Timers.Timer

For more information about the Selection of Timer, you should follow this link

System.Windows.Forms.Timer vs. System.Threading.Timer vs. System.Timers.Timer

private void TimerEventProcessor(Object myObject,
                                            EventArgs myEventArgs) {
{
   using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
        con.Open();
        using (SqlCommand cmd = new SqlCommand()) {
            string expression = "Parameter value";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Your Stored Procedure";
            cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
            cmd.Connection = con;
            using (IDataReader dr = cmd.ExecuteReader()) {
                if (dr.Read()) {
                    //Your functionality
                }
            }
        }
    }

}


问:
How to raise an event when object created
Why event handler dose not respond to the event when the object created<br/>
when I tried to raise a private event at the same way the private event raised and handled as expected </p>

```<code>Public Class Form1
    Dim WithEvents nClass As Class1
    Private Sub nClass_Created(ByVal sender As Object, ByVal e As System.EventArgs) Handles nClass.Created
        MessageBox.Show("Created !")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        nClass = New Class1
    End Sub
End Class

Public Class Class1
    Event Created(ByVal sender As Object, ByVal e As EventArgs)
    Sub New()
        'some codes

        'when finish
        RaiseEvent Created(Me, New EventArgs)
    End Sub
End Class
</code>```

答:
This concept is broken, logically. In order to raise an event, there has to be an event handler attached to the event. In order to attach a handler, the object has to exist. In order to exist the constructor must complete. You'll never be able to have a constructor raise an event because the delegate list will be empty when the constructor is running (no handlers will have been added)

This would be easier to see in C#, this is how we attach events to things:

```<code>var thing = new Thing();
thing.Event += new EventHandler(NameOfSomeMethod);
</code>```

VB has a similar construct:

```<code>Dim thing as New Thing()
AddHandler(thing.Event, AddressOf(NameOfSomeMethod))
</code>```

As you can see, the thing has to be constructed first. The constructor code could certainly invoke the event, but there won't be any handlers attached so nothing will happen

If you want to get notified every time an object is created use a Factory pattern; the class that constructs your class can raise the event that the class has been created

Body:
Why event handler dose not respond to the event when the object created

when I tried to raise a private event at the same way the private event raised and handled as expected

Public Class Form1
    Dim WithEvents nClass As Class1
    Private Sub nClass_Created(ByVal sender As Object, ByVal e As System.EventArgs) Handles nClass.Created
        MessageBox.Show("Created !")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        nClass = New Class1
    End Sub
End Class

Public Class Class1
    Event Created(ByVal sender As Object, ByVal e As EventArgs)
    Sub New()
        'some codes

        'when finish
        RaiseEvent Created(Me, New EventArgs)
    End Sub
End Class

Body:
This concept is broken, logically. In order to raise an event, there has to be an event handler attached to the event. In order to attach a handler, the object has to exist. In order to exist the constructor must complete. You'll never be able to have a constructor raise an event because the delegate list will be empty when the constructor is running (no handlers will have been added)

This would be easier to see in C#, this is how we attach events to things:

var thing = new Thing();
thing.Event += new EventHandler(NameOfSomeMethod);

VB has a similar construct:

Dim thing as New Thing()
AddHandler(thing.Event, AddressOf(NameOfSomeMethod))

As you can see, the thing has to be constructed first. The constructor code could certainly invoke the event, but there won't be any handlers attached so nothing will happen

If you want to get notified every time an object is created use a Factory pattern; the class that constructs your class can raise the event that the class has been created


问:
Fix grammtical or spelling errors?
I want to test this method in a junit and one more.</p>

答: You are trying to instantiate an object of class fahrenheit in your test class, then since you dont have a class named fahrenheit you are getting error.</p>

Title: Fix grammtical or spelling errors?


问:
How to test ENUMs using JUNIT
How can I create test cases using JUNIT to test ENUMS types. Below I added my code with the enum type.

```<code>public class TrafficProfileExtension {
public static enum CosProfileType {
    BENIGN ("BENIGN"),
    CUSTOMER ("CUSTOMER"),
    FRAME ("FRAME"),
    PPCO ("PPCO"),
    STANDARD ("STANDARD"),
    W_RED ("W-RED"),
    LEGACY("LEGACY"),
    OPTIONB ("OPTIONB");

 private final String cosProfileType;

 private CosProfileType(String s) {
     cosProfileType = s;
    }

    public boolean equalsName(String otherName){
        return (otherName == null)? false:cosProfileType.equals(otherName);
    }

    public String toString(){
       return cosProfileType;
    }
  }
}
</code>```

I created a test case for my enum CosProfileType, and I am getting an error on CosProfileType.How can I make this test case work?

```<code>@Test
   public void testAdd() {
    TrafficProfileExtension ext = new TrafficProfileExtension();
    assertEquals("FRAME", ext.CosProfileType.FRAME);

}
</code>```

答:
```<code>assertEquals("FRAME", CosProfileType.FRAME.name());
</code>```

It will work only when field and value both are same but won't wotk for below:

```<code>FRAME ("frame_value")
</code>```

Better to check with

```<code>assertEquals("FRAME", CosProfileType.FRAME.getFieldName());
</code>```

Title: How to test ENUMs using JUNIT

Body:
How can I create test cases using JUNIT to test ENUMS types. Below I added my code with the enum type.

public class TrafficProfileExtension {
public static enum CosProfileType {
    BENIGN ("BENIGN"),
    CUSTOMER ("CUSTOMER"),
    FRAME ("FRAME"),
    PPCO ("PPCO"),
    STANDARD ("STANDARD"),
    W_RED ("W-RED"),
    LEGACY("LEGACY"),
    OPTIONB ("OPTIONB");

 private final String cosProfileType;

 private CosProfileType(String s) {
     cosProfileType = s;
    }

    public boolean equalsName(String otherName){
        return (otherName == null)? false:cosProfileType.equals(otherName);
    }

    public String toString(){
       return cosProfileType;
    }
  }
}

I created a test case for my enum CosProfileType, and I am getting an error on CosProfileType.How can I make this test case work?

@Test
   public void testAdd() {
    TrafficProfileExtension ext = new TrafficProfileExtension();
    assertEquals("FRAME", ext.CosProfileType.FRAME);

}

Body:
assertEquals("FRAME", CosProfileType.FRAME.name());

It will work only when field and value both are same but won't wotk for below:

FRAME ("frame_value")

Better to check with

assertEquals("FRAME", CosProfileType.FRAME.getFieldName());