问:
Google analytics on my React app with firebase SDK
I used Google Analytics a lot for many sites...

I'm just releasing a first app with Firebase (Firestore + Firebase SDK with reactjs).

Then, I activated GA from my Firebase dashboard... but I cannot see any activity !

I probably need not to add plugin like "autotrack" ?

```<code>import 'autotrack';
ga('create', 'UA-XXXXX-Y', 'auto');
</code>```

It's not clear because, it's impossible to find out the track ID (UA-XXXXX-Y) from my dashboard !

Do I really need it ? Where can I find it ?

答:
Firebase gone through a lot of new updates. Change imports like this;</p>
```<code>import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/analytics';
</code>```

Body:
I used Google Analytics a lot for many sites...

I'm just releasing a first app with Firebase (Firestore + Firebase SDK with reactjs).

Then, I activated GA from my Firebase dashboard... but I cannot see any activity !

I probably need not to add plugin like "autotrack" ?

import 'autotrack';
ga('create', 'UA-XXXXX-Y', 'auto');

It's not clear because, it's impossible to find out the track ID (UA-XXXXX-Y) from my dashboard !

Do I really need it ? Where can I find it ?

Body:
Firebase gone through a lot of new updates. Change imports like this;

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/analytics';


来源: stackexchange

问:
SQL: SUM on Aggregate columns
I have this query:

```<code>SELECT
  spend_codes.spend_code,
  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
FROM spend_codeables
LEFT JOIN spend_codes
  ON spend_codeables.spend_code_id = spend_codes.id
LEFT JOIN orders
  ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
LEFT JOIN ordered_items
  ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
GROUP BY
  spend_codes.spend_code;
</code>```

Which has this result:

```<code>+--------------+---------------+--------------+
| spend_code   | order_total   | item_total   |
|--------------+---------------+--------------|
| 1230131391   | $362.00       | <null>       |
| A12345       | <null>        | <null>       |
| B29393       | <null>        | $374.28      |
+--------------+---------------+--------------+
</code>```

However, I'd like to add order_total and item_total in order to get just total.

So I'd expect this:

```<code>+--------------+---------------+
| spend_code   | total         |
|--------------+---------------+
| 1230131391   | $362.00       |
| A12345       | <null>        |
| B29393       | $374.28       |
+--------------+---------------+
</code>```

Doing this did not work:

```<code>  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) +
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as total

</code>```

Another monkeywrench is that the type of the numbers is money not integer.

Anyone would be able to help?

答:
If any of the 2 sums returns NULL then the result of the sum of the sums will also be NULL because NULL + anything returns NULL.

Use SUM() only once:

```<code>SUM(
  orders.shipping_cost +
  orders.sales_tax +
  orders.manual_total +
  orders.fees +
  ordered_items.fees +
  ordered_items.price * ordered_items.quantity
) as total
</code>```

If any of the columns involved may also be NULL use COALESCE() like COALESCE(orders.shipping_cost, 0::money)

ContentLicense: CC BY-SA 4.0

Title: SQL: SUM on Aggregate columns

Body:
I have this query:

SELECT
  spend_codes.spend_code,
  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) as order_total,
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as item_total
FROM spend_codeables
LEFT JOIN spend_codes
  ON spend_codeables.spend_code_id = spend_codes.id
LEFT JOIN orders
  ON spend_codeables.spend_codeable_id = orders.id AND spend_codeables.spend_codeable_type = 'App\Order'
LEFT JOIN ordered_items
  ON spend_codeables.spend_codeable_id = ordered_items.id AND spend_codeables.spend_codeable_type = 'App\OrderedItem'
GROUP BY
  spend_codes.spend_code;

Which has this result:

+--------------+---------------+--------------+
| spend_code   | order_total   | item_total   |
|--------------+---------------+--------------|
| 1230131391   | $362.00       | <null>       |
| A12345       | <null>        | <null>       |
| B29393       | <null>        | $374.28      |
+--------------+---------------+--------------+

However, I'd like to add order_total and item_total in order to get just total.

So I'd expect this:

+--------------+---------------+
| spend_code   | total         |
|--------------+---------------+
| 1230131391   | $362.00       |
| A12345       | <null>        |
| B29393       | $374.28       |
+--------------+---------------+

Doing this did not work:

  SUM(orders.shipping_cost + orders.sales_tax + orders.manual_total + orders.fees) +
  SUM(ordered_items.fees + ordered_items.price * ordered_items.quantity) as total

Another monkeywrench is that the type of the numbers is money not integer.

Anyone would be able to help?

Body:
If any of the 2 sums returns NULL then the result of the sum of the sums will also be NULL because NULL + anything returns NULL.

Use SUM() only once:

SUM(
  orders.shipping_cost +
  orders.sales_tax +
  orders.manual_total +
  orders.fees +
  ordered_items.fees +
  ordered_items.price * ordered_items.quantity
) as total

If any of the columns involved may also be NULL use COALESCE() like COALESCE(orders.shipping_cost, 0::money)


问:
Unit Testing TSQL
Is there anybody out there writing unit tests for their TSQL stored procedures, triggers, functions ... etc.

I've recently started making database and restores and installs part of our automated Cruise Control build process.  Now I'm thinking about taking it to the next level where we do the install, then run through a list of stored procedure tests etc.

I was going to just roll my own using MsBuild Extensions to invoke the tests.  However I'm aware of http://www.tsqltest.org/ and http://tsqlunit.sourceforge.net/.  I'm also aware that TFS has sql testing.

I just wanted to see what people in the real world are doing and if they have any suggestions.

Thanks

答:
I have used the database testing that is built into Visual Studio 2008 Database Edition on a project here.  It works well, but feels more like a third party bolt-on to Visual Studio than a native component.  Some of the pains I felt with it are:

Because SQL code lives in the res files and a single code file can include multiple tests, it is not as easy to search for tests based on table/column names.

Because multiple tests live in the same code files, you have some annoying variable name collisions (eg, if you have two tests in a single code file, all of the assertions for those tests have to have unique names; That means your assertion names will probably look like "testname_assertionname", which really shouldn't be necessary).

Refactoring your tests is not easy - for example, if you want to move a test from one code file to another, the easiest way is to create the test from scratch in the new file because there are bits and pieces of the test scattered about the res file and the code file.

All of that said, as I started with - It does work well.  Unfortunately, we have not added these tests to our continuous integration server yet, so I can't comment on how easy it is to automate the running of these tests.  We are using TFS for CI, and I am assuming that automation of the tests would work very similar to automation of standard unit tests; In other words, it seems like there should be an MSTest command line that would run the tests.

Of course, this is only an option if you are licensed to run Visual Studio 2008 DB Edition (which I understand is now included in the VS 2008 Pro license).

OwnerDisplayName: Richard

ContentLicense: CC BY-SA 2.5

Title: Unit Testing TSQL

OwnerDisplayName: Chris


问:
using two consecutive values from a list in each iteration
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.  </p>

```<code>import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :
</code>```

答:
A generator would probably be my way of choice on this one, they're simple, easy, and can be wrapped up and modularized better than an embedded for loop

```<code>>>> def solution_pairs(list):
...     for p0, p3 in zip(list, list[1:]):
...         yield (p0, p3)
</code>```

This can then be used in your code sussinctly in the for loop

```<code>>>> list = [1, 2, 3, 4, 5]
>>> for p0, p3 in solution_pairs(list):
...     print p0, p3
1 2
2 3
3 4
4 5
</code>```

You could even wrap your entire for loop that you currently have into a generator and have it yield p_u if you were so inclined.

ContentLicense: CC BY-SA 3.0

Body:
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.

import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :

Body:
A generator would probably be my way of choice on this one, they're simple, easy, and can be wrapped up and modularized better than an embedded for loop

>>> def solution_pairs(list):
...     for p0, p3 in zip(list, list[1:]):
...         yield (p0, p3)

This can then be used in your code sussinctly in the for loop

>>> list = [1, 2, 3, 4, 5]
>>> for p0, p3 in solution_pairs(list):
...     print p0, p3
1 2
2 3
3 4
4 5

You could even wrap your entire for loop that you currently have into a generator and have it yield p_u if you were so inclined.


问:
Is it possible for a program to read itself?
Theoretical question. But let's say I have written an assembly program. I have "labelx:" I want the program to read at this memory address and only this size and print to stdout.

Would it be something like

```<code>jmp labelx
</code>```

And then would i then use the Write syscall , making sure to read from the next instruction from labelx:

```<code>mov rsi,rip
mov rdi,0x01
mov rdx,?
mov rax,0x01
syscall
</code>```

to then output to stdout.

However how would I obtain the size to read itself? Especially if there is a
label after the code i want to read or code after. Would I have to manually
count the lines?

```<code>mov rdx,rip+(bytes*lines)
</code>```

And then syscall with populated registers for the syscall to write to from rsi to rdi. Being stdout.

Is this Even possible? Would i have to use the read syscall first, as the write system call requires rsi to be allocated memory buffer. However I assumed .text is already allocated memory and is read only. Would I have to allocate onto the stack or heap or a static buffer first before write, if it's even possible in the first place?

I'm using NASM syntax btw. And pretty new to assembly. And just a question.

答:
Yes, the .text section is just bytes in memory, no different from section .rodata where you might normally put msg: db "hello", 10.  x86 is a Von Neumann architecture (not Harvard), so there's no distinction between code pointers and data pointers, other than what you choose to do with them.  Use objdump -drwC -Mintel on a linked executable to see the machine-code bytes, or GDB's x command in a running process, to see bytes anywhere.

You can get the assembler to calculate the size by putting labels at the start/end of the part you want, and using mov edx, prog_end - prog_start in the code at the point where you want that size in RDX.

See How does $ work in NASM, exactly? for more about subtracting two labels (in the same section) to get a size. (Where $ is an implicit label at the start of the current line, although $ isn't likely what you want here.)

To get the current address into a register, you need a RIP-relative LEA, not mov, because RIP isn't a general-purpose register and there's no special form of mov that reads it.

```<code>here:
    lea rsi, [rel here]     ; with DEFAULT REL you could just use [here]
    mov edi, 1              ; stdout fileno
    mov edx, .end - here    ; assemble-time constant size calculation
    mov eax, 1              ; __NR_write
    syscall
.end:
</code>```

This is fully position-independent, unlike if you used mov esi, here.  (How to load address of function or label into register)

The LEA could use lea rsi, [rel $] to assemble to the same machine-code bytes, but you want a label there so you can  subtract them.

I optimized your MOV instructions to use 32-bit operand-size, implicitly zero-extending into the full 64-bit RDX and RAX.  (And RDI, but write(int fd, void *buf, size_t len) only looks at EDI anyway for the file descriptor).

Note that you can write any bytes of any section; there's nothing special about having a block of code write itself.  In the above example, put the start/end labels anywhere.  (e.g. foo: and .end:, and mov edx, foo.end - foo taking advantage of how NASM local labels work, by appending to the previous non-local label, so you can reference them from somewhere else.  Or just give them both non-dot names.)

Body:
Theoretical question. But let's say I have written an assembly program. I have "labelx:" I want the program to read at this memory address and only this size and print to stdout.

Would it be something like

jmp labelx

And then would i then use the Write syscall , making sure to read from the next instruction from labelx:

mov rsi,rip
mov rdi,0x01
mov rdx,?
mov rax,0x01
syscall

to then output to stdout.

However how would I obtain the size to read itself? Especially if there is a
label after the code i want to read or code after. Would I have to manually
count the lines?

mov rdx,rip+(bytes*lines)

And then syscall with populated registers for the syscall to write to from rsi to rdi. Being stdout.

Is this Even possible? Would i have to use the read syscall first, as the write system call requires rsi to be allocated memory buffer. However I assumed .text is already allocated memory and is read only. Would I have to allocate onto the stack or heap or a static buffer first before write, if it's even possible in the first place?

I'm using NASM syntax btw. And pretty new to assembly. And just a question.

Body:
Yes, the .text section is just bytes in memory, no different from section .rodata where you might normally put msg: db "hello", 10.  x86 is a Von Neumann architecture (not Harvard), so there's no distinction between code pointers and data pointers, other than what you choose to do with them.  Use objdump -drwC -Mintel on a linked executable to see the machine-code bytes, or GDB's x command in a running process, to see bytes anywhere.

You can get the assembler to calculate the size by putting labels at the start/end of the part you want, and using mov edx, prog_end - prog_start in the code at the point where you want that size in RDX.

See How does $ work in NASM, exactly? for more about subtracting two labels (in the same section) to get a size. (Where $ is an implicit label at the start of the current line, although $ isn't likely what you want here.)

To get the current address into a register, you need a RIP-relative LEA, not mov, because RIP isn't a general-purpose register and there's no special form of mov that reads it.

here:
    lea rsi, [rel here]     ; with DEFAULT REL you could just use [here]
    mov edi, 1              ; stdout fileno
    mov edx, .end - here    ; assemble-time constant size calculation
    mov eax, 1              ; __NR_write
    syscall
.end:

This is fully position-independent, unlike if you used mov esi, here.  (How to load address of function or label into register)

The LEA could use lea rsi, [rel $] to assemble to the same machine-code bytes, but you want a label there so you can  subtract them.

I optimized your MOV instructions to use 32-bit operand-size, implicitly zero-extending into the full 64-bit RDX and RAX.  (And RDI, but write(int fd, void *buf, size_t len) only looks at EDI anyway for the file descriptor).

Note that you can write any bytes of any section; there's nothing special about having a block of code write itself.  In the above example, put the start/end labels anywhere.  (e.g. foo: and .end:, and mov edx, foo.end - foo taking advantage of how NASM local labels work, by appending to the previous non-local label, so you can reference them from somewhere else.  Or just give them both non-dot names.)


问:
Jenkins agent(jnlp) Got permission denied /var/run/docker.sock on kubernetes
I deployed Jenkins via Helm chart(jenkins-helm:3.11.4) on my local Kubernetes cluster(rancher desktop). I installed docker on jenkins/inbound-agent image because it is not included where I am using the default Jenkins-controller image as provided. When I run the docker command in the local pipeline I am getting a permission error as below.

I am aware that, the issue is the permission for /var/run/.docker.sock folder but I could not fix it and really stuck. I tried to add command:["sh","-c","chmod 777 /var/run/.docker.sock ] to the agent in values.yaml but this time jenkins did not up and running properly. I tried to add RUN usermod -aG docker jenkins to the Dockerfile but still same.

```<code>jenkins@default-cnmq7:~/agent$ id
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),0(root)
jenkins@default-cnmq7:~/agent$ grep docker /etc/group
docker:x:107:
</code>```

So how can I grant permission for this folder through the helm chart for Jenkins agent pod? Or what is the proper solution to fix this issue.

```<code>node {
  stage('SCM') {
    checkout(scm)
  }
  stage('Build') {
    echo 'Building Project'
    sh """
      docker pull alpine
    """
  }
}

 [Pipeline] sh
    + docker pull alpine
    Using default tag: latest
    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.24/images/create?fromImage=alpine&tag=latest": dial unix /var/run/docker.sock: connect: permission denied
</code>```

values.yaml

```<code>    controller:
      componentName: "jenkins-controller"
      image: "jenkins"
      # tag: "2.319.3-jdk11"
      tagLabel: jdk11
      imagePullPolicy: "Always"
      imagePullSecretName:
      javaOpts: "-Xms512m -Xmx2048m"
      jenkinsUrl: "http://localhost:8080"
    agent:
      enabled: true
      defaultsProviderTemplate: ""
      # URL for connecting to the Jenkins contoller
      jenkinsUrl:
      jenkinsTunnel:
      image: "jenkins/inbound-agent"
      tag: "4.11.2-5"
      workingDir: "/home/jenkins/agent"
      nodeUsageMode: "NORMAL"
      componentName: "jenkins-agent"
      websocket: false
      privileged: true
      runAsUser:
      runAsGroup:
      alwaysPullImage: true
      podRetention: "Never"
      volumes:
      - type: HostPath
        hostPath: /Users/username/workspace
        mountPath: /Users/username/workspace
      - type: HostPath
        hostPath: /var/run/docker.sock
        mountPath: /var/run/docker.sock
      command:
      args: "${computer.jnlpmac} ${computer.name}"
</code>```

Dockerfile for jenkins agent

```<code>FROM jenkins/inbound-agent:4.11.2-4
USER root
RUN set -eux && \
    apt-get update && \
    apt-get install -y curl sudo docker.io docker-compose && \
    curl -sS https://raw.githubusercontent.com/HariSekhon/bash-tools/master/clean_caches.sh | sh
RUN usermod -aG docker jenkins
USER jenkins
</code>```

答:
First find the group id of docker from the Host

```<code>$ grep docker /etc/group
docker:x:999:
</code>```

Then create a user in the Dockerfile which its group is the same is docker group id.

```<code>RUN groupadd -g 999 tech
RUN useradd -g tech tech
USER tech
</code>```

Body:
I deployed Jenkins via Helm chart(jenkins-helm:3.11.4) on my local Kubernetes cluster(rancher desktop). I installed docker on jenkins/inbound-agent image because it is not included where I am using the default Jenkins-controller image as provided. When I run the docker command in the local pipeline I am getting a permission error as below.

I am aware that, the issue is the permission for /var/run/.docker.sock folder but I could not fix it and really stuck. I tried to add command:["sh","-c","chmod 777 /var/run/.docker.sock ] to the agent in values.yaml but this time jenkins did not up and running properly. I tried to add RUN usermod -aG docker jenkins to the Dockerfile but still same.

jenkins@default-cnmq7:~/agent$ id
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),0(root)
jenkins@default-cnmq7:~/agent$ grep docker /etc/group
docker:x:107:

So how can I grant permission for this folder through the helm chart for Jenkins agent pod? Or what is the proper solution to fix this issue.

node {
  stage('SCM') {
    checkout(scm)
  }
  stage('Build') {
    echo 'Building Project'
    sh """
      docker pull alpine
    """
  }
}

 [Pipeline] sh
    + docker pull alpine
    Using default tag: latest
    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.24/images/create?fromImage=alpine&tag=latest": dial unix /var/run/docker.sock: connect: permission denied

values.yaml

    controller:
      componentName: "jenkins-controller"
      image: "jenkins"
      # tag: "2.319.3-jdk11"
      tagLabel: jdk11
      imagePullPolicy: "Always"
      imagePullSecretName:
      javaOpts: "-Xms512m -Xmx2048m"
      jenkinsUrl: "http://localhost:8080"
    agent:
      enabled: true
      defaultsProviderTemplate: ""
      # URL for connecting to the Jenkins contoller
      jenkinsUrl:
      jenkinsTunnel:
      image: "jenkins/inbound-agent"
      tag: "4.11.2-5"
      workingDir: "/home/jenkins/agent"
      nodeUsageMode: "NORMAL"
      componentName: "jenkins-agent"
      websocket: false
      privileged: true
      runAsUser:
      runAsGroup:
      alwaysPullImage: true
      podRetention: "Never"
      volumes:
      - type: HostPath
        hostPath: /Users/username/workspace
        mountPath: /Users/username/workspace
      - type: HostPath
        hostPath: /var/run/docker.sock
        mountPath: /var/run/docker.sock
      command:
      args: "${computer.jnlpmac} ${computer.name}"

Dockerfile for jenkins agent

FROM jenkins/inbound-agent:4.11.2-4
USER root
RUN set -eux && \
    apt-get update && \
    apt-get install -y curl sudo docker.io docker-compose && \
    curl -sS https://raw.githubusercontent.com/HariSekhon/bash-tools/master/clean_caches.sh | sh
RUN usermod -aG docker jenkins
USER jenkins

Body:
First find the group id of docker from the Host

$ grep docker /etc/group
docker:x:999:

Then create a user in the Dockerfile which its group is the same is docker group id.

RUN groupadd -g 999 tech
RUN useradd -g tech tech
USER tech


问:
Disable Required validation attribute under certain circumstances
I was wondering if it is possible to disable the Required validation attribute in certain controller actions. I am wondering this because on one of my edit forms I do not require the user to enter values for fields that they have already specified previously. However I then implement logic that when they enter a value it uses some special logic to update the model, such as hashing a value etc.

Any sugestions on how to get around this problem?

EDIT:

And yes client validation is a problem here to, as it will not allow them to submit the form without entering a value.

答:
This one worked for me:</p>
```<code>$('#fieldId').rules('remove', 'required');
</code>```

Body:
This one worked for me:

$('#fieldId').rules('remove', 'required');


问:
fatal error: json-c/json.h: No such file or directory Cross compiling on ubuntu x64 for raspberry pi arm
I am trying to compile my code on my Ubuntu x64 laptop for the Raspberry Pi. </p>

<p>I am able to compile and run the code on Ubuntu laptop without any issue. However when I try to compile it for Raspberry Pi I get the following error: </p>

```<code>$make
/home/nmohan/Development/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-gcc -g -Wall -Wextra -I /home/nmohan/github/NiRobot/inc -fPIC -shared -L/home/nmohan/github/NiRobot/Obj_arm -Wl,-rpath=/home/nmohan/github/NiRobot/Obj -o  /home/nmohan/github/NiRobot/Obj_arm/libRSXA.so /home/nmohan/github/NiRobot/lib/RSXA.c -lNMT_stdlib -lNMT_log -ljson-c -lc  -Ljson-c
/home/nmohan/github/NiRobot/lib/RSXA.c:11:25: fatal error: json-c/json.h: No such file or directory
compilation terminated.
Makefile:101: recipe for target '/home/nmohan/github/NiRobot/Obj_arm/libRSXA.so' failed
make: *** [/home/nmohan/github/NiRobot/Obj_arm/libRSXA.so] Error 1
</code>```

```<code>#---------------------------------------#
#                                       #
#            Global Varibles            #
#                                       #
#---------------------------------------#
PROJ_DIR    = /home/nmohan/github/NiRobot
BIN_DIR     = $(PROJ_DIR)/bin
OBJ_DIR     = $(PROJ_DIR)/Obj
OBJ_DIR_ARM = $(PROJ_DIR)/Obj_arm
INC_DIR     = $(PROJ_DIR)/inc
LIB_DIR     = $(PROJ_DIR)/lib
OUT_DIR     = $(PROJ_DIR)/bld
OUT_DIR_ARM = $(PROJ_DIR)/bld_arm
CFLAGS      = -g -Wall -Wextra -I $(INC_DIR)
SFLAGS      = -fPIC -shared
RPATH       = -L$(OBJ_DIR) -Wl,-rpath=$(OBJ_DIR)
RPATH_ARM   = -L$(OBJ_DIR_ARM) -Wl,-rpath=$(OBJ_DIR)
GCC_DIR     = /home/nmohan/Development/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-gcc

#---------------------------------------#
#                                       #
#              Targets                  #
#                                       #
#---------------------------------------#
OBJS        = NMT_stdlib.so \
              NMT_log.so \
              RSXA.so \
              PCA9685.so \
              MTDR.so \
              CAM_MOTOR_CTRL.so \
              HCxSR04.so

#---------------------------------------#
#                                       #
#            Dependancies               #
#                                       #
#---------------------------------------#
NMT_STDLIB_LIBS     = -lc

NMT_LOG_LIBS        = -lc \
                      -lNMT_stdlib \

RSXA_LIBS           = -lNMT_stdlib \
                      -lNMT_log \
                      -ljson-c \
                      -lc

PCA9685_LIBS        = -lNMT_stdlib \
                      -lNMT_log \
                      -lc \
                      -lwiringPi \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

MTDR_LIBS           = -lNMT_stdlib \
                      -lNMT_log \
                      -lwiringPi \
                      -lPCA9685 \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

CAM_MOTOR_CTRL_LIBS = -lNMT_stdlib \
                      -lNMT_log \
                      -lwiringPi \
                      -lMTDR \
                      -lPCA9685 \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

HCxSR04_LIBS        = -lNMT_log \
                      -lNMT_stdlib \
                      -lRSXA \
                      -lwiringPi \
                      -lcrypt \
                      -lm \
                      -lrt

TARGET_OBJS := $(foreach OBJ,$(OBJS),$(OBJ_DIR)/lib$(OBJ))
TARGET_OBJS_ARM := $(foreach OBJ,$(OBJS),$(OBJ_DIR_ARM)/lib$(OBJ))

all: $(TARGET_OBJS) \
     $(TARGET_OBJS_ARM)
.PHONY: all

$(OBJ_DIR)/lib%.so: $(LIB_DIR)/%.c $(INC_DIR)/%.h
    gcc $(CFLAGS) $(SFLAGS) $(RPATH) -o  $@ $< $($(*)_LIBS)

$(OBJ_DIR_ARM)/lib%.so: $(LIB_DIR)/%.c $(INC_DIR)/%.h
    $(GCC_DIR) $(CFLAGS) $(SFLAGS) $(RPATH_ARM) -o  $@ $< $($(*)_LIBS)

$(OBJ_DIR)/lib%.so: $(LIB_DIR)/%.cpp $(INC_DIR)/%.hpp
    g++ $(CFLAGS) $(SFLAGS) $(RPATH) -o  $@ $< $($(*)_LIBS)
</code>```

答:
Installing libjson-c-dev package.</p>
```<code>sudo apt install libjson-c-dev
</code>```

Body:
I am trying to compile my code on my Ubuntu x64 laptop for the Raspberry Pi.

I am able to compile and run the code on Ubuntu laptop without any issue. However when I try to compile it for Raspberry Pi I get the following error:

$make
/home/nmohan/Development/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-gcc -g -Wall -Wextra -I /home/nmohan/github/NiRobot/inc -fPIC -shared -L/home/nmohan/github/NiRobot/Obj_arm -Wl,-rpath=/home/nmohan/github/NiRobot/Obj -o  /home/nmohan/github/NiRobot/Obj_arm/libRSXA.so /home/nmohan/github/NiRobot/lib/RSXA.c -lNMT_stdlib -lNMT_log -ljson-c -lc  -Ljson-c
/home/nmohan/github/NiRobot/lib/RSXA.c:11:25: fatal error: json-c/json.h: No such file or directory
compilation terminated.
Makefile:101: recipe for target '/home/nmohan/github/NiRobot/Obj_arm/libRSXA.so' failed
make: *** [/home/nmohan/github/NiRobot/Obj_arm/libRSXA.so] Error 1

#---------------------------------------#
#                                       #
#            Global Varibles            #
#                                       #
#---------------------------------------#
PROJ_DIR    = /home/nmohan/github/NiRobot
BIN_DIR     = $(PROJ_DIR)/bin
OBJ_DIR     = $(PROJ_DIR)/Obj
OBJ_DIR_ARM = $(PROJ_DIR)/Obj_arm
INC_DIR     = $(PROJ_DIR)/inc
LIB_DIR     = $(PROJ_DIR)/lib
OUT_DIR     = $(PROJ_DIR)/bld
OUT_DIR_ARM = $(PROJ_DIR)/bld_arm
CFLAGS      = -g -Wall -Wextra -I $(INC_DIR)
SFLAGS      = -fPIC -shared
RPATH       = -L$(OBJ_DIR) -Wl,-rpath=$(OBJ_DIR)
RPATH_ARM   = -L$(OBJ_DIR_ARM) -Wl,-rpath=$(OBJ_DIR)
GCC_DIR     = /home/nmohan/Development/arm-bcm2708-linux-gnueabi/bin/arm-bcm2708-linux-gnueabi-gcc

#---------------------------------------#
#                                       #
#              Targets                  #
#                                       #
#---------------------------------------#
OBJS        = NMT_stdlib.so \
              NMT_log.so \
              RSXA.so \
              PCA9685.so \
              MTDR.so \
              CAM_MOTOR_CTRL.so \
              HCxSR04.so

#---------------------------------------#
#                                       #
#            Dependancies               #
#                                       #
#---------------------------------------#
NMT_STDLIB_LIBS     = -lc

NMT_LOG_LIBS        = -lc \
                      -lNMT_stdlib \

RSXA_LIBS           = -lNMT_stdlib \
                      -lNMT_log \
                      -ljson-c \
                      -lc

PCA9685_LIBS        = -lNMT_stdlib \
                      -lNMT_log \
                      -lc \
                      -lwiringPi \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

MTDR_LIBS           = -lNMT_stdlib \
                      -lNMT_log \
                      -lwiringPi \
                      -lPCA9685 \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

CAM_MOTOR_CTRL_LIBS = -lNMT_stdlib \
                      -lNMT_log \
                      -lwiringPi \
                      -lMTDR \
                      -lPCA9685 \
                      -lcrypt \
                      -lm \
                      -lrt \
                      -lRSXA

HCxSR04_LIBS        = -lNMT_log \
                      -lNMT_stdlib \
                      -lRSXA \
                      -lwiringPi \
                      -lcrypt \
                      -lm \
                      -lrt

TARGET_OBJS := $(foreach OBJ,$(OBJS),$(OBJ_DIR)/lib$(OBJ))
TARGET_OBJS_ARM := $(foreach OBJ,$(OBJS),$(OBJ_DIR_ARM)/lib$(OBJ))

all: $(TARGET_OBJS) \
     $(TARGET_OBJS_ARM)
.PHONY: all

$(OBJ_DIR)/lib%.so: $(LIB_DIR)/%.c $(INC_DIR)/%.h
    gcc $(CFLAGS) $(SFLAGS) $(RPATH) -o  $@ $< $($(*)_LIBS)

$(OBJ_DIR_ARM)/lib%.so: $(LIB_DIR)/%.c $(INC_DIR)/%.h
    $(GCC_DIR) $(CFLAGS) $(SFLAGS) $(RPATH_ARM) -o  $@ $< $($(*)_LIBS)

$(OBJ_DIR)/lib%.so: $(LIB_DIR)/%.cpp $(INC_DIR)/%.hpp
    g++ $(CFLAGS) $(SFLAGS) $(RPATH) -o  $@ $< $($(*)_LIBS)

Body:
Installing libjson-c-dev package.

sudo apt install libjson-c-dev


问:
How to fix the error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>')
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};
```
<p>The error is happening at <code>const res = await fetch("/api/sendChoice" ,{</code></p>
<p>In terminal server the error</p>
<blockquote>
<p>error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'</p>
</blockquote>
<p>In the inspect element the error is as<br />
<img src="https://i.stack.imgur.com/15p7J.png" alt="this" /></p>
<p>I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.</p>
<p>Some other related code from my project:</p>
<p>api/sendChoice</p>
<pre class="lang-js prettyprint-override"><code>import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}
</code>```

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);
```

答:
if you are using Docker then, giving a version will solve the problem.

before:

```<code>FROM node:alpine

</code>```

now

```<code>FROM node:16.5.0-alpine

WORKDIR /app
COPY package.json .
RUN npm install --only=prod
COPY . .

CMD ["npm", "start"]
</code>```

Body:
I am sending my data to MongoDB via Mongoose. Now, during the fetch of API route for it, an error is thrown.

Code

const addChoice = async (e) => {
    try {
        e.preventDefault();
        const res = await fetch("/api/sendChoice", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                choiceSeq: choice,
                checkSubmit: true,
            }),
        });
        console.log(res);
        router.push("/home");
    } catch (error) {
        console.log(error);
    }
};

The error is happening at const res = await fetch("/api/sendChoice" ,{

In terminal server the error

error - TypeError: Cannot assign to read only property 'map' of object
'#<QueryCursor>'

In the inspect element the error is as

I can't find anything related to fix this issue, I don't even understand what the error means to try to resolve it myself.

Some other related code from my project:

api/sendChoice

import { getSession } from "next-auth/client";
import dbConnect from "../../helpers/dbConnect";
import Choice from "../../models/Choice";

export default async function sendChoice(req, res) {
    try {
        const session = await getSession({ req });
        await dbConnect();
        if (!session) {
            res.status(401).send("You are not signed in");
            return;
        }
        if (req.method === "POST") {
            console.log(req.body);
            const { choiceSeq, checkSubmit } = req.body;
            console.log(choiceSeq, checkSubmit);
            const userId = session.user.id;
            const nameP = session.user.name;
            const choice = new Choice({
                user: userId,
                name: nameP,
                choiceSeq,
                checkSubmit,
            });
            await choice.save();
            res.status(200).send("Choice saved");
        } else {
            res.status(400).send("Bad request");
        }
    }
    catch (error) {
        console.log(error);
    }
}

The MongoDB schema

import mongoose, { Schema } from 'mongoose';

const ChoiceSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
    },
    name: {
        type: String,
    },
    choiceSeq: {
        type: Array,
        default: [],
    },
    checkSubmit: {
        type: Boolean,
    }
});

mongoose.models = {};

export default mongoose.model('Choice', ChoiceSchema);

Body:
if you are using Docker then, giving a version will solve the problem.

before:

FROM node:alpine

now

FROM node:16.5.0-alpine

WORKDIR /app
COPY package.json .
RUN npm install --only=prod
COPY . .

CMD ["npm", "start"]


问:
Is there any way to delete useless functions in JS libraries?
I'm building a project in javascript, using paper.js in some features.
Most of my project is built in vanilla Javascript, just some minimum but important features are built with paper.js

The problem is that the library (.min library) is 200kb.
The normal library is 300kb, I was wondering if there is an automatic way to see which functions are being used in the main paper.js library, in order to delete the useless functions.
If  there is no program or automatic way to do this, maybe some advice of how to do it manually, or which tools you recommend for me and my team in order to delete useless functions, then minify the file and run it smaller.

Thank you all guys, I did not added any specific code because I want this anwser to be global.

Greetings

答:
I used the paper-core version and then minified.
I saved 140kb by doing this.
There's still no way to see useless functions in this library</p>


问:
Postgresql running inside docker container (gcp remote instance) can't be accessed from dbeaver locally
I'm running postgres as an indipendent service in an independent docker container on a remote instance (gcp) - see docker compose file below.

Postgres is actually working - if I access it through the container, I can connect and do operations within it (create db, users ...).

enter image description here

But, when I try to connect to the postgres db via dbeaver I always get a Connection attempt timed out error.

Here my dbeaver configuration:
Host: 172.17.0.1
Port: 5432
DB - Username - Password: postgres (as defined in the docker compose file)

Firewall rule has been set up in gcp. enter image description here

```<code>version: '3.7'
services:
    postgres:
        image: postgres:latest
        environment:
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
            - POSTGRES_DB=postgres
        ports:
             - "5432:5432"
        logging:
             options:
                  max-size: 10m
                  max-file: "3"
        volumes:
             - /opt/postgres_data:/var/lib/postgresql/data

    webserver:
        image: puckel/docker-airflow:latest
        restart: always
        depends_on:
            - postgres
        environment:
            - LOAD_EX=n
            - EXECUTOR=Local
        logging:
            options:
                max-size: 10m
                max-file: "3"
        volumes:
            - /opt/dags:/opt/airflow/dags
            - /opt/airflow_logs:/opt/airflow/logs
        ports:
            - "8080:8080"
        command: webserver
        healthcheck:
            test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
            interval: 30s
            timeout: 30s
            retries: 3

    scheduler:
        image: puckel/docker-airflow:latest
        restart: always
        depends_on:
            - postgres
            - webserver
        environment:
            - EXECUTOR=Local
        volumes:
            - /opt/dags:/opt/airflow/dags
            - /opt/airflow_logs:/opt/airflow/logs
        command: scheduler
</code>```

答: In order to connect using dbeaver you need to used localhost as host instead of 172.17.0.1 because this the db server inside docker compose network.

Body:
I'm running postgres as an indipendent service in an independent docker container on a remote instance (gcp) - see docker compose file below.

Postgres is actually working - if I access it through the container, I can connect and do operations within it (create db, users ...).

enter image description here

But, when I try to connect to the postgres db via dbeaver I always get a Connection attempt timed out error.

Here my dbeaver configuration:
Host: 172.17.0.1
Port: 5432
DB - Username - Password: postgres (as defined in the docker compose file)

Firewall rule has been set up in gcp. enter image description here

version: '3.7'
services:
    postgres:
        image: postgres:latest
        environment:
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
            - POSTGRES_DB=postgres
        ports:
             - "5432:5432"
        logging:
             options:
                  max-size: 10m
                  max-file: "3"
        volumes:
             - /opt/postgres_data:/var/lib/postgresql/data

    webserver:
        image: puckel/docker-airflow:latest
        restart: always
        depends_on:
            - postgres
        environment:
            - LOAD_EX=n
            - EXECUTOR=Local
        logging:
            options:
                max-size: 10m
                max-file: "3"
        volumes:
            - /opt/dags:/opt/airflow/dags
            - /opt/airflow_logs:/opt/airflow/logs
        ports:
            - "8080:8080"
        command: webserver
        healthcheck:
            test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
            interval: 30s
            timeout: 30s
            retries: 3

    scheduler:
        image: puckel/docker-airflow:latest
        restart: always
        depends_on:
            - postgres
            - webserver
        environment:
            - EXECUTOR=Local
        volumes:
            - /opt/dags:/opt/airflow/dags
            - /opt/airflow_logs:/opt/airflow/logs
        command: scheduler


问:
CSS animation when border's size change
I have a little probleme with my website: when I click on one of my boxes, the size of it changes, but without transition, even if I put transitions everywhere in my CSS. Here is my code and screens.
Thanks for your help.
Edit : I add my code in snippet, sry
Basically, my code works well, I juste want the transition when I close a box to be less brutal. If you don't want to check all the code, the variables starting by -tran are times (between 200 and 1000 ms).

first screen
second screen

const   body = document.querySelector("body"),
        sidebar = body.querySelector(".sidebar"),
        toggle = body.querySelector(".toggle"),
        searchBtn = body.querySelector(".search-box"),
        modeSwitch = body.querySelector(".toggle-switch"),
        modeText = body.querySelector(".mode-text"),
        moi = body.querySelector(".article"),
        afficher_moi = body.querySelector(".afficher_moi");

        toggle.addEventListener("click", () =>{
            sidebar.classList.toggle("close");
        });

        searchBtn.addEventListener("click", () =>{
            sidebar.classList.remove("close");
        });

        modeSwitch.addEventListener("click", () =>{
            body.classList.toggle("dark");

            if(body.classList.contains("dark")){
                modeText.innerText = "Light Mode";
            }
            else{
                modeText.innerText = "Dark Mode";
            }
        });

        $(document).ready(function () {
            $(".article1").click(function () {
              $(".article1").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article2").click(function () {
              $(".article2").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article3").click(function () {
              $(".article3").toggleClass("close");
            });
        });

        $(document).ready(function () {
            $(".article4").click(function () {
              $(".article4").toggleClass("close");
            });
        });

        ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Importation des polices */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

/* Tout */
*{
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Initialisation des variables au lancement */
:root{
    --body-color: #e4e9f7;
    --sidebar-color: #fff;
    --primary-color: #695cfe;
    --primary-color-light: #f6f5ff;
    --toggle-color: #ddd;
    --text-color: #707070;

    --tran-02: all 0.2s ease;
    --tran-03: all 0.3s ease;
    --tran-04: all 0.4s ease;
    --tran-05: all 0.5s ease;
    --tran-10: all 1s ease;

}

/* Body */
body{
    height: 100vh;
    background: var(--body-color);
    transition: var(--tran-05);
}

body.dark{
    --body-color: #18191a;
    --sidebar-color: #242526;
    --primary-color: #3a3b3c;
    --primary-color-light: #3a3b3c;
    --toggle-color: #fff;
    --text-color: #ccc;
}

body.dark .sidebar header .toggle{
    color: var(--text-color);
}

body.dark .sidebar li a:hover .icon, body.dark .sidebar li a:hover .text{
    color: var(--text-color);
}

body.dark .menu-bar .mode i.sun{
    opacity: 1;
}

body.dark .menu-bar .mode i.moon{
    opacity: 0;
}

body.dark .switch::before{
    left: 1.25vw;
}

/* sidebar */
.sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 13vw;
    padding: 0.925vh 0.73vw;
    background: var(--sidebar-color);
    transition: var(--tran-05);
    z-index: 100;
}

.sidebar header .toggle{
    position: absolute;
    top: 50%;
    right: -1.302vw;
    transform: translateY(-50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--sidebar-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
}

.sidebar .text{
    font-size: 0.83vw;
    font-weight: 500;
    color: var(--text-color);
    transition: var(--tran-05);
    white-space: nowrap;
    opacity: 1;
}

.sidebar .image{
    min-width: 3.125vw;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sidebar li{
    height: 4.63vh;
    margin-top: 0.93vh;
    list-style: none;
    display: flex;
    align-items: center;
}

.sidebar li .icon{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.042vw;
    min-width: 3.125vw;
}

.sidebar li .icon, .sidebar li .text{
    color: var(--text-color);
    transition: var(--tran-05);
}

.sidebar .image-text img{
    width: 2.08vw;
    border-radius: 0.3125vw;
}

.sidebar .search-box{
    background: var(--primary-color-light);
    border-radius: 0.3125vw;
    transition: var(--tran-05)
}

.sidebar .menu{
    margin-top: 3.24vh;
}

.sidebar li a{
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    text-decoration: none;
    border-radius: 0.3125vw;
    transition: var(--tran-05);
}

.sidebar.close header .toggle{
    transform: translateY(-50%);
}

.sidebar .menu-bar{
    height: calc(100% - 4.63vh);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

/* sidebar header */
.sidebar header{
    position: relative;
}

.sidebar header .image-text{
    display: flex;
    align-items: center;
}

/* sidebar close */
.sidebar.close{
    width: 4.58vw;
}

.sidebar.close .text{
    opacity: 0;
}

.sidebar.close ~ .home{
    left: 4.58vw;
    width: calc(100% - 4.58vw);
}

/* header */
header .image-text .header-text{
    display: flex;
    flex-direction: column;

}

.header-text .name{
    font-weight: 600;
}

.header-text .profession{
    margin-top: -0.104vw;;
}

/* searchbox */
.search-box input{
    height: 100%;
    width: 100%;
    outline: none;
    border: none;
    border-radius: 0.3125vw;
    font-size: 0.83vw;
    font-weight: 500;
    background: var(--primary-color-light);
    transition: var(--tran-05);
    color: var(--text-color);
}

/* menu */

.menu-bar .mode{
    position: relative;
    border-radius: 0.3125vw;
    background-color: var(--primary-color-light);
}

.menu-bar .mode .dark-light{
    height: 4.63vh;
    width: 3.125vw;
    display: flex;
    align-items: center;
}

.menu-bar .mode i{
    position: absolute;
    transition: var(--tran-05);
}

.menu-bar .mode i.sun{
    opacity: 0;
}

.menu-bar .mode .toggle-switch{
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-width: 3.125vw;
    cursor: pointer;
    border-radius: 0.3125vw;
    background: var(--primary-color-light);
}

/* toggle-switch & switch */

.toggle-switch .switch{
    position: relative;
    height: 2.04vh;
    width: 2.29vw;
    border-radius: 1.3vw;
    background: var(--toggle-color);
}

.switch::before{
    content: '';
    position: absolute;
    height: 1.39vh;
    width: 0.78vw;
    border-radius: 50%;
    top: 50%;
    left: 0.26vw;
    transform: translateY(-50%);
    background: var(--sidebar-color);
    transition: var(--tran-05);
}

/* Pages */

/* Accueil (home) */

.home{
    position: relative;
    height: 100vh;
    left: 13.02vw;
    right: 0;
    width: calc(100% - 13.02vw);
    background: var(--body-color);
}

.home .text{
    font-size: 1.5625vw;
    font-weight: 500;
    color: var(--text-color);
    padding: 0.74vh 2.08vw;
}

.home .text article{
    display: inline-block;
    position: relative;
    margin-top: 5%;
    padding: 2%;
    margin-left: 5%;
    align-content: center;
    justify-content: center;
    border-radius: 6px;
    border: solid 1px;
    height: 100%;
    width: 40%;
    opacity: 1;
    /* float: left; */
}

.home .text article.close{
    transition: var(--tran-05);
    height: 100%;
}

.home .text article .description .afficher_moi{
    position: absolute;
    transform: translateY(50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--toggle-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
    z-index: 100;
    top: 30%;
    right: 10%;
}

.home .text article.close .afficher_moi{
    transform: translateY(50%);
}

.home .text article.close p{
    opacity: 0;
    height: 0;
    transition: var(--tran-05);
}

/* évenement */
.sidebar li a:hover{
    background: var(--primary-color);
}

.sidebar li a:hover .icon, .sidebar li a:hover .text{
    color: var(--sidebar-color);
}

.home .text article:hover{
    cursor: pointer;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Slidebar + Dark  mode</title>
    <link rel="stylesheet" href="style.css">
    <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

                    Lucas DUMONT
                    Etudiant

                            <input type="text" placeholder="Rechercher ...">

                            Accueil

                            CV

                            Projets

                            Loisirs

                            Contact

                            Se connecter

                        Dark Mode

Bienvenue sur mon site

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

```

答:
Have you tried CSS : box-sizing:border-box?

```<code>* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
</code>```

https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Title: CSS animation when border's size change

Body:
I have a little probleme with my website: when I click on one of my boxes, the size of it changes, but without transition, even if I put transitions everywhere in my CSS. Here is my code and screens.
Thanks for your help.
Edit : I add my code in snippet, sry
Basically, my code works well, I juste want the transition when I close a box to be less brutal. If you don't want to check all the code, the variables starting by -tran are times (between 200 and 1000 ms).

first screen
second screen

const   body = document.querySelector("body"),
        sidebar = body.querySelector(".sidebar"),
        toggle = body.querySelector(".toggle"),
        searchBtn = body.querySelector(".search-box"),
        modeSwitch = body.querySelector(".toggle-switch"),
        modeText = body.querySelector(".mode-text"),
        moi = body.querySelector(".article"),
        afficher_moi = body.querySelector(".afficher_moi");

        toggle.addEventListener("click", () =>{
            sidebar.classList.toggle("close");
        });

        searchBtn.addEventListener("click", () =>{
            sidebar.classList.remove("close");
        });

        modeSwitch.addEventListener("click", () =>{
            body.classList.toggle("dark");

            if(body.classList.contains("dark")){
                modeText.innerText = "Light Mode";
            }
            else{
                modeText.innerText = "Dark Mode";
            }
        });

        $(document).ready(function () {
            $(".article1").click(function () {
              $(".article1").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article2").click(function () {
              $(".article2").toggleClass("close");
            });
          });

        $(document).ready(function () {
            $(".article3").click(function () {
              $(".article3").toggleClass("close");
            });
        });

        $(document).ready(function () {
            $(".article4").click(function () {
              $(".article4").toggleClass("close");
            });
        });

/* Importation des polices */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

/* Tout */
*{
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Initialisation des variables au lancement */
:root{
    --body-color: #e4e9f7;
    --sidebar-color: #fff;
    --primary-color: #695cfe;
    --primary-color-light: #f6f5ff;
    --toggle-color: #ddd;
    --text-color: #707070;

    --tran-02: all 0.2s ease;
    --tran-03: all 0.3s ease;
    --tran-04: all 0.4s ease;
    --tran-05: all 0.5s ease;
    --tran-10: all 1s ease;

}

/* Body */
body{
    height: 100vh;
    background: var(--body-color);
    transition: var(--tran-05);
}

body.dark{
    --body-color: #18191a;
    --sidebar-color: #242526;
    --primary-color: #3a3b3c;
    --primary-color-light: #3a3b3c;
    --toggle-color: #fff;
    --text-color: #ccc;
}

body.dark .sidebar header .toggle{
    color: var(--text-color);
}

body.dark .sidebar li a:hover .icon, body.dark .sidebar li a:hover .text{
    color: var(--text-color);
}

body.dark .menu-bar .mode i.sun{
    opacity: 1;
}

body.dark .menu-bar .mode i.moon{
    opacity: 0;
}

body.dark .switch::before{
    left: 1.25vw;
}

/* sidebar */
.sidebar{
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 13vw;
    padding: 0.925vh 0.73vw;
    background: var(--sidebar-color);
    transition: var(--tran-05);
    z-index: 100;
}

.sidebar header .toggle{
    position: absolute;
    top: 50%;
    right: -1.302vw;
    transform: translateY(-50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--sidebar-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
}

.sidebar .text{
    font-size: 0.83vw;
    font-weight: 500;
    color: var(--text-color);
    transition: var(--tran-05);
    white-space: nowrap;
    opacity: 1;
}

.sidebar .image{
    min-width: 3.125vw;
    display: flex;
    align-items: center;
    justify-content: center;
}

.sidebar li{
    height: 4.63vh;
    margin-top: 0.93vh;
    list-style: none;
    display: flex;
    align-items: center;
}

.sidebar li .icon{
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.042vw;
    min-width: 3.125vw;
}

.sidebar li .icon, .sidebar li .text{
    color: var(--text-color);
    transition: var(--tran-05);
}

.sidebar .image-text img{
    width: 2.08vw;
    border-radius: 0.3125vw;
}

.sidebar .search-box{
    background: var(--primary-color-light);
    border-radius: 0.3125vw;
    transition: var(--tran-05)
}

.sidebar .menu{
    margin-top: 3.24vh;
}

.sidebar li a{
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    text-decoration: none;
    border-radius: 0.3125vw;
    transition: var(--tran-05);
}

.sidebar.close header .toggle{
    transform: translateY(-50%);
}

.sidebar .menu-bar{
    height: calc(100% - 4.63vh);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

/* sidebar header */
.sidebar header{
    position: relative;
}

.sidebar header .image-text{
    display: flex;
    align-items: center;
}

/* sidebar close */
.sidebar.close{
    width: 4.58vw;
}

.sidebar.close .text{
    opacity: 0;
}

.sidebar.close ~ .home{
    left: 4.58vw;
    width: calc(100% - 4.58vw);
}

/* header */
header .image-text .header-text{
    display: flex;
    flex-direction: column;

}

.header-text .name{
    font-weight: 600;
}

.header-text .profession{
    margin-top: -0.104vw;;
}

/* searchbox */
.search-box input{
    height: 100%;
    width: 100%;
    outline: none;
    border: none;
    border-radius: 0.3125vw;
    font-size: 0.83vw;
    font-weight: 500;
    background: var(--primary-color-light);
    transition: var(--tran-05);
    color: var(--text-color);
}

/* menu */

.menu-bar .mode{
    position: relative;
    border-radius: 0.3125vw;
    background-color: var(--primary-color-light);
}

.menu-bar .mode .dark-light{
    height: 4.63vh;
    width: 3.125vw;
    display: flex;
    align-items: center;
}

.menu-bar .mode i{
    position: absolute;
    transition: var(--tran-05);
}

.menu-bar .mode i.sun{
    opacity: 0;
}

.menu-bar .mode .toggle-switch{
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-width: 3.125vw;
    cursor: pointer;
    border-radius: 0.3125vw;
    background: var(--primary-color-light);
}

/* toggle-switch & switch */

.toggle-switch .switch{
    position: relative;
    height: 2.04vh;
    width: 2.29vw;
    border-radius: 1.3vw;
    background: var(--toggle-color);
}

.switch::before{
    content: '';
    position: absolute;
    height: 1.39vh;
    width: 0.78vw;
    border-radius: 50%;
    top: 50%;
    left: 0.26vw;
    transform: translateY(-50%);
    background: var(--sidebar-color);
    transition: var(--tran-05);
}

/* Pages */

/* Accueil (home) */

.home{
    position: relative;
    height: 100vh;
    left: 13.02vw;
    right: 0;
    width: calc(100% - 13.02vw);
    background: var(--body-color);
}

.home .text{
    font-size: 1.5625vw;
    font-weight: 500;
    color: var(--text-color);
    padding: 0.74vh 2.08vw;
}

.home .text article{
    display: inline-block;
    position: relative;
    margin-top: 5%;
    padding: 2%;
    margin-left: 5%;
    align-content: center;
    justify-content: center;
    border-radius: 6px;
    border: solid 1px;
    height: 100%;
    width: 40%;
    opacity: 1;
    /* float: left; */
}

.home .text article.close{
    transition: var(--tran-05);
    height: 100%;
}

.home .text article .description .afficher_moi{
    position: absolute;
    transform: translateY(50%) rotate(180deg);
    height: 1.302vw;
    width: 1.302vw;
    background: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    color: var(--toggle-color);
    font-size: 1.145vw;
    transition: var(--tran-05);
    z-index: 100;
    top: 30%;
    right: 10%;
}

.home .text article.close .afficher_moi{
    transform: translateY(50%);
}

.home .text article.close p{
    opacity: 0;
    height: 0;
    transition: var(--tran-05);
}

/* évenement */
.sidebar li a:hover{
    background: var(--primary-color);
}

.sidebar li a:hover .icon, .sidebar li a:hover .text{
    color: var(--sidebar-color);
}

.home .text article:hover{
    cursor: pointer;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Slidebar + Dark  mode</title>
    <link rel="stylesheet" href="style.css">
    <link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>

                    Lucas DUMONT
                    Etudiant

                            <input type="text" placeholder="Rechercher ...">

                            Accueil

                            CV

                            Projets

                            Loisirs

                            Contact

                            Se connecter

                        Dark Mode

Bienvenue sur mon site

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

A propos de moi

                    Insérer description de moi

Body:
Have you tried CSS : box-sizing:border-box?

* {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

https://www.w3schools.com/cssref/css3_pr_box-sizing.asp


问:
Building a subset of boost libraries
I'm trying to build only a subset of boost libraries. For example, I have this code:

test.cpp:

```<code>#include <boost/thread.hpp>

int main (){
    return 0;
}
</code>```

I then do

```<code>./bcp --scan test.cpp ~/dev/boost_compact/
</code>```

So the dependencies files are copied to ~/dev/boost_compact/boost.

Then, following this answer, I copy all files at the root of a regular boost and also the tools directory and run

```<code>./bootstrap
./bjam
./bjam install
</code>```

This does copy all the headers to a destination directory, but it does not build/copy the libraries. This same set of actions does work in the full boost. What am I doing wrong?

答:
Solved the problem. The reason the libraries were not being copied was that I was using the wrong boost directory, that is

```<code>./bcp --scan --boost=<path to boost build directory> test.cpp ~/dev/boost_compact/
</code>```

when I should be using

```<code>./bcp --scan --boost=<path to boost source directory> test.cpp ~/dev/boost_compact/
</code>```

If now you run

```<code>./bootstrap
./bjam
./bjam install
</code>```

The libraries will be build.

Title: Building a subset of boost libraries

Body:
I'm trying to build only a subset of boost libraries. For example, I have this code:

test.cpp:

#include <boost/thread.hpp>

int main (){
    return 0;
}

I then do

./bcp --scan test.cpp ~/dev/boost_compact/

So the dependencies files are copied to ~/dev/boost_compact/boost.

Then, following this answer, I copy all files at the root of a regular boost and also the tools directory and run

./bootstrap
./bjam
./bjam install

This does copy all the headers to a destination directory, but it does not build/copy the libraries. This same set of actions does work in the full boost. What am I doing wrong?

Body:
Solved the problem. The reason the libraries were not being copied was that I was using the wrong boost directory, that is

./bcp --scan --boost=<path to boost build directory> test.cpp ~/dev/boost_compact/

when I should be using

./bcp --scan --boost=<path to boost source directory> test.cpp ~/dev/boost_compact/

If now you run

./bootstrap
./bjam
./bjam install

The libraries will be build.


问:
Live Server Extension in VS Code is not working in WSL
I have been working with visual studio a long of time ago in Windows without any problems.
I installed WSL in my PC, all perfect.

But now I migrated one of my webpages directory to the WSL root
\wsl$\Ubuntu\home\user\webPage

And when I click on "Live Server" extension, it loads propertly in:
http://127.0.0.1:5500/index.html

But when I make a change and save, is not working

Do I have to change something else? Of course all the extensions are installed, seems to be the same

答:
Modify this settings in your VS Code extension:</p>
```<code>"liveServer.settings.https": {
    "passphrase": "true",
    "key": "true",
    "cert": "true",
    "enable": 1
},
</code>```

Body:
Modify this settings in your VS Code extension:

"liveServer.settings.https": {
    "passphrase": "true",
    "key": "true",
    "cert": "true",
    "enable": 1
},


问:
How to sort the nested object data in react-native
```<code>    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }
</code>```

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

答:
Sort by age in years oldest first</p>
```<code>// use slice() to copy the array
    var byAge = array.slice(0);
    byAge.sort(function(a,b) {
        return a.age_in_years - b.age_in_years ;
    });
</code>```

Body:
    {
    "lion":{
    "age_in_years":"10",
    "name":"king",
    "country":"africa"
    },

    "elephant":{
    "age_in_years":"15",
    "name":"hero",
    "country":"usa"
    },

    "racoon":{
    "age_in_years":"5",
    "name":"thanos",
    "country":"syria"
    },
   }

This is the data I'm getting through a web socket in react-native. I want to sort it in ascending order based on the "age_in_years". So the oldest animal's data should be shown at top and  the youngest data at the last.

Body:
Sort by age in years oldest first

// use slice() to copy the array
    var byAge = array.slice(0);
    byAge.sort(function(a,b) {
        return a.age_in_years - b.age_in_years ;
    });


问:
How to transform a string into a list of char and int using a list comprehension in Python
Given the following string:

```<code>"[10,20]"
</code>```

I want to create the following list using a list comprehension in Python:

```<code>['[', 10, ',', 20, ']']
</code>```

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

答:
You could also use reduce from functools:

```<code>from functools import reduce
def fun(x, y):
    if isinstance(x[-1], str) and x[-1].isdigit():
        x[-1] = x[-1] + y if y.isdigit()  else int(x[-1])
    else:
        x += [y]
    return x

reduce(fun, '[10,[20,30]]', [''])[1:]
Out[]: ['[', 10, '[', 20, 30, ']']
</code>```

Another approach may be to use recursion:

```<code>def fun_recurse(y, x=None):
    if x is None:
        x = ['']
    if len(y) == 1:
        return x[1:] + [y]
    if isinstance(x[-1], str) and x[-1].isdigit():
       x[-1] = x[-1] + y[0] if y[0].isdigit() else int(x[-1])
       return fun_recurse(y[1:], x)
    else:
        return fun_recurse(y[1:], x + [y[0]])

fun_recurse('[10,[20,30]]')
Out[]: ['[', 10, '[', 20, 30, ']']
</code>```

Body:
Given the following string:

"[10,20]"

I want to create the following list using a list comprehension in Python:

['[', 10, ',', 20, ']']

Being 10 and 20 integers and the rest of the elements in the list chars.

I assume that I would need a to use something similar to what itertools.groupby(iterable, key=None) provides:

Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the iterable
needs to already be sorted on the same key function.

However Python's group by returns an iterator with consecutive keys and groups. In my case the keys would change so I guess I'd need a similar iterator that returns the groups based on a filter. Any ideas?

Body:
You could also use reduce from functools:

from functools import reduce
def fun(x, y):
    if isinstance(x[-1], str) and x[-1].isdigit():
        x[-1] = x[-1] + y if y.isdigit()  else int(x[-1])
    else:
        x += [y]
    return x

reduce(fun, '[10,[20,30]]', [''])[1:]
Out[]: ['[', 10, '[', 20, 30, ']']

Another approach may be to use recursion:

def fun_recurse(y, x=None):
    if x is None:
        x = ['']
    if len(y) == 1:
        return x[1:] + [y]
    if isinstance(x[-1], str) and x[-1].isdigit():
       x[-1] = x[-1] + y[0] if y[0].isdigit() else int(x[-1])
       return fun_recurse(y[1:], x)
    else:
        return fun_recurse(y[1:], x + [y[0]])

fun_recurse('[10,[20,30]]')
Out[]: ['[', 10, '[', 20, 30, ']']


问:
Show highlighted image in UITableViewCell
I have set an image and a background image to a UITableViewCell.
But when I click on it, it show the standard blue high-lightening and not mine.

Do you know how I can change this mecanism ?

Thanks, Niels

答: You just have to set the two UITableViewCell property backgroundView and selectedBackgoundView. iOS will do the rest.</p>


问:
Singly Linked List suppose to print (12, 7) but instead prints (127, )
I am trying to write a program that takes an integer and inserts it into the second position in the linked list, but when I run my program it prints out (127, ) when I want it to print out (12, 7). I know it is probably an easy fix, but I am unsure of how to fix this small error. I have tried switching words around like head and tail and next, but nothing I do seems to work. Any input would help a ton!

```<code>public class IntSinglyLinkedList {

  private static class Node {

    private Integer element;

    private Node next;

    public Node(Integer e, Node n) {
      element = e;
      next = n;
    }

  private Node head = null;

  private Node tail = null;

  private int size = 0;

  public IntSinglyLinkedList() { }

  public int size() { return size; }

    public void addSecond(Integer e) {
    if(head == null)
      return;
    Node Final = new Node(e, head);
    Final.next = head.next;
    head.next = Final;
  }
    public static void main(String[] args) {
      IntSinglyLinkedList sl = new IntSinglyLinkedList();
      sl.addFirst(12);
      sl.addSecond(7);
      System.out.println(sl.toString());
    }
}

</code>```

My toString also looks like this if this is any help!

```<code>public String toString() {
    StringBuilder sb = new StringBuilder("(");
    Node walk = head;
    while (walk != null) {
      sb.append(walk.getElement());
      if (walk != tail)
        sb.append(", ");
      walk = walk.getNext();
    }
    sb.append(")");
    return sb.toString();
  }
</code>```

my addFirst method

```<code>public void addFirst(Integer e) {
    head = new Node(e, head);
    if (size == 0)
      tail = head;
    size++;
  }
</code>```

答:
You never update your tail element after your addFirst, so the , will not be printed after the first element.

You have to add tail = Final; in your addSecond method to make this particular example to print correctly.

That answers the specific question of why you get (127,) printed instead of (12, 7) in this particular case.

However, it is hard to see where you are going with this. Are you planning to write a new method for every element you want to add? It would make more sense to have a general add:

```<code>public Node add(final Integer i) {
  final var node = new Node(i, null);
  if (size == 0) {
    head = node;
  } else {
    tail.next = node;
  }
  tail = node;
  size++;
  return node;
}
</code>```

Body:
I am trying to write a program that takes an integer and inserts it into the second position in the linked list, but when I run my program it prints out (127, ) when I want it to print out (12, 7). I know it is probably an easy fix, but I am unsure of how to fix this small error. I have tried switching words around like head and tail and next, but nothing I do seems to work. Any input would help a ton!

public class IntSinglyLinkedList {

  private static class Node {

    private Integer element;

    private Node next;

    public Node(Integer e, Node n) {
      element = e;
      next = n;
    }

  private Node head = null;

  private Node tail = null;

  private int size = 0;

  public IntSinglyLinkedList() { }

  public int size() { return size; }

    public void addSecond(Integer e) {
    if(head == null)
      return;
    Node Final = new Node(e, head);
    Final.next = head.next;
    head.next = Final;
  }
    public static void main(String[] args) {
      IntSinglyLinkedList sl = new IntSinglyLinkedList();
      sl.addFirst(12);
      sl.addSecond(7);
      System.out.println(sl.toString());
    }
}

My toString also looks like this if this is any help!

public String toString() {
    StringBuilder sb = new StringBuilder("(");
    Node walk = head;
    while (walk != null) {
      sb.append(walk.getElement());
      if (walk != tail)
        sb.append(", ");
      walk = walk.getNext();
    }
    sb.append(")");
    return sb.toString();
  }

my addFirst method

public void addFirst(Integer e) {
    head = new Node(e, head);
    if (size == 0)
      tail = head;
    size++;
  }

Body:
You never update your tail element after your addFirst, so the , will not be printed after the first element.

You have to add tail = Final; in your addSecond method to make this particular example to print correctly.

That answers the specific question of why you get (127,) printed instead of (12, 7) in this particular case.

However, it is hard to see where you are going with this. Are you planning to write a new method for every element you want to add? It would make more sense to have a general add:

public Node add(final Integer i) {
  final var node = new Node(i, null);
  if (size == 0) {
    head = node;
  } else {
    tail.next = node;
  }
  tail = node;
  size++;
  return node;
}


问:
Why would MySQL execute return None?
I am trying to query on a local MySQL database using Python's (3.4) MySQL module with the following code:

```<code>class databases():

  def externaldatabase(self):

  try:
    c = mysql.connector.connect(host="127.0.0.1", user="user",
                                password="password", database="database")
     if c.is_connected():
           c.autocommit = True
      return(c)
    except:
         return(None)
    d = databases().externaldatabase()
    c = d.cursor()
    r = c.execute('''select * from tbl_wiki''')
    print(r)
> Returns: None
</code>```

As far as I can tell, the connection is successful, the database is composed of several rows but the query always returns the none type.

What instances does the MySQL execute function return None?

答:
For my case, I return the cursor as I need the value to return a string specifically, for instance, I return the password (string) for inspect whether user used the same password twice. Here's how I did it (In my case):

def getUserPassword(metadata):
    cursorObject.execute("SELECT password FROM users WHERE email=%s AND password=%s LIMIT 1", (metadata['email'], metadata['password']))
    return cursorObject.fetchall()[0]['password']
```
<p>Which I can  easily call from another <code>class</code> by calling the method:</p>
<pre class="lang-py prettyprint-override"><code>assert getUserPassword({"email" : "email", "password" : "oldpass"}) is not None
</code>```

And which the getUserPassword itself is returning a string

Title: Why would MySQL execute return None?

Body:
I am trying to query on a local MySQL database using Python's (3.4) MySQL module with the following code:

class databases():

  def externaldatabase(self):

  try:
    c = mysql.connector.connect(host="127.0.0.1", user="user",
                                password="password", database="database")
     if c.is_connected():
           c.autocommit = True
      return(c)
    except:
         return(None)
    d = databases().externaldatabase()
    c = d.cursor()
    r = c.execute('''select * from tbl_wiki''')
    print(r)
> Returns: None

As far as I can tell, the connection is successful, the database is composed of several rows but the query always returns the none type.

What instances does the MySQL execute function return None?

Body:
For my case, I return the cursor as I need the value to return a string specifically, for instance, I return the password (string) for inspect whether user used the same password twice. Here's how I did it (In my case):

def getUserPassword(metadata):
    cursorObject.execute("SELECT password FROM users WHERE email=%s AND password=%s LIMIT 1", (metadata['email'], metadata['password']))
    return cursorObject.fetchall()[0]['password']

Which I can  easily call from another class by calling the method:

assert getUserPassword({"email" : "email", "password" : "oldpass"}) is not None

And which the getUserPassword itself is returning a string


问:
Doing import ray breaks my custom logging formatter
I am using ray inside modin to accelerate reading some huge datasets.

In the whole project there is a custom logging formatter. From the reading I have done i think ray's log format (you can find it under ray.ray_constants called LOGGER_FORMAT) overrides my format.

So when i do import ray my logging breaks.

reproducible example

```<code>import os
import logging
import logging.config

def initialise_logger(config):
    """
    Args:
        section (str): the log_configuration section for the service.

    """
    logging.config.fileConfig(fname=config, disable_existing_loggers=False)
    old_factory = logging.getLogRecordFactory()

    def my_record_factory(*args, **kwargs):

        record = old_factory(*args, **kwargs)
        record.project = "alex"
        record.microservice = "alex"
        record.hostname = "alex"
        record.local_ip = "alex"

        # all Mesos containers in production have this environment variable.
        # if it is not present, then we are not in production
       record.mesos_task_id = "alex"

    return record

    logging.setLogRecordFactory(my_record_factory)

def main():
    text = """[loggers]
    keys=root,test_logger,Test_Class

    [handlers]
    keys=consoleHandler

    [formatters]
    keys=consoleFormatter

    [logger_root]
    level=INFO
    handlers=consoleHandler

    [logger_test_logger]
    level=INFO
    handlers=consoleHandler
    qualname=test_logger
    propagate=0

    [logger_Test_Class]
    level=INFO
    handlers=consoleHandler
    qualname=Test_Class
    propagate=0

    [handler_consoleHandler]
    class=StreamHandler
    level=INFO
    formatter=consoleFormatter
    args=(sys.stdout,)

    [formatter_consoleFormatter]
    format = %(asctime)s.%(msecs)03d %(project)s %(microservice)s %(levelname)s %(hostname)s %(local_ip)s %(name)s %(filename)s %(lineno)d %(funcName)s %(module)s %(processName)s %(process)d %(threadName)s %(thread)d  %(message)s
    datefmt= %Y-%m-%d %H:%M:%S
    """

    with open(os.path.join(os.getcwd(), "config.ini"), "w") as conffile:
        conffile.write(text)

    initialise_logger(config="config.ini")

    logging.info("RAY NOT IMPORTED")

    import ray

    logging.info("RAY IMPORTED")

if __name__ == '__main__':
    main()
</code>```

答: Instead of using the global logging module, try instantiating a logger (e.g. logger = logging.getLogger(__name__)) and then set the formatters and handlers for that logger instance. That way, even if a 3rd party library is messing with the base configuration, it shouldn't mess with your logger instance.

Body:
I am using ray inside modin to accelerate reading some huge datasets.

In the whole project there is a custom logging formatter. From the reading I have done i think ray's log format (you can find it under ray.ray_constants called LOGGER_FORMAT) overrides my format.

So when i do import ray my logging breaks.

reproducible example

import os
import logging
import logging.config

def initialise_logger(config):
    """
    Args:
        section (str): the log_configuration section for the service.

    """
    logging.config.fileConfig(fname=config, disable_existing_loggers=False)
    old_factory = logging.getLogRecordFactory()

    def my_record_factory(*args, **kwargs):

        record = old_factory(*args, **kwargs)
        record.project = "alex"
        record.microservice = "alex"
        record.hostname = "alex"
        record.local_ip = "alex"

        # all Mesos containers in production have this environment variable.
        # if it is not present, then we are not in production
       record.mesos_task_id = "alex"

    return record

    logging.setLogRecordFactory(my_record_factory)

def main():
    text = """[loggers]
    keys=root,test_logger,Test_Class

    [handlers]
    keys=consoleHandler

    [formatters]
    keys=consoleFormatter

    [logger_root]
    level=INFO
    handlers=consoleHandler

    [logger_test_logger]
    level=INFO
    handlers=consoleHandler
    qualname=test_logger
    propagate=0

    [logger_Test_Class]
    level=INFO
    handlers=consoleHandler
    qualname=Test_Class
    propagate=0

    [handler_consoleHandler]
    class=StreamHandler
    level=INFO
    formatter=consoleFormatter
    args=(sys.stdout,)

    [formatter_consoleFormatter]
    format = %(asctime)s.%(msecs)03d %(project)s %(microservice)s %(levelname)s %(hostname)s %(local_ip)s %(name)s %(filename)s %(lineno)d %(funcName)s %(module)s %(processName)s %(process)d %(threadName)s %(thread)d  %(message)s
    datefmt= %Y-%m-%d %H:%M:%S
    """

    with open(os.path.join(os.getcwd(), "config.ini"), "w") as conffile:
        conffile.write(text)

    initialise_logger(config="config.ini")

    logging.info("RAY NOT IMPORTED")

    import ray

    logging.info("RAY IMPORTED")

if __name__ == '__main__':
    main()


问:
How to make some fields optional in Django ORM
I've coded a function that signs up a user. In my sterilizer the name field is optional but whenever I try to create a user without giving a name, I just face KeyError: 'name'.
what should I do to make this code work?

def post(self, request):
        if request.user.is_anonymous:
            data = RegisterationSerializer(data=request.data)
            if data.is_valid():
                User.objects.create_user(email=data.validated_data['email'], username=data.validated_data['username'],
                 password=data.validated_data['password'], name=data.validated_data['name'])
                return Response({
                "message": f'{data.validated_data["email"]} account was created successfully'
                }, status=status.HTTP_201_CREATED)

            else:
                return Response(data.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({
                "message": "You already authorized"
            }, status=status.HTTP_400_BAD_REQUEST)
```

答:
The problem is you are trying to access to name in your validated_data. But there is no name.

you can do something like User.objects.create_user(**data.validated_data)
or you can do

User.objects.create_user(
        email=data.validated_data['email'],
        username=data.validated_data['username'],
        password=data.validated_data['password'],
        name=data.validated_data['name'] if 'name' in data.validated_data else '') # or None
```


问:
Parse XML in Mootools
There doesn't seem to be any useful documentation out there about parsing XML in Mootools. Either it's so stupidly easy nobody could be bothered to mention it, or it's so fiendishly difficult everybody's given up trying. Does anyone have any simple cross browser method for parsing XML with Mootools?

Here's my little XML file data.xml:

```<code><?xml version="1.0"?>
<suggestions>
   <suggestion winning="Y">
      <copy><![CDATA[Draw straws to see who wins]]>
      </copy>
      <person><![CDATA[Sue]]>
      </person>
      <location><![CDATA[London]]>
      </location>
   </suggestion>
   <suggestion winning="N">
      <copy><![CDATA[Race your friends round the meeting room]]>
      </copy>
      <person><![CDATA[Jack]]>
      </person>
      <location><![CDATA[Lancaster]]>
      </location>
   </suggestion>
</suggestions>
</code>```

And this is my JS:

```<code>window.addEvent('domready', function(){

    var outputHTML = '';

    var req = new Request({
        url: 'data.xml',
        method: 'get',
        onSuccess: function(responseText, responseXML) {
            if(typeOf(responseXML) != 'document'){
                responseXML = responseXML.documentElement;
            }
            var suggestions = responseXML.getElements('suggestion');
            suggestions.each(function(item) {
                    outputHTML += '<p>';
                    outputHTML += item.getElement('copy').get('text') + '<br/>';
                    outputHTML += '<b>' + item.getElement('person').get('text') + '</b>: ';
                    outputHTML += item.getElement('location').get('text')  + '<br/>';
                    if (item.get('winning') == 'Y') {
                        outputHTML += ' <b>Won!</b>';
                    }
                    outputHTML += '</p>';
            });
            $('output').set('html', outputHTML);
        }
    }).send();

});
</code>```

I found I had to do the responseXML = responseXML.documentElement bit to make it work in Chrome. This JS works OK in Chrome and FF, but IE complains "Object doesn't support this property or method" for line 16, where I'm trying to run getElements('suggestion') on responseXML.

Can any kindly expert restore my faith in the mystical powers of Mootools?

Cheers
Fred

答:
In MooTools Forge there is a plugin for converting XML to a JavaScript object:

http://mootools.net/forge/p/xml2js_converter

Title: Parse XML in Mootools

Body:
There doesn't seem to be any useful documentation out there about parsing XML in Mootools. Either it's so stupidly easy nobody could be bothered to mention it, or it's so fiendishly difficult everybody's given up trying. Does anyone have any simple cross browser method for parsing XML with Mootools?

Here's my little XML file data.xml:

<?xml version="1.0"?>
<suggestions>
   <suggestion winning="Y">
      <copy><![CDATA[Draw straws to see who wins]]>
      </copy>
      <person><![CDATA[Sue]]>
      </person>
      <location><![CDATA[London]]>
      </location>
   </suggestion>
   <suggestion winning="N">
      <copy><![CDATA[Race your friends round the meeting room]]>
      </copy>
      <person><![CDATA[Jack]]>
      </person>
      <location><![CDATA[Lancaster]]>
      </location>
   </suggestion>
</suggestions>

And this is my JS:

window.addEvent('domready', function(){

    var outputHTML = '';

    var req = new Request({
        url: 'data.xml',
        method: 'get',
        onSuccess: function(responseText, responseXML) {
            if(typeOf(responseXML) != 'document'){
                responseXML = responseXML.documentElement;
            }
            var suggestions = responseXML.getElements('suggestion');
            suggestions.each(function(item) {
                    outputHTML += '
';
                    outputHTML += item.getElement('copy').get('text') + '
';
                    outputHTML += '' + item.getElement('person').get('text') + ': ';
                    outputHTML += item.getElement('location').get('text')  + '
';
                    if (item.get('winning') == 'Y') {
                        outputHTML += ' Won!';
                    }
                    outputHTML += '
';
            });
            $('output').set('html', outputHTML);
        }
    }).send();

});

I found I had to do the responseXML = responseXML.documentElement bit to make it work in Chrome. This JS works OK in Chrome and FF, but IE complains "Object doesn't support this property or method" for line 16, where I'm trying to run getElements('suggestion') on responseXML.

Can any kindly expert restore my faith in the mystical powers of Mootools?

Cheers
Fred


问:
Custom code containers for google cloud-ml for inference
I am aware that it is possible to deploy custom containers for training jobs on google cloud and I have been able to get the same running using command.

```<code>gcloud ai-platform jobs submit training infer name --region some_region --master-image-uri=path/to/docker/image --config config.yaml
</code>```

The training job was completed successfully and the model was successfully obtained, Now I want to use this model for inference, but the issue is a part of my code has system level dependencies, so I have to make some modification into the architecture in order to get it running all the time. This was the reason to have a custom container for the training job in the first place.

The documentation is only available for the training part and the inference part, (if possible) with custom containers has not been explored to the best of my knowledge.

The training part documentation is available on this link

My question is, is it possible to deploy custom containers for inference purposes on google cloud-ml?

答:
This response refers to using Vertex AI Prediction, the newest platform for ML on GCP.

Suppose you wrote the model artifacts out to cloud storage from your training job.

The next step is to create the custom container and push to a registry, by following something like what is described here:

https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements

This section describes how you pass the model artifact directory to the custom container to be used for interence:

https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#artifacts

You will also need to create an endpoint in order to deploy the model:

https://cloud.google.com/vertex-ai/docs/predictions/deploy-model-api#aiplatform_deploy_model_custom_trained_model_sample-gcloud

Finally, you would use gcloud ai endpoints deploy-model ... to deploy the model to the endpoint:

https://cloud.google.com/sdk/gcloud/reference/ai/endpoints/deploy-model

Body:
I am aware that it is possible to deploy custom containers for training jobs on google cloud and I have been able to get the same running using command.

gcloud ai-platform jobs submit training infer name --region some_region --master-image-uri=path/to/docker/image --config config.yaml

The training job was completed successfully and the model was successfully obtained, Now I want to use this model for inference, but the issue is a part of my code has system level dependencies, so I have to make some modification into the architecture in order to get it running all the time. This was the reason to have a custom container for the training job in the first place.

The documentation is only available for the training part and the inference part, (if possible) with custom containers has not been explored to the best of my knowledge.

The training part documentation is available on this link

My question is, is it possible to deploy custom containers for inference purposes on google cloud-ml?