问:
nvidia-docker : Got permission denied
Docker newbie question here, so please be nice.

I know this might be asked before but I could not find anything related to nvidia-docker.
I completed the installation instructions on the official guide.

When I wanted to test Nvidia-docker:

docker run --gpus all nvidia/cuda:10.0-base nvidia-smi

I got this error:

```<code>(base) user@adminme:~$ docker run --gpus all --rm nvidia/cuda nvidia-smi
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
</code>```

I found this answer here, but it felt a bit different for my case. I am very new to docker and still learning. let me know what you think?

here is some information about my remote Linux machine:

```<code>(base) user@adminme:~$ lspci | grep -i nvidia
02:00.0 VGA compatible controller: NVIDIA Corporation GP104 [GeForce GTX 1080] (rev a1)
02:00.1 Audio device: NVIDIA Corporation GP104 High Definition Audio Controller (rev a1)
</code>```

nvidia-smi command:

```<code>(base) user@adminme:~$ nvidia-smi
Sun May 31 01:12:25 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1080    Off  | 00000000:02:00.0 Off |                  N/A |
|  0%   33C    P8     9W / 215W |     17MiB /  8116MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      2545      G   /usr/lib/xorg/Xorg                            15MiB |
+-----------------------------------------------------------------------------+
</code>```

docker-version :

```<code>(base) user@adminme:~$ docker --version
Docker version 19.03.10, build 9424aeaee9
</code>```

答:
The quick fix would be to run the container using sudo:

```<code>sudo docker run --gpus all nvidia/cuda:10.0-base nvidia-smi
</code>```

If you want to run docker as non-root user then you need to add it to the docker group.

Create the docker group if it does not exist

```<code>sudo groupadd docker
</code>```

Add your user to the docker group.

```<code>sudo usermod -aG docker $USER
</code>```

Run the following command or Logout and login again and run (that doesn't work you may need to reboot your machine first)

```<code>newgrp docker
</code>```

Check if docker can be run without root

```<code>docker run --gpus all nvidia/cuda:10.0-base nvidia-smi
</code>```

Ref:- https://docs.docker.com/engine/install/linux-postinstall/

Title: nvidia-docker : Got permission denied

Body:
Docker newbie question here, so please be nice.

I know this might be asked before but I could not find anything related to nvidia-docker.
I completed the installation instructions on the official guide.

When I wanted to test Nvidia-docker:

docker run --gpus all nvidia/cuda:10.0-base nvidia-smi

I got this error:

(base) user@adminme:~$ docker run --gpus all --rm nvidia/cuda nvidia-smi
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.

I found this answer here, but it felt a bit different for my case. I am very new to docker and still learning. let me know what you think?

here is some information about my remote Linux machine:

(base) user@adminme:~$ lspci | grep -i nvidia
02:00.0 VGA compatible controller: NVIDIA Corporation GP104 [GeForce GTX 1080] (rev a1)
02:00.1 Audio device: NVIDIA Corporation GP104 High Definition Audio Controller (rev a1)

nvidia-smi command:

(base) user@adminme:~$ nvidia-smi
Sun May 31 01:12:25 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1080    Off  | 00000000:02:00.0 Off |                  N/A |
|  0%   33C    P8     9W / 215W |     17MiB /  8116MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      2545      G   /usr/lib/xorg/Xorg                            15MiB |
+-----------------------------------------------------------------------------+

docker-version :

(base) user@adminme:~$ docker --version
Docker version 19.03.10, build 9424aeaee9

Body:
The quick fix would be to run the container using sudo:

sudo docker run --gpus all nvidia/cuda:10.0-base nvidia-smi

If you want to run docker as non-root user then you need to add it to the docker group.

Create the docker group if it does not exist

sudo groupadd docker

Add your user to the docker group.

sudo usermod -aG docker $USER

Run the following command or Logout and login again and run (that doesn't work you may need to reboot your machine first)

newgrp docker

Check if docker can be run without root

docker run --gpus all nvidia/cuda:10.0-base nvidia-smi

Ref:- https://docs.docker.com/engine/install/linux-postinstall/


来源: stackexchange

问:
Python: Find longest binary gap in binary representation of an integer number
I would like to know if my implementation is efficient.
I have tried to find the simplest and low complex solution to that problem using python.

```<code>def count_gap(x):
    """
        Perform Find the longest sequence of zeros between ones "gap" in binary representation of an integer

        Parameters
        ----------
        x : int
            input integer value

        Returns
        ----------
        max_gap : int
            the maximum gap length

    """
    try:
        # Convert int to binary
        b = "{0:b}".format(x)
        # Iterate from right to lift
        # Start detecting gaps after fist "one"
        for i,j in enumerate(b[::-1]):
            if int(j) == 1:
                max_gap = max([len(i) for i in b[::-1][i:].split('1') if i])
                break
    except ValueError:
        print("Oops! no gap found")
        max_gap = 0
    return max_gap
</code>```

let me know your opinion.

答:
```<code>def solution(N):
    # write your code in Python 3.6
    count = 0
    gap_list=[]
    bin_var = format(N,"b")
    for bit in bin_var:
        if (bit =="1"):
            gap_list.append(count)
            count =0
        else:
            count +=1
    return max(gap_list)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to know if my implementation is efficient.
I have tried to find the simplest and low complex solution to that problem using python.

def count_gap(x):
    """
        Perform Find the longest sequence of zeros between ones "gap" in binary representation of an integer

        Parameters
        ----------
        x : int
            input integer value

        Returns
        ----------
        max_gap : int
            the maximum gap length

    """
    try:
        # Convert int to binary
        b = "{0:b}".format(x)
        # Iterate from right to lift
        # Start detecting gaps after fist "one"
        for i,j in enumerate(b[::-1]):
            if int(j) == 1:
                max_gap = max([len(i) for i in b[::-1][i:].split('1') if i])
                break
    except ValueError:
        print("Oops! no gap found")
        max_gap = 0
    return max_gap

let me know your opinion.

ContentLicense: CC BY-SA 4.0


问:
How to retrieve data from a one to many sql relationship using PHP
I have two tables. One is called "employee" and has a column named "role". I have another table with the name "role" that has two columns in it "role_id" and "name".

I have linked the two in MySQL with a foreign key (I think!), by going to relationship view through phpmyadmin and selecting the appropriate settings.

Now in PHP I have the following code:

```<code>$employees = "SELECT employee_id, first_name, last_name, role
                 FROM employee
                 WHERE status = 1";
$employee = mysqli_query($link, $employees);

foreach ($employee as $employeeInfo) {
    <?php echo $employeeInfo['role'];?>
}
</code>```

However, this returns the number I have assigned to the role in the employee's table. Not the name from the linked table.

I think it has something to do with having to use the JOIN condition is the PHP code. However, doing some experimentation just gets me blank results.

Do you have any tips for outputting the role name from the second table in this case?

Thank you

答:
Inner Joins should really work...</p>

```<code>SELECT employee_id, first_name, last_name, role.name as role
    FROM employee
    INNER JOIN role ON employee.role = role.role_id
    WHERE status = 1;
</code>```

Body:
I have two tables. One is called "employee" and has a column named "role". I have another table with the name "role" that has two columns in it "role_id" and "name".

I have linked the two in MySQL with a foreign key (I think!), by going to relationship view through phpmyadmin and selecting the appropriate settings.

Now in PHP I have the following code:

$employees = "SELECT employee_id, first_name, last_name, role
                 FROM employee
                 WHERE status = 1";
$employee = mysqli_query($link, $employees);

foreach ($employee as $employeeInfo) {
    <?php echo $employeeInfo['role'];?>
}

However, this returns the number I have assigned to the role in the employee's table. Not the name from the linked table.

I think it has something to do with having to use the JOIN condition is the PHP code. However, doing some experimentation just gets me blank results.

Do you have any tips for outputting the role name from the second table in this case?

Thank you

Body:
Inner Joins should really work...

SELECT employee_id, first_name, last_name, role.name as role
    FROM employee
    INNER JOIN role ON employee.role = role.role_id
    WHERE status = 1;


问:
How to convert from a Hybris enumtype to a Java Calendar?
In Hybris, I created an enumeration of days of week.

Here is my code:

```<code>public enum DaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");
}
</code>```

How can I convert this enumeration to a Calendar in Java, so as I can compare between Hybris enumeration and Java Calendar values?

答:
It's unfortunate Hybris does not have an OOTB service / utility for such kind of conversion. If you look at the OOTB de.hybris.platform.servicelayer.cronjob.impl.DefaultTriggerService, it has a DAYS_OF_WEEK_MAP hashmap to deal with this.

You could probably create your own service / utility to do something similar. Here's something I thought of, to convert from Hybris enum to Calendar int (for week), or from Calendar object or int to Hybris enum. You could probably adjust it to become more flexible.

```<code>enum HybrisDaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");

    private final String code;

    private HybrisDaysOfWeek(final String code)
    {
        this.code = code.intern();
    }

    public String getCode()
    {
        return this.code;
    }
}

class CalendarUtil {

    private CalendarUtil() {
        // do not instantiate
    }

    public static final HybrisDaysOfWeek toHybrisDaysOfWeek(Calendar calendar) {
        return HybrisDaysOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK) - 1];
    }

    public static final HybrisDaysOfWeek toHybrisDaysOfWeek(int dayOfWeek) {
        return HybrisDaysOfWeek.values()[dayOfWeek - 1];
    }

    public static final int toCalendarDayOfWeek(HybrisDaysOfWeek week) {
        return week.ordinal() + 1;
    }
}

public class Demo {

    public static void main(String[] args) {

        System.out.println("### Calendar Object to Hybris:");
        Calendar cal = Calendar.getInstance();
        // Prints Sunday (Calendar value: 1)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Monday (Calendar value: 2)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Friday (Calendar value: 6)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Saturday (Calendar value: 7)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));

        System.out.println("### Calendar int to Hybris:");
        // Prints Sunday (Calendar value: 1)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.SUNDAY));
        // Prints Monday (Calendar value: 2)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.MONDAY));
        // Prints Friday (Calendar value: 6)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.FRIDAY));
        // Prints Saturday (Calendar value: 7)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.SATURDAY));

        System.out.println("### Hybris enum to Calendar int:");
        // Prints 1
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.SUNDAY));
        // Prints 2
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.MONDAY));
        // Prints 6
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.FRIDAY));
        // Prints 7
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.SATURDAY));
    }
}
</code>```

Body:
In Hybris, I created an enumeration of days of week.

Here is my code:

public enum DaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");
}

How can I convert this enumeration to a Calendar in Java, so as I can compare between Hybris enumeration and Java Calendar values?

Body:
It's unfortunate Hybris does not have an OOTB service / utility for such kind of conversion. If you look at the OOTB de.hybris.platform.servicelayer.cronjob.impl.DefaultTriggerService, it has a DAYS_OF_WEEK_MAP hashmap to deal with this.

You could probably create your own service / utility to do something similar. Here's something I thought of, to convert from Hybris enum to Calendar int (for week), or from Calendar object or int to Hybris enum. You could probably adjust it to become more flexible.

enum HybrisDaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");

    private final String code;

    private HybrisDaysOfWeek(final String code)
    {
        this.code = code.intern();
    }

    public String getCode()
    {
        return this.code;
    }
}

class CalendarUtil {

    private CalendarUtil() {
        // do not instantiate
    }

    public static final HybrisDaysOfWeek toHybrisDaysOfWeek(Calendar calendar) {
        return HybrisDaysOfWeek.values()[calendar.get(Calendar.DAY_OF_WEEK) - 1];
    }

    public static final HybrisDaysOfWeek toHybrisDaysOfWeek(int dayOfWeek) {
        return HybrisDaysOfWeek.values()[dayOfWeek - 1];
    }

    public static final int toCalendarDayOfWeek(HybrisDaysOfWeek week) {
        return week.ordinal() + 1;
    }
}

public class Demo {

    public static void main(String[] args) {

        System.out.println("### Calendar Object to Hybris:");
        Calendar cal = Calendar.getInstance();
        // Prints Sunday (Calendar value: 1)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Monday (Calendar value: 2)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Friday (Calendar value: 6)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));
        // Prints Saturday (Calendar value: 7)
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(cal));

        System.out.println("### Calendar int to Hybris:");
        // Prints Sunday (Calendar value: 1)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.SUNDAY));
        // Prints Monday (Calendar value: 2)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.MONDAY));
        // Prints Friday (Calendar value: 6)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.FRIDAY));
        // Prints Saturday (Calendar value: 7)
        System.out.println(CalendarUtil.toHybrisDaysOfWeek(Calendar.SATURDAY));

        System.out.println("### Hybris enum to Calendar int:");
        // Prints 1
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.SUNDAY));
        // Prints 2
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.MONDAY));
        // Prints 6
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.FRIDAY));
        // Prints 7
        System.out.println(CalendarUtil.toCalendarDayOfWeek(HybrisDaysOfWeek.SATURDAY));
    }
}


问:
Finding the angle in a right-angle triangle with python 3

I manage to solve this question for only 1 case out of the 5 in the system. I'm certain that my method is correct, but for some reason it doesn't work out for other cases.
Below is my code

```<code>import math
AB = int(input("Enter a value for side AB: "))
while(AB>100 and AB<=0):
     AB = input("Enter a value for side AB: ")
BC = int(input("Enter a value for side BC: "))
while(BC>100 and BC<=0):
     BC = input("Enter a value for side BC: ")
hyp = math.sqrt(math.pow(AB,2) + math.pow(BC,2)) #find side AC
mhyp = hyp/2                                     #find side MC
sind = (mhyp/BC)                                 #sin(deg)=opp/hypotenuse
degree = round(((math.asin(sind))/((math.pi)*2))*360,0) #find the angle
print("%d" %(degree) + "°")
</code>```

For the case when AC and BC are 10, it did yield 45 degrees as the angle. But when AC=1 and BC=100, it produces an error since arcsine cannot accept value beyond 1.7 radians. Same goes for AC=20 and BC=10 and AC=100 and BC=1..
Is this question solvable?

答:
It is a matter of primarily your angle coming in radians and then you converting it into degrees. Rest everything then will fall in place :)

Also, We can see that BM is equal to MC basis the median to hypotenuse property making the triangle MBC as isosceles and hence Angle MBC = Angle MCB.

```<code>import math
if __name__ == '__main__':
    AB = input()
    assert 0<int(AB)<=100
    BC = input()
    assert 0<int(BC)<=100
    assert (int(AB) >= 0 and float(AB).is_integer() == True) and (int(BC) >= 0 and float(BC).is_integer() == True)
    AC = math.sqrt((int(AB)**2) + (int(BC)**2))
    tan_acb_rad = int(AB)/int(BC)
    acb_rad = math.atan(tan_acb_rad) #the angle comes in radians
    acb_deg = math.degrees(acb_rad) #you have to convert it into degrees
    ang_mbc = acb_deg
    print(str(int(round(ang_mbc,0)))+u"\N{DEGREE SIGN}") #adding the degree symbol at end
</code>```

Body:
I manage to solve this question for only 1 case out of the 5 in the system. I'm certain that my method is correct, but for some reason it doesn't work out for other cases.
Below is my code

import math
AB = int(input("Enter a value for side AB: "))
while(AB>100 and AB<=0):
     AB = input("Enter a value for side AB: ")
BC = int(input("Enter a value for side BC: "))
while(BC>100 and BC<=0):
     BC = input("Enter a value for side BC: ")
hyp = math.sqrt(math.pow(AB,2) + math.pow(BC,2)) #find side AC
mhyp = hyp/2                                     #find side MC
sind = (mhyp/BC)                                 #sin(deg)=opp/hypotenuse
degree = round(((math.asin(sind))/((math.pi)*2))*360,0) #find the angle
print("%d" %(degree) + "°")

For the case when AC and BC are 10, it did yield 45 degrees as the angle. But when AC=1 and BC=100, it produces an error since arcsine cannot accept value beyond 1.7 radians. Same goes for AC=20 and BC=10 and AC=100 and BC=1..
Is this question solvable?

Body:
It is a matter of primarily your angle coming in radians and then you converting it into degrees. Rest everything then will fall in place :)

Also, We can see that BM is equal to MC basis the median to hypotenuse property making the triangle MBC as isosceles and hence Angle MBC = Angle MCB.

import math
if __name__ == '__main__':
    AB = input()
    assert 0<int(AB)<=100
    BC = input()
    assert 0<int(BC)<=100
    assert (int(AB) >= 0 and float(AB).is_integer() == True) and (int(BC) >= 0 and float(BC).is_integer() == True)
    AC = math.sqrt((int(AB)**2) + (int(BC)**2))
    tan_acb_rad = int(AB)/int(BC)
    acb_rad = math.atan(tan_acb_rad) #the angle comes in radians
    acb_deg = math.degrees(acb_rad) #you have to convert it into degrees
    ang_mbc = acb_deg
    print(str(int(round(ang_mbc,0)))+u"\N{DEGREE SIGN}") #adding the degree symbol at end


问:
How to select editor in Jquery when using Html.Kendo().EditorFor
I'm using the Telerik Kendo UI editor for a field that can be posted to the server.

```<code>@( Html.Kendo().EditorFor(model => model.TickerContent)
                           .Name("TickerContent")
                           .Encode(true)
                           .HtmlAttributes(new { style = "width:100%;height:440px" }))
</code>```

On the same page as the form I have a list of items that I want to be able to edit, so I need to set the value of the editor. The demo code uses the following code to get and set the value of the editor:

```<code><script>
    $(document).ready(function () {
        var editor = $("#Editor").data("kendoEditor");

        var setValue = function () {
            editor.value($("#value").val());
        };

        $("#get").click(function () {
            alert(editor.value());
        });

        $("#set").click(setValue);
    });
</script>
</code>```

The value of variable editor is always undefined. My question is how can I get and set the editor value?

I tried var editor = $("#TickerContent").data("kendoEditor"); but the editor is still undefined.

答:
For setting the editor value you can set like this:</p>

```<code>$("#Editor").data("kendoEditor").value($("#value").val());
</code>```

Body:
I'm using the Telerik Kendo UI editor for a field that can be posted to the server.

@( Html.Kendo().EditorFor(model => model.TickerContent)
                           .Name("TickerContent")
                           .Encode(true)
                           .HtmlAttributes(new { style = "width:100%;height:440px" }))

On the same page as the form I have a list of items that I want to be able to edit, so I need to set the value of the editor. The demo code uses the following code to get and set the value of the editor:

The value of variable editor is always undefined. My question is how can I get and set the editor value?

I tried var editor = $("#TickerContent").data("kendoEditor"); but the editor is still undefined.

Body:
For setting the editor value you can set like this:

$("#Editor").data("kendoEditor").value($("#value").val());


问:
Having trouble with updatePixels() in a Java app using Processing libraries
I'm trying to write a simple game in Java that uses Processing to render graphics. However, I'm having trouble rendering any changes using updatePixels(). I can successfully set the background color and draw basic 2d shapes, but I get nothing from editing the pixels[] variable, or from using set(x, y, color).

This is my (abridged) code:

```<code>import processing.core.*;

public class GameController extends PApplet {
  private int width, height;

  private final static String RENDER_MODE = PConstants.P2D; //JAVA2D;

  public GameController(int width, int height) {
    this.width = width;
    this.height = height - this.getBounds().y;
  }

  @Override
  public void setup() {
    this.size(this.width, this.height, RENDER_MODE);
    this.background(0);
  }

  @Override
  public void draw() {
    this.ellipse(50, 50, 100, 10);

    this.loadPixels();
    for (int p : this.pixels) {
      p = this.color(255, 0, 0);
    }
    this.updatePixels();
  }
}
</code>```

When I init() this class, I get a white ellipse on a black screen, not a screen of red pixels (which is what I'm expecting).
The pixels[] array is definitely there, as I've printed it out, and I'm getting no errors.
What am I doing wrong?

答:
This line:

```<code>p = this.color(255, 0, 0);
</code>```

only changes the local variable p, which contained a copy if the pixel value.

What you want is to modify the values inside the pixels array, as in:

```<code>for (int i = 0 ; i < pixels.length ; i++) {
    pixels[i] = color(255, 0, 0);
}
</code>```

Body:
I'm trying to write a simple game in Java that uses Processing to render graphics. However, I'm having trouble rendering any changes using updatePixels(). I can successfully set the background color and draw basic 2d shapes, but I get nothing from editing the pixels[] variable, or from using set(x, y, color).

This is my (abridged) code:

import processing.core.*;

public class GameController extends PApplet {
  private int width, height;

  private final static String RENDER_MODE = PConstants.P2D; //JAVA2D;

  public GameController(int width, int height) {
    this.width = width;
    this.height = height - this.getBounds().y;
  }

  @Override
  public void setup() {
    this.size(this.width, this.height, RENDER_MODE);
    this.background(0);
  }

  @Override
  public void draw() {
    this.ellipse(50, 50, 100, 10);

    this.loadPixels();
    for (int p : this.pixels) {
      p = this.color(255, 0, 0);
    }
    this.updatePixels();
  }
}

When I init() this class, I get a white ellipse on a black screen, not a screen of red pixels (which is what I'm expecting).
The pixels[] array is definitely there, as I've printed it out, and I'm getting no errors.
What am I doing wrong?

Body:
This line:

p = this.color(255, 0, 0);

only changes the local variable p, which contained a copy if the pixel value.

What you want is to modify the values inside the pixels array, as in:

for (int i = 0 ; i < pixels.length ; i++) {
    pixels[i] = color(255, 0, 0);
}


问:
use simple for loop in laravel eloquent
I just wanted to use simple for loop in my blade file to create a demo.

the example code in PHP is :

```<code>for($i=0;$i<20;$i++) {
 // the loop events
}
</code>```

the thing is I don't have any parameter to use foreach, therefore i have to use for loop.

答:
This is simple as you want</p>

```<code>@for($i=0;$i<20;$i++)
    {{$i}}
@endfor
</code>```

Title: use simple for loop in laravel eloquent

Body:
I just wanted to use simple for loop in my blade file to create a demo.

the example code in PHP is :

for($i=0;$i<20;$i++) {
 // the loop events
}

the thing is I don't have any parameter to use foreach, therefore i have to use for loop.

Body:
This is simple as you want

@for($i=0;$i<20;$i++)
    {{$i}}
@endfor


问:
How to solve this Import error for pandas?
I get this error when I try to import pandas after installing it using pip install and I'm using IntelliJ

C:\Users\Start\venv\Pyhon3.7\Scripts\python.exe D:/PYTHON/HelloWorld/HelloWorld.py
Traceback (most recent call last):
  File "C:\Users\Start\venv\Pyhon3.7\lib\site-packages\pandas\__init__.py", line 30, in <module>
    from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
  File "pandas\_libs\hashtable.pyx", line 1, in init pandas._libs.hashtable
ImportError: DLL load failed: %1 is not a valid Win32 application.
```
</blockquote>

<p>During handling of the above exception, another exception occurred:</p>

<blockquote>
  <pre class="lang-sh prettyprint-override"><code>Traceback (most recent call last):
  File "D:/PYTHON/HelloWorld/HelloWorld.py", line 25, in <module>
    import pandas as pd
  File "C:\Users\Start\venv\Pyhon3.7\lib\site-packages\pandas\__init__.py", line 38, in <module>
    "the C extensions first.".format(module)
ImportError: C extension: DLL load failed: %1 is not a valid Win32 application. not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first.
</code>```

答:
If you are using Pycharm

Go to settings.

Go to Project: (Project-name)

Go to Project Interpreter and all the modules you have downloaded. Maybe pandas was not installed correctly

Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the pandas library.
You can also go to Unofficial Windows Binaries for Python Extension Packages to find any python libs.

Body:
I get this error when I try to import pandas after installing it using pip install and I'm using IntelliJ

C:\Users\Start\venv\Pyhon3.7\Scripts\python.exe D:/PYTHON/HelloWorld/HelloWorld.py
Traceback (most recent call last):
  File "C:\Users\Start\venv\Pyhon3.7\lib\site-packages\pandas\__init__.py", line 30, in <module>
    from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
  File "pandas\_libs\hashtable.pyx", line 1, in init pandas._libs.hashtable
ImportError: DLL load failed: %1 is not a valid Win32 application.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/PYTHON/HelloWorld/HelloWorld.py", line 25, in <module>
    import pandas as pd
  File "C:\Users\Start\venv\Pyhon3.7\lib\site-packages\pandas\__init__.py", line 38, in <module>
    "the C extensions first.".format(module)
ImportError: C extension: DLL load failed: %1 is not a valid Win32 application. not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first.


问:
Tensorflow epochs are too slow
I'm trying to get started with tensorflow using the python interface. I'm building an image classification system explained Here. But when running the code, epochs take too much time, almost 2 minutes for 1 epoch, and if number of steps are increased, epoch running time increases exponentially.

My system configurations are:

and software configurations are:

Python 3.7

Spyder 4

Tensorflow 2.2.0

I found similar thread Here but in my case, basic operations are fast enough.

How can I improve performance of tensorflow

答: Sadly, both TensorFlow and PyTorch use only Cuda as a backend for GPU acceleration and they don't support any of the Mac'a GPUs - Intel's or AMD's. This means that your TensorFlow code would run only on CPU.</p>

Title: Tensorflow epochs are too slow


问:
Error "Client was not authenticated to send anonymous mail"
i try to send an email with this code...but i have this error :"Client was not authenticated to send anonymous mail during MAIL FROM"

code:

```<code>var smtpClient = new SmtpClient()
        {
            Host = "smtp.office365.com",
            Port = 25, //587
            UseDefaultCredentials = false,
            EnableSsl = true
        };
        smtpClient.UseDefaultCredentials = false;
        smtpClient.DeliveryMethod= System.Net.Mail.SmtpDeliveryMethod.Network;
        smtpClient.Credentials = new NetworkCredential("{mail}", "{password}","{domain}");

        var message = new MailMessage
        {
            From = new MailAddress("{mail}","{display name}",System.Text.Encoding.UTF8),

            Subject = "Test mail",
            IsBodyHtml = false
        };
        message.To.Add("{mail}");

        message.Body = "This is a test mail. ";
        try{
            smtpClient.Send(message);

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
</code>```

thanks

答:
This indicates that you are connecting to the SMTP client submission endpoint (smtp.office365.com), which can't be used for direct send. For direct send, use the MX endpoint for your Office 365 tenant, which ends with "mail.protection.outlook.com." So, please let your admin check the MX record. Moreover, please check if the SMTP port is 25/TLS.

Moreover, you can try the following suggestions to check if there is any improvement:

Remove the account and add it again to check the issue.

Try using another same tenant account to check the issue.

See Client was not authenticated to send anonymous mail for more information.

Body:
i try to send an email with this code...but i have this error :"Client was not authenticated to send anonymous mail during MAIL FROM"

code:

var smtpClient = new SmtpClient()
        {
            Host = "smtp.office365.com",
            Port = 25, //587
            UseDefaultCredentials = false,
            EnableSsl = true
        };
        smtpClient.UseDefaultCredentials = false;
        smtpClient.DeliveryMethod= System.Net.Mail.SmtpDeliveryMethod.Network;
        smtpClient.Credentials = new NetworkCredential("{mail}", "{password}","{domain}");

        var message = new MailMessage
        {
            From = new MailAddress("{mail}","{display name}",System.Text.Encoding.UTF8),

            Subject = "Test mail",
            IsBodyHtml = false
        };
        message.To.Add("{mail}");

        message.Body = "This is a test mail. ";
        try{
            smtpClient.Send(message);

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }

thanks


问:
Incorrect syntax near the keyword 'key'
I am trying to persist a new object into the database, but i am getting this error:

SQL Error: 156, SQLState: S0001

Incorrect syntax near the keyword 'key'.

What I am doing

```<code>Bucket bucket = new Bucket();
bucket.setKey(key);
bucket.setValue(value);

entityManager.persist(bucket);

</code>```

I believe this error is due to the keyword 'key' being used in sql statements causing this.  Is there a native query that I can use to insert rows into my table?

My table has these three columns, with Id being auto-generated.

Bucket:

```<code>@Entity
@Getter
@Setter
@ToString
public class Bucket {

    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id; //auto allocation of PK
    private String key;
    private String value;
}

</code>```

答:
Thank you Martin Smith for the help. Just one simple change and the issue was resolved.

Bucket:

```<code>@Entity
@Getter
@Setter
@ToString
public class Bucket {

    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id; //auto allocation of PK
    @Column(name = "\"key\"")
    private String key;
    @Column(name = "\"value\"")
    private String value;
}

</code>```

Title: Incorrect syntax near the keyword 'key'

Body:
I am trying to persist a new object into the database, but i am getting this error:

SQL Error: 156, SQLState: S0001

Incorrect syntax near the keyword 'key'.

What I am doing

Bucket bucket = new Bucket();
bucket.setKey(key);
bucket.setValue(value);

entityManager.persist(bucket);

I believe this error is due to the keyword 'key' being used in sql statements causing this.  Is there a native query that I can use to insert rows into my table?

My table has these three columns, with Id being auto-generated.

Bucket:

@Entity
@Getter
@Setter
@ToString
public class Bucket {

    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id; //auto allocation of PK
    private String key;
    private String value;
}

Body:
Thank you Martin Smith for the help. Just one simple change and the issue was resolved.

Bucket:

@Entity
@Getter
@Setter
@ToString
public class Bucket {

    @Id @GeneratedValue(strategy= GenerationType.IDENTITY)
    private long id; //auto allocation of PK
    @Column(name = "\"key\"")
    private String key;
    @Column(name = "\"value\"")
    private String value;
}


问:
node: command not found - in wsl bash
I install docker on my windows 10. after that I get a message that I need to download and install wsl2.

Now, when I run bash command I get wsl bash.

When I try to run node I get an error (node.exe is installed in my windows10):

```<code>DESKTOP-BVRDS:/tmp/docker-desktop-root/mnt/host/c/Users/myuser# node
bash: node: command not found
</code>```

when I run echo $PATH I get output of:

```<code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>```

and not the windows path's. (where the node and other software installed).

How to solve this error? maybe change the default bash? to git bash? (which I don't know how)

答:
In Cmder, open settings: Win + Alt + P

Under Startup > Tasks, add a task called {bash} with the following settings:

Task parameters (set icon):

```<code>      For Cmder icon:  /icon "%CMDER_ROOT%\cmder.exe"
</code>```

```<code>      For Git icon: /icon "C:\Program Files (x86)\Git\etc\git.ico"
</code>```

Commands (open Git's bash shell):

```<code>      "C:\Program Files (x86)\Git\bin\sh.exe" -l -new_console:d:%USERPROFILE%
</code>```

Under Startup, set startup options to Specified name task --> {bash}

Please check below a couple of articles and should solve an issue.

https://gist.github.com/nickautomatic/02ccb76292f7f8d9767e
  https://gingter.org/2016/11/16/running-windows-10-ubuntu-bash-in-cmder/

Title: node: command not found - in wsl bash

Body:
I install docker on my windows 10. after that I get a message that I need to download and install wsl2.

Now, when I run bash command I get wsl bash.

When I try to run node I get an error (node.exe is installed in my windows10):

DESKTOP-BVRDS:/tmp/docker-desktop-root/mnt/host/c/Users/myuser# node
bash: node: command not found

when I run echo $PATH I get output of:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

and not the windows path's. (where the node and other software installed).

How to solve this error? maybe change the default bash? to git bash? (which I don't know how)

Body:
In Cmder, open settings: Win + Alt + P

Under Startup > Tasks, add a task called {bash} with the following settings:

Task parameters (set icon):

      For Cmder icon:  /icon "%CMDER_ROOT%\cmder.exe"

      For Git icon: /icon "C:\Program Files (x86)\Git\etc\git.ico"

Commands (open Git's bash shell):

      "C:\Program Files (x86)\Git\bin\sh.exe" -l -new_console:d:%USERPROFILE%

Under Startup, set startup options to Specified name task --> {bash}

Please check below a couple of articles and should solve an issue.

https://gist.github.com/nickautomatic/02ccb76292f7f8d9767e
  https://gingter.org/2016/11/16/running-windows-10-ubuntu-bash-in-cmder/


问:
Detect difference between & and %26 in location.hash
Analyzing the location.hash with this simple javascript code:

I have a difficult time separating out GET variables that contain a & (encoded as %26) and a & used to separate variables.

Example one:

code=php&age=15d

Example two:

code=php%20%26%20code&age=15d

As you can see, example 1 has no problems, but getting javascript to know that "code=php & code" in example two is beyond my abilities:

(Note: I'm not really using these variable names, and changing them to something else will only work so long as a search term does not match a search key, so I wouldn't consider that a valid solution.)

答:
There is no difference between %26 and & in a fragment identifier (‘hash’). ‘&’ is only a reserved character with special meaning in a query (‘search’) segment of a URI. Escaping ‘&’ to ‘%26’ need be given no more application-level visibility than escaping ‘a’ to ‘%61’.

Since there is no standard encoding scheme for hiding structured data within a fragment identifier, you could make your own. For example, use ‘+XX’ hex-encoding to encode a character in a component:

```<code>hxxp://www.example.com/page#code=php+20+2B+20php&age=15d

function encodeHashComponent(x) {
    return encodeURIComponent(x).split('%').join('+');
}
function decodeHashComponent(x) {
    return decodeURIComponent(x.split('+').join('%'));
}

function getHashParameters() {
    var parts= location.hash.substring(1).split('&');
    var pars= {};
    for (var i= parts.length; i-->0;) {
        var kv= parts[i].split('=');
        var k= kv[0];
        var v= kv.slice(1).join('=');
        pars[decodeHashComponent(k)]= decodeHashComponent(v);
    }
    return pars;
}
</code>```

OwnerDisplayName: Eric Caron

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: sblundy

Body:
There is no difference between %26 and & in a fragment identifier (‘hash’). ‘&’ is only a reserved character with special meaning in a query (‘search’) segment of a URI. Escaping ‘&’ to ‘%26’ need be given no more application-level visibility than escaping ‘a’ to ‘%61’.

Since there is no standard encoding scheme for hiding structured data within a fragment identifier, you could make your own. For example, use ‘+XX’ hex-encoding to encode a character in a component:

hxxp://www.example.com/page#code=php+20+2B+20php&age=15d

function encodeHashComponent(x) {
    return encodeURIComponent(x).split('%').join('+');
}
function decodeHashComponent(x) {
    return decodeURIComponent(x.split('+').join('%'));
}

function getHashParameters() {
    var parts= location.hash.substring(1).split('&');
    var pars= {};
    for (var i= parts.length; i-->0;) {
        var kv= parts[i].split('=');
        var k= kv[0];
        var v= kv.slice(1).join('=');
        pars[decodeHashComponent(k)]= decodeHashComponent(v);
    }
    return pars;
}

OwnerDisplayName: bobince

LastEditorDisplayName: bobince


问:
Question about lea instruction, IA32
If I have an IA32 instruction like the following:

```<code>lea 0x4(x1, x2, x3), %eax
</code>```

What do x1, x2, and x3 represent?
Thanks.

答:
They are a base register, an index register, and a scale value. So, it's useful for calculating the address of an element of an array base of elements of size scale at position index, i.e. in C:

```<code>base[index]
</code>```

where scale will be 1 for a char array, 2 for a short array, ... on typical C compilers for x86.

Title: Question about lea instruction, IA32

Body:
If I have an IA32 instruction like the following:

lea 0x4(x1, x2, x3), %eax

What do x1, x2, and x3 represent?
Thanks.

Body:
They are a base register, an index register, and a scale value. So, it's useful for calculating the address of an element of an array base of elements of size scale at position index, i.e. in C:

base[index]

where scale will be 1 for a char array, 2 for a short array, ... on typical C compilers for x86.


问:
How to enable/disable cloudwatch event attached to lambda?
I've tried using the Cloudwatch Events/EventBridge JS SDK to enable/disable the rule which does work on the global scale. However, the cloudwatch event that is attached to my lambda does not change in state.

I'm looking to have a lambda that I can enable/disable the CRON aspect of. I see in the AWS UI there is a toggle to enable/disable the cloudwatch event but I'm not able to figure out how to access this functionality with the JS SDK.

toggle of AWS cloudwatch event:

答:
To disable this you want to look at the event source mapping.

In the JS SDK there is a function named updateEventSourceMapping which is responsible for this.

One of the params you can pass in is Enabled which if set to false will set a disabled flag.

To get the UUID of the event source take a look at the listEventSourceMappings function. You can filter by FunctionName and/or EventSourceArn (in this case the Arn of the CloudWatch Event).

Hope this helps.


问:
How to create a regex that matches either 0 occurrences, or between 7 and 50 occurrences?
In regex, I can match zero or more occurrences with *, and between 7 and 50 occurrences with {7,50}. How can I match either zero or between 7 and 50 occurrences?

答:
Group the range match and make it optional with ? (match 0 or 1 instance).

Python, since a language wasn't specified:

```<code>>>> import re
>>> test = 'abaxbaxxxxxxbaxxxxxxxbaxxxxxxxxb'
>>> re.findall('a(?:x{7,50})?b',test)
['ab', 'axxxxxxxb', 'axxxxxxxxb']
</code>```

Match a.

(?:n) match n but don't make a capture group.grouping.

(?:x{7,50}) groups match 7-50 occurrences of x.

(?:x{7,50})? makes it optional (0 or 1 occurrence)

Match b

Without the non-capturing group you'd get:

```<code>>>> re.findall('a(x{7,50})?b',test)
['', 'xxxxxxx', 'xxxxxxxx']
</code>```

See a working example @ https://regex101.com/r/qkziuu/1

Body:
Group the range match and make it optional with ? (match 0 or 1 instance).

Python, since a language wasn't specified:

>>> import re
>>> test = 'abaxbaxxxxxxbaxxxxxxxbaxxxxxxxxb'
>>> re.findall('a(?:x{7,50})?b',test)
['ab', 'axxxxxxxb', 'axxxxxxxxb']

Match a.

(?:n) match n but don't make a capture group.grouping.

(?:x{7,50}) groups match 7-50 occurrences of x.

(?:x{7,50})? makes it optional (0 or 1 occurrence)

Match b

Without the non-capturing group you'd get:

>>> re.findall('a(x{7,50})?b',test)
['', 'xxxxxxx', 'xxxxxxxx']

See a working example @ https://regex101.com/r/qkziuu/1


问:
How can I make rounded TextField in flutter?
Material Design for iOS doesn't look good, especially the TextField. So is there any way to create your own ? Or Is ther any way to add some styling to TextField so it will look rounded ?

答:
I've collected this solution from several methods and solutions over the internet, it works very well with me, so it could help someone out there:
This solution will control the width and height of the TextField, and other properties

```<code>Container(
    child: Theme(
      data: Theme.of(context).copyWith(splashColor: Colors.transparent),
      child: TextField(
        autofocus: false,
        style: TextStyle(fontSize: 15.0, color: Color(0xFFbdc6cf)),
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          hintText: 'Search',
          contentPadding:
          const EdgeInsets.only(left: 14.0, bottom: 12.0, top: 0.0),

          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.white),
            borderRadius: BorderRadius.circular(25.7),
          ),

          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.white),
            borderRadius: BorderRadius.circular(25.7),
          ),
        ),
      ),
    ),

    decoration: new BoxDecoration (
      borderRadius: new BorderRadius.all(new Radius.circular(30.0)),
      color: Colors.white   ),   width: 250,   height: 50,   margin: new EdgeInsets.fromLTRB(20, 20, 20, 210),   padding: new EdgeInsets.fromLTRB(8, 8, 8, 8),

),
</code>```

Body:
I've collected this solution from several methods and solutions over the internet, it works very well with me, so it could help someone out there:
This solution will control the width and height of the TextField, and other properties

Container(
    child: Theme(
      data: Theme.of(context).copyWith(splashColor: Colors.transparent),
      child: TextField(
        autofocus: false,
        style: TextStyle(fontSize: 15.0, color: Color(0xFFbdc6cf)),
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          hintText: 'Search',
          contentPadding:
          const EdgeInsets.only(left: 14.0, bottom: 12.0, top: 0.0),

          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.white),
            borderRadius: BorderRadius.circular(25.7),
          ),

          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.white),
            borderRadius: BorderRadius.circular(25.7),
          ),
        ),
      ),
    ),

    decoration: new BoxDecoration (
      borderRadius: new BorderRadius.all(new Radius.circular(30.0)),
      color: Colors.white   ),   width: 250,   height: 50,   margin: new EdgeInsets.fromLTRB(20, 20, 20, 210),   padding: new EdgeInsets.fromLTRB(8, 8, 8, 8),

),


问:
C# AutoMapper: set destination value by source value after validation in conditional mapping
I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)

```<code> CreateMap<ClassA, ClassA>()
                    .ForMember(dest => dest.PropertyA, opt =>
                            opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
                    )
</code>```

This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here?
Please help

答:
You can do as follows:

```<code>var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => opt.Condition(src => (src.PropertyB!= null)));
});
</code>```

Or as follows:

```<code>var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => {
        opt.PreCondition(src => (src.PropertyB!=null));
        opt.MapFrom(src => src.PropertyB); // mapping process takes place here
    });
});
</code>```

But the difference is that, the later runs sooner in the mapping process.

There is an excellent documentation in setting conditions for automapper:

https://docs.automapper.org/en/stable/Conditional-mapping.html

Body:
I'm fairly new to AutoMapper and want to know how to set a destination member to a value based on a DIFFERENT source property value and if that value is null I just want to apply the default behaviour of Automapper (keep destination value when the source is null)

 CreateMap<ClassA, ClassA>()
                    .ForMember(dest => dest.PropertyA, opt =>
                            opt.MapFrom(src => src.PropertyB!= null ? null : opt.UseDestinationValue())
                    )

This doesn't work (don't compile) the opt.UseDestinationValue() , what option can I use here?
Please help

Body:
You can do as follows:

var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => opt.Condition(src => (src.PropertyB!= null)));
});

Or as follows:

var configuration = new MapperConfiguration(cfg => {
  cfg.CreateMap<ClassA,ClassA>()
    .ForMember(dest => dest.PropertyA, opt => {
        opt.PreCondition(src => (src.PropertyB!=null));
        opt.MapFrom(src => src.PropertyB); // mapping process takes place here
    });
});

But the difference is that, the later runs sooner in the mapping process.

There is an excellent documentation in setting conditions for automapper:

https://docs.automapper.org/en/stable/Conditional-mapping.html


问:
passing variables as parameter from JSP in onChange event?
I'd like to know if it is possible to pass variables as a parameter from JSP to Onchange function. If so, how to do it ?

```<code><%>for(int i = 0; i < i < 100; i ++){<%>
    <select name="<%= i %>user" id="<%= i %>" onchange="myFunction(<%=i%>)">
      <option value="present">present</option>
      <option value="absent">absent</option>
      <option value="holiday">holiday</option>
    </select>
<%>}<%>
</code>```

```<code>function myFunction(i) {
    var element = document.getElementById(i);

    element.setAttribute("style", "background-color: red;");
}
</code>```

I've been trying different ways, but it doesn't work.

Please help!

答:
You can use <c:forEach></<c:forEach> loop to iterate and use ${loop.index} to get particular value i.e : 0,1..100

Your jsp code will look like below :

```<code><%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
 //begin from 0 loop till 100
 <c:forEach begin="0" end="100" varStatus="loop">
       <select name="${loop.index}user" id="${loop.index}" onchange="myFunction(${loop.index})">
            <option value="present">present</option>
            <option value="absent">absent</option>
            <option value="holiday">holiday</option>
       </select>
  </c:forEach>
</code>```

Your javascript code :

```<code>function myFunction(i) {
   var element = document.getElementById(i);//getting id
    element.style.background = "blue";//apply bg color
}
</code>```

Body:
I'd like to know if it is possible to pass variables as a parameter from JSP to Onchange function. If so, how to do it ?

<%>for(int i = 0; i < i < 100; i ++){<%>
    <select name="<%= i %>user" id="<%= i %>" onchange="myFunction(<%=i%>)">
      <option value="present">present</option>
      <option value="absent">absent</option>
      <option value="holiday">holiday</option>
    </select>
<%>}<%>

function myFunction(i) {
    var element = document.getElementById(i);

    element.setAttribute("style", "background-color: red;");
}

I've been trying different ways, but it doesn't work.

Please help!

Body:
You can use <c:forEach></<c:forEach> loop to iterate and use ${loop.index} to get particular value i.e : 0,1..100

Your jsp code will look like below :

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
 //begin from 0 loop till 100
 <c:forEach begin="0" end="100" varStatus="loop">
       <select name="${loop.index}user" id="${loop.index}" onchange="myFunction(${loop.index})">
            <option value="present">present</option>
            <option value="absent">absent</option>
            <option value="holiday">holiday</option>
       </select>
  </c:forEach>

Your javascript code :

function myFunction(i) {
   var element = document.getElementById(i);//getting id
    element.style.background = "blue";//apply bg color
}


问:
How to decrypt the password in python
My code is connecting to sql server using pyspark. For that connection i am getting encrypted password in jceks. How can i decrypt that password and use to load the tables from sql server. Please suggest.</p>

```<code>import pyspark
import re
from pyspark_llap import HiveWarehouseSession
from pyspark.sql.functions import struct
from pyspark.sql.functions import *
from pyspark.sql.session import SparkSession

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL data source example") \
    .getOrCreate()

hive = HiveWarehouseSession.session(spark).build()

df1 = spark.read.format("jdbc") \
    .option("url", "URL") \
    .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
    .option("dbtable", "tableName") \
    .option("user", "user") \
    .option("password", "password_alias").load()
</code>```

答:
I know it's little late to answer this question, this is one of the ways to pass the alias as password

You need to decrypt the password_alias using hadoopConfiguration, and pass it to spark.

```<code>#Declaring Jceks path and password alias path
    jceks_path="jceks://hdfs/sqlserver.password.jceks"
    alias="password_alias"

# Reading the path of jceks using hadoopConfiguration
    conf = spark.sparkContext._jsc.hadoopConfiguration()
    conf.set('{0}'.format("hadoop.security.credential.provider.path"), jceks_path)

# Get password and make it a string.
    credential_raw = conf.getPassword(alias)
    password = ''
        for i in range(credential_raw.__len__()):
            password = password + str(credential_raw.__getitem__(i))

# Pass the password string to spark.
    df1 = spark.read.format("jdbc") \
        .option("url", "URL") \
        .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
        .option("dbtable", "tableName") \
        .option("user", "user") \
        .option("password", password).load()
</code>```

Title: How to decrypt the password in python

Body:
My code is connecting to sql server using pyspark. For that connection i am getting encrypted password in jceks. How can i decrypt that password and use to load the tables from sql server. Please suggest.

import pyspark
import re
from pyspark_llap import HiveWarehouseSession
from pyspark.sql.functions import struct
from pyspark.sql.functions import *
from pyspark.sql.session import SparkSession

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL data source example") \
    .getOrCreate()

hive = HiveWarehouseSession.session(spark).build()

df1 = spark.read.format("jdbc") \
    .option("url", "URL") \
    .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
    .option("dbtable", "tableName") \
    .option("user", "user") \
    .option("password", "password_alias").load()

Body:
I know it's little late to answer this question, this is one of the ways to pass the alias as password

You need to decrypt the password_alias using hadoopConfiguration, and pass it to spark.

#Declaring Jceks path and password alias path
    jceks_path="jceks://hdfs/sqlserver.password.jceks"
    alias="password_alias"

# Reading the path of jceks using hadoopConfiguration
    conf = spark.sparkContext._jsc.hadoopConfiguration()
    conf.set('{0}'.format("hadoop.security.credential.provider.path"), jceks_path)

# Get password and make it a string.
    credential_raw = conf.getPassword(alias)
    password = ''
        for i in range(credential_raw.__len__()):
            password = password + str(credential_raw.__getitem__(i))

# Pass the password string to spark.
    df1 = spark.read.format("jdbc") \
        .option("url", "URL") \
        .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
        .option("dbtable", "tableName") \
        .option("user", "user") \
        .option("password", password).load()


问:
python: can't open file 'main.py': [Errno 2] No such file or directory - docker
I'm seeing the above error when I try to run my docker image. Below are the screenshots of my docker file and the directory structure.

答:
As you have already specified the WORKDIR in the Dockerfile. Dont' copy your files to /.

Change your command to

```<code>COPY . .   # If you want to copy whole folder into container
</code>```

and as well CMD command to

```<code>CMD ["python", "src/main.py"]
</code>```

Body:
As you have already specified the WORKDIR in the Dockerfile. Dont' copy your files to /.

Change your command to

COPY . .   # If you want to copy whole folder into container

and as well CMD command to

CMD ["python", "src/main.py"]


问:
How to combine python asyncio with threads?
I have successfully built a RESTful microservice with Python asyncio and aiohttp that listens to a POST event to collect realtime events from various feeders.

It then builds an in-memory structure to cache the last 24h of events in a nested defaultdict/deque structure.

Now I would like to periodically checkpoint that structure to disc, preferably using pickle.

Since the memory structure can be >100MB I would like to avoid holding up my incoming event processing for the time it takes to checkpoint the structure.

I'd rather create a snapshot copy (e.g. deepcopy) of the structure and then take my time to write it to disk and repeat on a preset time interval.

I have been searching for examples on how to combine threads (and is a thread even the best solution for this?) and asyncio for that purpose but could not find something that would help me.

Any pointers to get started are much appreciated!

答:
Another alternative is to use loop.call_soon_threadsafe along with an asyncio.Queue as the intermediate channel of communication.

The current documentation for Python 3 also has a section on Developing with asyncio - Concurrency and Multithreading:

import asyncio

# This method represents your blocking code
def blocking(loop, queue):
    import time
    while True:
        loop.call_soon_threadsafe(queue.put_nowait, 'Blocking A')
        time.sleep(2)
        loop.call_soon_threadsafe(queue.put_nowait, 'Blocking B')
        time.sleep(2)

# This method represents your async code
async def nonblocking(queue):
    await asyncio.sleep(1)
    while True:
        queue.put_nowait('Non-blocking A')
        await asyncio.sleep(2)
        queue.put_nowait('Non-blocking B')
        await asyncio.sleep(2)

# The main sets up the queue as the communication channel and synchronizes them
async def main():
    queue = asyncio.Queue()
    loop = asyncio.get_running_loop()

    blocking_fut = loop.run_in_executor(None, blocking, loop, queue)
    nonblocking_task = loop.create_task(nonblocking(queue))

    running = True  # use whatever exit condition
    while running:
        # Get messages from both blocking and non-blocking in parallel
        message = await queue.get()
        # You could send any messages, and do anything you want with them
        print(message)

asyncio.run(main())
```
<p>How to send asyncio tasks to loop running in other thread may also help you.</p>
<p>If you need a more "powerful" example, check out my Wrapper to launch async tasks from threaded code. It will handle the thread safety part for you (for the most part) and let you do things like this:</p>
```# See https://gist.github.com/Lonami/3f79ed774d2e0100ded5b171a47f2caf for the full example

async def async_main(queue):
    # your async code can go here
    while True:
        command = await queue.get()
        if command.id == 'print':
            print('Hello from async!')
        elif command.id == 'double':
            await queue.put(command.data * 2)

with LaunchAsync(async_main) as queue:
    # your threaded code can go here
    queue.put(Command('print'))
    queue.put(Command('double', 7))
    response = queue.get(timeout=1)
    print('The result of doubling 7 is', response)
```

Body:
Another alternative is to use loop.call_soon_threadsafe along with an asyncio.Queue as the intermediate channel of communication.

The current documentation for Python 3 also has a section on Developing with asyncio - Concurrency and Multithreading:

import asyncio

# This method represents your blocking code
def blocking(loop, queue):
    import time
    while True:
        loop.call_soon_threadsafe(queue.put_nowait, 'Blocking A')
        time.sleep(2)
        loop.call_soon_threadsafe(queue.put_nowait, 'Blocking B')
        time.sleep(2)

# This method represents your async code
async def nonblocking(queue):
    await asyncio.sleep(1)
    while True:
        queue.put_nowait('Non-blocking A')
        await asyncio.sleep(2)
        queue.put_nowait('Non-blocking B')
        await asyncio.sleep(2)

# The main sets up the queue as the communication channel and synchronizes them
async def main():
    queue = asyncio.Queue()
    loop = asyncio.get_running_loop()

    blocking_fut = loop.run_in_executor(None, blocking, loop, queue)
    nonblocking_task = loop.create_task(nonblocking(queue))

    running = True  # use whatever exit condition
    while running:
        # Get messages from both blocking and non-blocking in parallel
        message = await queue.get()
        # You could send any messages, and do anything you want with them
        print(message)

asyncio.run(main())

How to send asyncio tasks to loop running in other thread may also help you.

If you need a more "powerful" example, check out my Wrapper to launch async tasks from threaded code. It will handle the thread safety part for you (for the most part) and let you do things like this:

# See https://gist.github.com/Lonami/3f79ed774d2e0100ded5b171a47f2caf for the full example

async def async_main(queue):
    # your async code can go here
    while True:
        command = await queue.get()
        if command.id == 'print':
            print('Hello from async!')
        elif command.id == 'double':
            await queue.put(command.data * 2)

with LaunchAsync(async_main) as queue:
    # your threaded code can go here
    queue.put(Command('print'))
    queue.put(Command('double', 7))
    response = queue.get(timeout=1)
    print('The result of doubling 7 is', response)


问:
I would like to put a word counter in this code but can't
I need to be able to count the number of words I put into the string that I enter. I have tried many different things and none of them have worked for me</p>

```<code>import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter some text: ");
    String str = in.nextLine().toLowerCase();
    String vowels = "aeiou";
    System.out.println(str);

    int vcount = 0;
    int ccount = 0;

for (char c : str.toCharArray()) {

  if (Character.isLetter(c)) {

      if (vowels.indexOf(c) >= 0)
      {
        vcount++;
      }
      else
      {
        ccount++;
        }
    }
}

    System.out.print("your input has " + vcount + " vowels" + "\n");
    System.out.print("your input has " + ccount + " consonants" + "\n");
    //System.out.print("your input has " + words + " words");
   }
}

</code>```

答:
The regex approach is for sure reasonable.
But if you are just starting to learn programming, maybe the folowing approach might be more suited.

Lets' start by defining what a "word" is. One option: "a sequence of one or more consecutive letters".

So when iterating through the characters, we can have the following situations:

We are already in a word and another letter is found -> still in a word

We are already in a word and anything other than a letter is found -> not in a word any more

We are not in a word and a letter is found -> we found a new word

We are not in a word and anything other than a letter is found -> still not in a word

So we have to keep track of "we are in a word" by a boolean variable.

Translated to code:

```<code>int vcount = 0;
int ccount = 0;
int wcount = 0;
boolean inword = false;

for (char c : str.toCharArray())
{
    if (Character.isLetter(c))
    {
        if (vowels.indexOf(c) >= 0)
        {
            vcount++;
        }
        else
        {
            ccount++;
        }
        if (!inword)
        {
            inword = true;
            wcount++;
        }
    }
    else
    {
        inword = false;
    }
}
</code>```

Body:
I need to be able to count the number of words I put into the string that I enter. I have tried many different things and none of them have worked for me

import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter some text: ");
    String str = in.nextLine().toLowerCase();
    String vowels = "aeiou";
    System.out.println(str);

    int vcount = 0;
    int ccount = 0;

for (char c : str.toCharArray()) {

  if (Character.isLetter(c)) {

      if (vowels.indexOf(c) >= 0)
      {
        vcount++;
      }
      else
      {
        ccount++;
        }
    }
}

    System.out.print("your input has " + vcount + " vowels" + "\n");
    System.out.print("your input has " + ccount + " consonants" + "\n");
    //System.out.print("your input has " + words + " words");
   }
}

Body:
The regex approach is for sure reasonable.
But if you are just starting to learn programming, maybe the folowing approach might be more suited.

Lets' start by defining what a "word" is. One option: "a sequence of one or more consecutive letters".

So when iterating through the characters, we can have the following situations:

We are already in a word and another letter is found -> still in a word

We are already in a word and anything other than a letter is found -> not in a word any more

We are not in a word and a letter is found -> we found a new word

We are not in a word and anything other than a letter is found -> still not in a word

So we have to keep track of "we are in a word" by a boolean variable.

Translated to code:

int vcount = 0;
int ccount = 0;
int wcount = 0;
boolean inword = false;

for (char c : str.toCharArray())
{
    if (Character.isLetter(c))
    {
        if (vowels.indexOf(c) >= 0)
        {
            vcount++;
        }
        else
        {
            ccount++;
        }
        if (!inword)
        {
            inword = true;
            wcount++;
        }
    }
    else
    {
        inword = false;
    }
}


问:
TypeError: undefined is not an object(evaluating events[0].name)
Why can't I access the state that I've already set inside the then block? events[0].name is the one causing this error. How do I pass data to my Timeline component to handle this asynchronous-ness?</p>

```<code>  const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);

  React.useEffect(() => {
    firebase
      .database()
      .ref("events/adventure")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
        // Not sure why when i console.log(events[0].name) my terminal gets flooded with the output
      });
  });
  let data = [
    {
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0].name}</Text>,
    },
  ];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};
</code>```

答:
You are setting the events in an asynchronous but trying to access events[0].name in the data array.
So in the initial render until the events are loaded you will get this error.

One fix you can do is to set description conditionally
 description: {events[0]?.name},

Or render the Timeline only if the events array has at least one element

```<code>  return (
    <View style={styles.container}>
     { events.length===1&& <Timeline style={styles.list} data={data} /> }
    </View>
  );
</code>```

Better do a console log of your snapshot.val() to check the values you get from firebase too.

Body:
Why can't I access the state that I've already set inside the then block? events[0].name is the one causing this error. How do I pass data to my Timeline component to handle this asynchronous-ness?

  const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);

  React.useEffect(() => {
    firebase
      .database()
      .ref("events/adventure")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
        // Not sure why when i console.log(events[0].name) my terminal gets flooded with the output
      });
  });
  let data = [
    {
      time: "09:00",
      title: "Event 1",
      description: <Text>{events[0].name}</Text>,
    },
  ];
  return (
    <View style={styles.container}>
      <Timeline style={styles.list} data={data} />
    </View>
  );
};

Body:
You are setting the events in an asynchronous but trying to access events[0].name in the data array.
So in the initial render until the events are loaded you will get this error.

One fix you can do is to set description conditionally
 description: {events[0]?.name},

Or render the Timeline only if the events array has at least one element

  return (
    <View style={styles.container}>
     { events.length===1&& <Timeline style={styles.list} data={data} /> }
    </View>
  );

Better do a console log of your snapshot.val() to check the values you get from firebase too.


问:
How to create a new GitHub account with the same email address?
We are using GitHub Enterprise 2.5.1.

In our company, when a user switches to a new role, a new AD account will be created for him, with a new set of permissions. e.g. my current account is "huj" as a developer with email address "Jirong_Hu@otpp.com, if I become a BA, then:

The old account "huj" will be marked as "OIM Deletion" in AD.

A new account called "huj2" will be created for me, with the same old email address, Jirong_Hu@otpp.com.

My questions are:

As account is automatically created upon login, if I login to GitHub with the new account "huj2", I got this error: Unable to create the user because email Jirong_Hu@otpp.com is already taken and emails is invalid.

How can I create the new account "huj2" in GitHub, with the same old email address.

What's the consequence of doing the above?

答:
The simple answer is NO.
You can't create more than 1 ID in GitHub by the same email, but you can do it by using multiple email IDs.

If you try to do it, GitHub will show an error - "email invalid or already taken", so delete the present account or make it with a new email id .


问:
Interpreting compressed SVG path command syntax
I'm working with compressed SVG path data which has been output from SVGO, and I can't understand one part of a relative line-to command. The path itself looks like this (it's a triangle, and it displays correctly):

<path d="M2107.49 3283.96l70.68 81.44 28.54-81.69-99.22.25z"/>

Pulling apart the d attribute into commands, we get:

```<code>M: (Start coords) 2107.49 3283.96
l: (Relative line to coords) 70.68 81.44 28.54-81.69-99.22.25
z (close)
</code>```

The piece I don't understand is the last 'pair' of the line-to commands: From what I understand, we should have 3 pairs of coordinates, which are either separated by a space 70.68 81.44, or where negative, no space: 28.54-81.69 = 28.54, -81.69. But what's going on in that last 'pair'? Does -99.22.25 represent -99.2 and 2.25? How would I know how to split that?

SVGO is trying to squeeze every last byte out of its compression, so it's possibly taking advantage of some implied parsing rule I can't find a reference to. Does anyone know how to deal with that last pair?

答:
Per the BNF in the SVG specification

...

Similarly, for the string "M 0.6.5", the first coordinate of the "moveto" consumes the characters "0.6" and stops upon encountering the second decimal point because the production of a "coordinate" only allows one decimal point. The result is that the first coordinate will be "0.6" and the second coordinate will be ".5".

So -99.22.25 is -99.22 followed by .25

Body:
I'm working with compressed SVG path data which has been output from SVGO, and I can't understand one part of a relative line-to command. The path itself looks like this (it's a triangle, and it displays correctly):

<path d="M2107.49 3283.96l70.68 81.44 28.54-81.69-99.22.25z"/>

Pulling apart the d attribute into commands, we get:

M: (Start coords) 2107.49 3283.96
l: (Relative line to coords) 70.68 81.44 28.54-81.69-99.22.25
z (close)

The piece I don't understand is the last 'pair' of the line-to commands: From what I understand, we should have 3 pairs of coordinates, which are either separated by a space 70.68 81.44, or where negative, no space: 28.54-81.69 = 28.54, -81.69. But what's going on in that last 'pair'? Does -99.22.25 represent -99.2 and 2.25? How would I know how to split that?

SVGO is trying to squeeze every last byte out of its compression, so it's possibly taking advantage of some implied parsing rule I can't find a reference to. Does anyone know how to deal with that last pair?


问:
List all objects in Alibaba OSS Bucket using its Java SDK
Using Alibaba OSS Java SDK, I can only retrieve maximum 100 objects in Bucket. How to list all objects?

compile group: 'com.aliyun.oss', name: 'aliyun-sdk-oss', version:
  '3.9.1'

ObjectListing objectListing = ossClient.listObjects(bucketName);

int count = 1;
// Use objectListing.getObjectSummaries to obtain the descriptions of all objects.
for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
    System.out.println(count++ + " - " + objectSummary.getKey() + "  " +
            "(size = " + objectSummary.getSize() + ")");
}
```

答:
Using below code, all objects from a Bucket can be listed. Reference Link.</p>

```<code>        do
        {
            System.out.println("**** ITERATION COUNT - " + itCount++ + "*****");
            // The number of objects listed in each page is specified by the maxKeys parameter. If the object number is larger than the specified value, other files are listed in another page.
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName, null, nextMarker, null, 100);

            result = client.listObjects(listObjectsRequest);

            for (OSSObjectSummary summary: result.getObjectSummaries())
            {
                System.out.println("Object Count: " + objCount++ + ", Name:" + summary.getKey());
            }
            nextMarker = result.getNextMarker();
        } while (result.isTruncated());
</code>```

Body:
Using below code, all objects from a Bucket can be listed. Reference Link.

        do
        {
            System.out.println("**** ITERATION COUNT - " + itCount++ + "*****");
            // The number of objects listed in each page is specified by the maxKeys parameter. If the object number is larger than the specified value, other files are listed in another page.
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName, null, nextMarker, null, 100);

            result = client.listObjects(listObjectsRequest);

            for (OSSObjectSummary summary: result.getObjectSummaries())
            {
                System.out.println("Object Count: " + objCount++ + ", Name:" + summary.getKey());
            }
            nextMarker = result.getNextMarker();
        } while (result.isTruncated());


问:
Android Retrofit - Unable to add response to a List / recyclerview
When I get my response.body() it will not allow me to set it to a List.

SAMPLE GSON:

```<code> {
"cod": "200",
"message": 0,
"cnt": 5,
"list": [
    {
        "dt": 1590861600,
        "main": {
            "temp": 17.74,
            "feels_like": 14.52,
            "temp_min": 15.99,
            "temp_max": 17.74,
            "pressure": 1022,
            "sea_level": 1022,
            "grnd_level": 1021,
            "humidity": 51,
            "temp_kf": 1.75
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "broken clouds",
                "icon": "04d"
            }
        ],
        "clouds": {
            "all": 82
        },
        "wind": {
            "speed": 3.75,
            "deg": 124
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2020-05-30 18:00:00"
    },
</code>```

Class

```<code>public class WeatherResponse {

@SerializedName("cod")
@Expose
private String cod;
@SerializedName("message")
@Expose
private Long message;
@SerializedName("cnt")
@Expose
private Long cnt;
@SerializedName("list")
@Expose
private List<WeatherList> results;
@SerializedName("city")
@Expose
private City city;
</code>```

CODE

```<code>  private List<WeatherResponse> mWeatherResponseList;

  public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

            Log.d(TAG, "onResponse: server response " + response.toString());

            // response code 200 means a successful request
            // if successful store the response body in the log
            if (response.code() == 200) {

              mWeatherResponseList = response.body();   --Throws an error
</code>```

The error states incompatible types: Required Java.util.list - Found WeatherResponse

I did this:

list = new ArrayList(Collections.singleton(((response.body())))); Which appears to have worked. But the problem now is the response has nested Json. Its one object with a list of 5 items. When I try to display the 5 items in the recyclerview it only displays the one object but not the nested list of 5 items which I actually want

答:
you are trying to access the entire JSON object but you are required with only the list of results in the JSON object.
so you are getting the single JSON object response in the call, so you could get the list of results this way.

```<code>private List<WeatherList> mWeatherResponseList;

public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

        Log.d(TAG, "onResponse: server response " + response.toString());

        if (response.code() == 200) {

          mWeatherResponseList = response.body().results;
</code>```

This way you are getting the list.

Body:
When I get my response.body() it will not allow me to set it to a List.

SAMPLE GSON:

 {
"cod": "200",
"message": 0,
"cnt": 5,
"list": [
    {
        "dt": 1590861600,
        "main": {
            "temp": 17.74,
            "feels_like": 14.52,
            "temp_min": 15.99,
            "temp_max": 17.74,
            "pressure": 1022,
            "sea_level": 1022,
            "grnd_level": 1021,
            "humidity": 51,
            "temp_kf": 1.75
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "broken clouds",
                "icon": "04d"
            }
        ],
        "clouds": {
            "all": 82
        },
        "wind": {
            "speed": 3.75,
            "deg": 124
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2020-05-30 18:00:00"
    },

Class

public class WeatherResponse {

@SerializedName("cod")
@Expose
private String cod;
@SerializedName("message")
@Expose
private Long message;
@SerializedName("cnt")
@Expose
private Long cnt;
@SerializedName("list")
@Expose
private List<WeatherList> results;
@SerializedName("city")
@Expose
private City city;

CODE

  private List<WeatherResponse> mWeatherResponseList;

  public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

            Log.d(TAG, "onResponse: server response " + response.toString());

            // response code 200 means a successful request
            // if successful store the response body in the log
            if (response.code() == 200) {

              mWeatherResponseList = response.body();   --Throws an error

The error states incompatible types: Required Java.util.list - Found WeatherResponse

I did this:

list = new ArrayList(Collections.singleton(((response.body())))); Which appears to have worked. But the problem now is the response has nested Json. Its one object with a list of 5 items. When I try to display the 5 items in the recyclerview it only displays the one object but not the nested list of 5 items which I actually want

Body:
you are trying to access the entire JSON object but you are required with only the list of results in the JSON object.
so you are getting the single JSON object response in the call, so you could get the list of results this way.

private List<WeatherList> mWeatherResponseList;

public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

        Log.d(TAG, "onResponse: server response " + response.toString());

        if (response.code() == 200) {

          mWeatherResponseList = response.body().results;

This way you are getting the list.


问:
Read a Text file having row in parenthesis and values separated by comma using pandas
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

```<code>(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)
</code>```

I want the data in this format :

```<code>a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4
</code>```

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.

答:
I'm sure there is a slicker and more Pythonic way, but here is a quick and dirty function that you can build on

```<code>def str_parser(in_str):
     out_str = ""
     while(in_str != ""):
         first_idx, last_idx = in_str.index("("), in_str.index(")")
         sub_str = in_str[first_idx+1: last_idx]
         out_str += (sub_str.replace(",", "") + "\n")
         in_str = in_str[last_idx+1:]
     return out_str
</code>```

Input:

```<code>print(str_parser("(a, b, c, d) (a1, b1, c1, d1) (a2, b2, c2, d2) (a3, b3, c3, d3) (a4, b4, c4, d4)"))
</code>```

Output:

```<code>a b c d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4

</code>```

Body:
I want to read a text file which contains data in parenthesis as row and values in it as column.The format of txt file is below :

(a, b, c, d) (a1, b1, (c1,c12,c13), d1) (a2, b2, (c2,c22,c23), d2) (a3, b3, (c3,c32,c33), d3) (a4, b4, (c4,c42,c43), d4)

I want the data in this format :

a  b  c  d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4

When i am reading text file as csv file it reads all the data in one row only. It shows 1 row and all the columns.
Please help me with this problem.

Body:
I'm sure there is a slicker and more Pythonic way, but here is a quick and dirty function that you can build on

def str_parser(in_str):
     out_str = ""
     while(in_str != ""):
         first_idx, last_idx = in_str.index("("), in_str.index(")")
         sub_str = in_str[first_idx+1: last_idx]
         out_str += (sub_str.replace(",", "") + "\n")
         in_str = in_str[last_idx+1:]
     return out_str

Input:

print(str_parser("(a, b, c, d) (a1, b1, c1, d1) (a2, b2, c2, d2) (a3, b3, c3, d3) (a4, b4, c4, d4)"))

Output:

a b c d
a1 b1 c1 d1
a2 b2 c2 d2
a3 b3 c3 d3
a4 b4 c4 d4


问:
Need to Apply pipe for specific property out of many property
I am receiving 18 property from API, I need to apply date pipe for a two-property value. How I can apply in .ts file out of 18 property.

In below the code,

```<code>return {
       prop: i,
       index: index,
       };
</code>```

give all the property. and return to _cols, I need to apply date pipe for two fields to make the date as US format.

this is .ts file:

```<code>private getStatusSummary(clearCache?: boolean) {
this.loaderService.startLoader(this.loader.id);
let params = {
  reportname: 'getscriptstatusdisplay',
  fromDate: '',
  toDate: ''
};
params = merge({}, params, this.filters);

this.httpClient
  .cache(clearCache)
  .get(`/${API.sourceStatusSummary}`, {
    params: params
  })
  .subscribe(
    (data: any) => {
      this.loaderService.stopLoader(this.loader.id);
      const error = get(data, 'errorMessage', '');
      const records = get(data, 'body', []);
      if (error) {
      } else {
        this.rows = records;
        let _cols =
          isArray(this.rows) && this.rows.length > 0
            ? Object.keys(get(this.rows, '[0]')).map((i, index) =>
          {
                  return {
                  prop: i,
                  index: index,
                };

              })
            : [];
        this.tempRows = records;

        this.columns = _cols;

        this.allColumns = _cols;
        this.columns.push({
          prop: 'Action',
          index: this.columns.length,
          width: 100,
          resizeable: false,
          sortable: false,
          cellTemplate: this.actionTemplate
        });

        this.setError('');
      }
    },
    error => {
      this.loaderService.stopLoader(this.loader.id);
      this.setError(error);
    }
  );
}
</code>```

HTML CODE:

```<code>   <ngx-datatable
    [rows]="rows"
    [rowHeight]="'auto'"
    [scrollbarH]="true"
    class="bootstrap"
    [columnMode]="'force'"
    [reorderable]="'false'"
    [headerHeight]="50"
    [footerHeight]="50"
    [limit]="ITEM_PER_PAGE"
    [hidden]="rows.length === 0"

  #table
>
 <ngx-datatable-column
    [resizeable]="false"
    *ngFor="let col of columns;"
    [prop]="col.prop"
    [cellTemplate]="col.cellTemplate"
    [maxWidth]="col.maxWidth"
  >
  </ngx-datatable-column>
</code>```

I need to display the date property as US(07-16-1997)formate as of now it is giving as  1997-07-16T19:20:30.45+01:00

答:
should be easy, just pass the pipe you want to apply to that column's data:

Ngx-Datatable Docs

Example: I want to format all the data in my column as currency values i.e instead 100000, it shows $100,000.

```<code>{
                prop: 'commitment',
                name: 'Hourly Commitment',
                pipe: this.currencyPipe
}
</code>```

where I'm using the default currency pipe available in Angular. You can use the Date Pipe to solve your use-case.
Date Pipe from Angular

Body:
I am receiving 18 property from API, I need to apply date pipe for a two-property value. How I can apply in .ts file out of 18 property.

In below the code,

return {
       prop: i,
       index: index,
       };

give all the property. and return to _cols, I need to apply date pipe for two fields to make the date as US format.

this is .ts file:

private getStatusSummary(clearCache?: boolean) {
this.loaderService.startLoader(this.loader.id);
let params = {
  reportname: 'getscriptstatusdisplay',
  fromDate: '',
  toDate: ''
};
params = merge({}, params, this.filters);

this.httpClient
  .cache(clearCache)
  .get(`/${API.sourceStatusSummary}`, {
    params: params
  })
  .subscribe(
    (data: any) => {
      this.loaderService.stopLoader(this.loader.id);
      const error = get(data, 'errorMessage', '');
      const records = get(data, 'body', []);
      if (error) {
      } else {
        this.rows = records;
        let _cols =
          isArray(this.rows) && this.rows.length > 0
            ? Object.keys(get(this.rows, '[0]')).map((i, index) =>
          {
                  return {
                  prop: i,
                  index: index,
                };

              })
            : [];
        this.tempRows = records;

        this.columns = _cols;

        this.allColumns = _cols;
        this.columns.push({
          prop: 'Action',
          index: this.columns.length,
          width: 100,
          resizeable: false,
          sortable: false,
          cellTemplate: this.actionTemplate
        });

        this.setError('');
      }
    },
    error => {
      this.loaderService.stopLoader(this.loader.id);
      this.setError(error);
    }
  );
}

HTML CODE:

   <ngx-datatable
    [rows]="rows"
    [rowHeight]="'auto'"
    [scrollbarH]="true"
    class="bootstrap"
    [columnMode]="'force'"
    [reorderable]="'false'"
    [headerHeight]="50"
    [footerHeight]="50"
    [limit]="ITEM_PER_PAGE"
    [hidden]="rows.length === 0"

  #table
>
 <ngx-datatable-column
    [resizeable]="false"
    *ngFor="let col of columns;"
    [prop]="col.prop"
    [cellTemplate]="col.cellTemplate"
    [maxWidth]="col.maxWidth"
  >
  </ngx-datatable-column>

I need to display the date property as US(07-16-1997)formate as of now it is giving as  1997-07-16T19:20:30.45+01:00

Body:
should be easy, just pass the pipe you want to apply to that column's data:

Ngx-Datatable Docs

Example: I want to format all the data in my column as currency values i.e instead 100000, it shows $100,000.

{
                prop: 'commitment',
                name: 'Hourly Commitment',
                pipe: this.currencyPipe
}

where I'm using the default currency pipe available in Angular. You can use the Date Pipe to solve your use-case.
Date Pipe from Angular


问:
how can add 10 marks when collision is detected?

score_value = 0
lives_value = 3

# Check if collide/overlap
def collision(rleft, rtop, rlength, cX, cY, radius):
    rright = rleft + rlength
    cbottom = cY + radius
    score_value = 0
    lives_value = 3
    if (rleft <= cX <= rright) and (cbottom >= rtop):
        score_value += 10
    else:
        lives_value -= 1
```

<pre class="lang-py prettyprint-override"><code># Defining variables
rright = rect_x + rect_length
rbottom = rect_y + rect_width

# Call the collision() function
collision(rect_x, rect_y , rect_length, circle_x, circle_y, radius)
</code>```

I have to create a pygame which when a circle collides with a rectangle, 10 points should be added. But now the score just kept increasing like crazy, even when the ball is falling, how can I fix this? Above are the codes i wrote for this project. original questionPLEASE HELP

答:
The problem is that the collision is not detected just once. It is recognized several times in consecutive frames. Add a return value to the function collision that indicates if the collision was detected:

def collision(rleft, rtop, rlength, cX, cY, radius):
    rright = rleft + rlength
    cbottom = cY + radius
    score_value = 0
    lives_value = 3
    collision = (rleft <= cX <= rright) and (cbottom >= rtop)

    if collision:
        score_value += 10
    else:
        lives_value -= 1
    return collision:
```
<p>Add a variable <code>rect_circle_collided</code> to the application and store the result of <code>collision</code> to the variable. Only Invoke  <code>collision</code> if <code>rect_circle_collided</code> is <code>False</code>:</p>
<pre class="lang-py prettyprint-override"><code>rect_circle_collided = False

while not done:

    # [...]

    # Call the collision() function
    if not rect_circle_collided:
        rect_circle_collided = collision(rect_x, rect_y , rect_length, circle_x, circle_y, radius)
</code>```

Note you have to reset the state (rect_circle_collided = False) when you create new circle at the top of the window.

Body:
score_value = 0
lives_value = 3

# Check if collide/overlap
def collision(rleft, rtop, rlength, cX, cY, radius):
    rright = rleft + rlength
    cbottom = cY + radius
    score_value = 0
    lives_value = 3
    if (rleft <= cX <= rright) and (cbottom >= rtop):
        score_value += 10
    else:
        lives_value -= 1

# Defining variables
rright = rect_x + rect_length
rbottom = rect_y + rect_width

# Call the collision() function
collision(rect_x, rect_y , rect_length, circle_x, circle_y, radius)

I have to create a pygame which when a circle collides with a rectangle, 10 points should be added. But now the score just kept increasing like crazy, even when the ball is falling, how can I fix this? Above are the codes i wrote for this project. original questionPLEASE HELP

Body:
The problem is that the collision is not detected just once. It is recognized several times in consecutive frames. Add a return value to the function collision that indicates if the collision was detected:

def collision(rleft, rtop, rlength, cX, cY, radius):
    rright = rleft + rlength
    cbottom = cY + radius
    score_value = 0
    lives_value = 3
    collision = (rleft <= cX <= rright) and (cbottom >= rtop)

    if collision:
        score_value += 10
    else:
        lives_value -= 1
    return collision:

Add a variable rect_circle_collided to the application and store the result of collision to the variable. Only Invoke  collision if rect_circle_collided is False:

rect_circle_collided = False

while not done:

    # [...]

    # Call the collision() function
    if not rect_circle_collided:
        rect_circle_collided = collision(rect_x, rect_y , rect_length, circle_x, circle_y, radius)

Note you have to reset the state (rect_circle_collided = False) when you create new circle at the top of the window.