问:
NGINX container as a proxy for other containers
I am trying to run of containers on my UBUNTU server, these containers are:

DNS servers with bind9.

NTP server with cturra/ntp.

NGINX for reverse proxy => reverse proxy for DNS and NTP

I have these containers in the same yaml file:

```<code>version: '3'
services:
  reverse-proxy-engine:
    image: nginx
    container_name: reverse-proxy-engine
    volumes:
      - ~/core/reverse-proxy/:/usr/share/nginx/
    ports:
      - "80:80"
      - "443:443"
      - "53:53"
      - "123:123/udp"
    depends_on:
      - "DNS-SRV"
      - "ntp"
  DNS-SRV:
    container_name: DNS-SRV
    image: ubuntu/bind9
    user: root
    environment:
      - TZ=UTC
    volumes:
      - ~/core/bind9/:/etc/bind/
  ntp:
    image: cturra/ntp
    container_name: ntp
    restart: always
    read_only: true
    tmpfs:
      - /etc/chrony:rw,mode=1750
      - /run/chrony:rw,mode=1750
      - /var/lib/chrony:rw,mode=1750
    environment:
      - NTP_SERVERS=time.cloudflare.com
      - LOG_LEVEL=0
</code>```

After running this yaml file, the containers are created and I see the ports mapped correctly:

```<code>admin@main-srv:~/core/yamls$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS                                                                                NAMES
4720bae2a44c        nginx               "/docker-entrypoint.…"   5 seconds ago       Up 4 seconds                      0.0.0.0:53->53/tcp, 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:123->123/udp   reverse-proxy-engine
1681814f651e        cturra/ntp          "/bin/sh /opt/startu…"   6 seconds ago       Up 5 seconds (health: starting)   123/udp                                                                              ntp
dde2f9094b45        ubuntu/bind9        "docker-entrypoint.sh"   6 seconds ago       Up 5 seconds                      53/tcp                                                                               DNS-SRV
</code>```

I am able to access the nginx webpage on the browser using port 80 with <UBUNTU_SERVER_IP:80>, but I'm unable to use this same IP to resolve DNS or NTP on the same network, but within the containers network, it's working.

So I think that NGINX ports are exposed to the UBUNTU server, but the DNS and NTP ports are not exposed to NGINX, would that be correct? What am I missing?

Below is my NginX configuration file:

```<code>events {
  worker_connections 1024;
}

stream {

    upstream dns_servers {
        server DNS-SRV:53;
    }

    upstream ntp_server {
      server ntp:123;
    }

    server {
        listen 53 udp;
        listen 53; #tcp
        proxy_pass dns_servers;
        error_log  /var/log/nginx/dns.log info;
        proxy_responses 1;
        proxy_timeout   1s;
    }

    server {
      listen 123 udp;
      listen 123; #tcp

      proxy_pass ntp_server;
      error_log  /var/log/nginx/ntp.log info;
      proxy_responses 1;
      proxy_timeout   1s;
    }
}
</code>```

So far it seems logical to me, any ideas?

答:
I think that's because you don't set hostname for bind and ntp container, I use below configuration and get it working

```<code>version: '3'
services:
  reverse-proxy-engine:
    image: nginx
    container_name: reverse-proxy-engine
    volumes:
      - ~/core/reverse-proxy/:/usr/share/nginx/
      - $PWD/nginx.conf:/etc/nginx/nginx.conf
    ports:
      - "80:80"
      - "443:443"
      - "53:53"
      - "123:123/udp"
    depends_on:
      - "DNS-SRV"
      - "ntp"
  DNS-SRV:
    container_name: DNS-SRV
    hostname: DNS-SRV
    image: ubuntu/bind9
    user: root
    environment:
      - TZ=UTC
    volumes:
      - ~/core/bind9/:/etc/bind/
  ntp:
    image: cturra/ntp
    container_name: ntp
    hostname: ntp
    restart: always
    read_only: true
    tmpfs:
      - /etc/chrony:rw,mode=1750
      - /run/chrony:rw,mode=1750
      - /var/lib/chrony:rw,mode=1750
    environment:
      - NTP_SERVERS=time.cloudflare.com
      - LOG_LEVEL=0
</code>```

In above configuration I add hostname for bind and ntp container, also i mount nginx configuration and replace the default configuration.

Below nginx.conf configuration

```<code>user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

stream {

    upstream dns_servers {
        server DNS-SRV:53;
    }

    upstream ntp_server {
      server ntp:123;
    }

    server {
        listen 53 udp;
        listen 53; #tcp
        proxy_pass dns_servers;
        error_log  /var/log/nginx/dns.log info;
        proxy_responses 1;
        proxy_timeout   1s;
    }

    server {
      listen 123 udp;
      listen 123; #tcp

      proxy_pass ntp_server;
      error_log  /var/log/nginx/ntp.log info;
      proxy_responses 1;
      proxy_timeout   1s;
    }
}
</code>```

Note: Make sure the binding port you use 80, 443, 53, 123 not used by other application.

Body:
I am trying to run of containers on my UBUNTU server, these containers are:

DNS servers with bind9.

NTP server with cturra/ntp.

NGINX for reverse proxy => reverse proxy for DNS and NTP

I have these containers in the same yaml file:

version: '3'
services:
  reverse-proxy-engine:
    image: nginx
    container_name: reverse-proxy-engine
    volumes:
      - ~/core/reverse-proxy/:/usr/share/nginx/
    ports:
      - "80:80"
      - "443:443"
      - "53:53"
      - "123:123/udp"
    depends_on:
      - "DNS-SRV"
      - "ntp"
  DNS-SRV:
    container_name: DNS-SRV
    image: ubuntu/bind9
    user: root
    environment:
      - TZ=UTC
    volumes:
      - ~/core/bind9/:/etc/bind/
  ntp:
    image: cturra/ntp
    container_name: ntp
    restart: always
    read_only: true
    tmpfs:
      - /etc/chrony:rw,mode=1750
      - /run/chrony:rw,mode=1750
      - /var/lib/chrony:rw,mode=1750
    environment:
      - NTP_SERVERS=time.cloudflare.com
      - LOG_LEVEL=0

After running this yaml file, the containers are created and I see the ports mapped correctly:

admin@main-srv:~/core/yamls$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                            PORTS                                                                                NAMES
4720bae2a44c        nginx               "/docker-entrypoint.…"   5 seconds ago       Up 4 seconds                      0.0.0.0:53->53/tcp, 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:123->123/udp   reverse-proxy-engine
1681814f651e        cturra/ntp          "/bin/sh /opt/startu…"   6 seconds ago       Up 5 seconds (health: starting)   123/udp                                                                              ntp
dde2f9094b45        ubuntu/bind9        "docker-entrypoint.sh"   6 seconds ago       Up 5 seconds                      53/tcp                                                                               DNS-SRV

I am able to access the nginx webpage on the browser using port 80 with <UBUNTU_SERVER_IP:80>, but I'm unable to use this same IP to resolve DNS or NTP on the same network, but within the containers network, it's working.

So I think that NGINX ports are exposed to the UBUNTU server, but the DNS and NTP ports are not exposed to NGINX, would that be correct? What am I missing?

Below is my NginX configuration file:

events {
  worker_connections 1024;
}

stream {

    upstream dns_servers {
        server DNS-SRV:53;
    }

    upstream ntp_server {
      server ntp:123;
    }

    server {
        listen 53 udp;
        listen 53; #tcp
        proxy_pass dns_servers;
        error_log  /var/log/nginx/dns.log info;
        proxy_responses 1;
        proxy_timeout   1s;
    }

    server {
      listen 123 udp;
      listen 123; #tcp

      proxy_pass ntp_server;
      error_log  /var/log/nginx/ntp.log info;
      proxy_responses 1;
      proxy_timeout   1s;
    }
}

So far it seems logical to me, any ideas?

Body:
I think that's because you don't set hostname for bind and ntp container, I use below configuration and get it working

version: '3'
services:
  reverse-proxy-engine:
    image: nginx
    container_name: reverse-proxy-engine
    volumes:
      - ~/core/reverse-proxy/:/usr/share/nginx/
      - $PWD/nginx.conf:/etc/nginx/nginx.conf
    ports:
      - "80:80"
      - "443:443"
      - "53:53"
      - "123:123/udp"
    depends_on:
      - "DNS-SRV"
      - "ntp"
  DNS-SRV:
    container_name: DNS-SRV
    hostname: DNS-SRV
    image: ubuntu/bind9
    user: root
    environment:
      - TZ=UTC
    volumes:
      - ~/core/bind9/:/etc/bind/
  ntp:
    image: cturra/ntp
    container_name: ntp
    hostname: ntp
    restart: always
    read_only: true
    tmpfs:
      - /etc/chrony:rw,mode=1750
      - /run/chrony:rw,mode=1750
      - /var/lib/chrony:rw,mode=1750
    environment:
      - NTP_SERVERS=time.cloudflare.com
      - LOG_LEVEL=0

In above configuration I add hostname for bind and ntp container, also i mount nginx configuration and replace the default configuration.

Below nginx.conf configuration

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

stream {

    upstream dns_servers {
        server DNS-SRV:53;
    }

    upstream ntp_server {
      server ntp:123;
    }

    server {
        listen 53 udp;
        listen 53; #tcp
        proxy_pass dns_servers;
        error_log  /var/log/nginx/dns.log info;
        proxy_responses 1;
        proxy_timeout   1s;
    }

    server {
      listen 123 udp;
      listen 123; #tcp

      proxy_pass ntp_server;
      error_log  /var/log/nginx/ntp.log info;
      proxy_responses 1;
      proxy_timeout   1s;
    }
}

Note: Make sure the binding port you use 80, 443, 53, 123 not used by other application.


来源: stackexchange

问:
JavaScript Array: Order Nested Object by Key
I have the following nested object. I would like to iterate through every item (latest.sentTime) and then sort the object itself by "sentTime". So that the most recent message is on top. How can I achieve this?

In the following example, "0" and "1" need to be swapped basically, since "1" has a more recent "sentTime".

答:
Using Array#map, iterate over the array to get latest.sentTime

Using Array#sort and Date, sort the items

const arr = [
  { latest: { sentTime: '2022-02-05T19:15:32.000Z' } },
  { latest: { sentTime: '2022-02-06T22:12:00.000Z' } }
];

const sentTimes = arr
  .map(({ latest }) => latest.sentTime)
  .sort((a, b) => new Date(b) - new Date(a));

console.log(sentTimes);```

ContentLicense: CC BY-SA 4.0


问:
Javascript for simple menu expanding
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

```<code><div id="submenu">
  <ul>
   <li>
     Something
   </li>
   <li>
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>
</code>```

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

答:
```<code><div id="submenu">
  <ul>
   <li id="1">
     Something
   </li>
   <li id="2">
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>
</code>```

if you are not using any library then you need to bind it something like this:

```<code> var menuText;

  window.onload = function()
  {

     menuText= document.getElementById("1");
     menuText.onfocus = menuFocusHandler;
     menuText.onblur = menuBlurHandler;
  }

function menuFocusHandler()
{
document.getElementById("submenu-1").style.display="inline";
}

function menuBlurHandler()
{
document.getElementById("submenu-1").style.display="none";
}
</code>```

or you can do this nicely and easily using certain javascript libraries that have APIs to do this easily.. some of these libraries are Jquery (the most popular one), Sencha etc.

Some of these libraries have extensions that have menu implementation etc.

ContentLicense: CC BY-SA 3.0

Title: Javascript for simple menu expanding

Body:
Hi I'm new to JavaScript and I want to code a very simple expanding submenu.

     Something

     Another

Something-sub

Something-sub

Something-sub

Another-sub

Another-sub

Another-sub

To be more specific, if I hover over something I want the something submenu displayed if the mouse leaves I want it to be hidden again...
I know it has been asked a lot and there are many ways to do this but Google brought up too many unsatisfying answers.
I hope you can spare 10 minutes to help me out of my misery

Regards and thank you!

Body:
<div id="submenu">
  <ul>
   <li id="1">
     Something
   </li>
   <li id="2">
     Another
   </li>
 </ul>
 <div id="submenu-1" class="submenu-options">
  <ul>
   <li>Something-sub</li>
   <li>Something-sub</li>
   <li>Something-sub</li>
  </ul>
 </div>
 <div id="submenu-2" class="submenu-options">
  <ul>
   <li>Another-sub</li>
   <li>Another-sub</li>
   <li>Another-sub</li>
  </ul>
 </div>
</div>

if you are not using any library then you need to bind it something like this:

 var menuText;

  window.onload = function()
  {

     menuText= document.getElementById("1");
     menuText.onfocus = menuFocusHandler;
     menuText.onblur = menuBlurHandler;
  }

function menuFocusHandler()
{
document.getElementById("submenu-1").style.display="inline";
}

function menuBlurHandler()
{
document.getElementById("submenu-1").style.display="none";
}

or you can do this nicely and easily using certain javascript libraries that have APIs to do this easily.. some of these libraries are Jquery (the most popular one), Sencha etc.

Some of these libraries have extensions that have menu implementation etc.


问:
How Can i limit the maximum number of options that can be selected in a Material UI lab Autocomplete component
(for instance) I wish to limit user selecting only 3 options in my Autocomplete component, and disable the options when the length of TAG Array reaches 3.
The problem is there is no limitMaxNumberOfTags option in the api, and i cant get any way to access the Selected tags array whatsoever {except the limitTags, which only limits the visible tags}
.
something along the lines of this might help
getOptionDisabled={(options, tags) => (tags.length > 3 ? true : false)}
.
Here is my autocomplete implementation so far

<Autocomplete
  multiple
  id="tags-outlined"
  options={students}
  getOptionLabel={(option) => option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
  defaultValue={[...added]}
  onChange={(e, newVal) => setAdded([...newVal])}
  renderOption={(option, state) => {
    return (
      <Chip
        icon={
          <FaceIcon /> /*<Avatar color="primary" variant='outlined' size="small" className={classes.small}></Avatar>*/
        }
        label={option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
        color="default"
        variant="outlined"
        {...state}
      />
    );
  }}
  renderTags={(options, getTagProps) =>
    options.map((option) => (
      <Chip
        icon={
          <FaceIcon /> /*<Avatar color="primary" variant='outlined' size="small" className={classes.small}></Avatar>*/
        }
        label={option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
        color="primary"
        variant="outlined"
        {...getTagProps({})}
      />
    ))
  }
  filterSelectedOptions
  filterOptions={(options, state) =>
    options.filter((option) => {
      for (let i = 0; i < added.length; i++) {
        if (added[i]._id === option._id) {
          return false;
        }
      }
      return true;
    })
  }
  // --->         getOptionDisabled={(options) => (tags.length > 3 ? true : false)}
  renderInput={(params) => (
    <TextField {...params} variant="outlined" color="primary" label="Select Students" placeholder="Participant" />
  )}
/>
```

答:
In my case, this worked fine.

```<code>onChange={(e, newVal) => {
    if (newVal > 3) {
      newVal.pop();
    }
    setAdded([...newVal]);
}
</code>```

Though the documentation explains that the value parameter of onChange prop is the new value, the actual content seems the array of all selected options.

And the last element in the value array is the newly selected option by the current change event.  Therefore the code snippet above eliminates the exceeding element against the limited number (3 as above).

The latter type (Array<T>) for value parameter in the documentation is the case.

Body:
In my case, this worked fine.

onChange={(e, newVal) => {
    if (newVal > 3) {
      newVal.pop();
    }
    setAdded([...newVal]);
}

Though the documentation explains that the value parameter of onChange prop is the new value, the actual content seems the array of all selected options.

And the last element in the value array is the newly selected option by the current change event.  Therefore the code snippet above eliminates the exceeding element against the limited number (3 as above).

The latter type (Array<T>) for value parameter in the documentation is the case.


问:
How to disable pytest dumping out source code?
When one of the tests fail, pytest will dump out the source code of the function where the exception is raised. However, something when the error is raised from another library, it still dumps the function source code flood the output.

Is it possible to disable pytest from dump source code and have the stack trace only? Stack trace is usually more than enough to track down the problem.

I have searched a bit but all I can find are posts related to --show-capture.

答:
Here is how to put your chosen option in a pytest.ini file:

```<code>[pytest]
# --tb not given    Produces reams of output, with full source code included in tracebacks
# --tb=no           Just shows location of failure in the test file: no use for tracking down errors
# --tb=short        Just shows vanilla traceback: very useful, but file names are incomplete and relative
# --tb=native       Slightly more info than short: still works very well. The full paths may be useful for CI
addopts = --tb=native
</code>```

The available values for --tb are:

```<code>  --tb=style            traceback print mode
                        (auto/long/short/line/native/no).
</code>```

Useful links:

pytest Configuration file formats

pytest Command-line Flags

Body:
Here is how to put your chosen option in a pytest.ini file:

[pytest]
# --tb not given    Produces reams of output, with full source code included in tracebacks
# --tb=no           Just shows location of failure in the test file: no use for tracking down errors
# --tb=short        Just shows vanilla traceback: very useful, but file names are incomplete and relative
# --tb=native       Slightly more info than short: still works very well. The full paths may be useful for CI
addopts = --tb=native

The available values for --tb are:

  --tb=style            traceback print mode
                        (auto/long/short/line/native/no).

Useful links:

pytest Configuration file formats

pytest Command-line Flags


问:
Is this formula for weighted binary cross entropy loss correct?
Here it is the formula I built: My equation for weighted binary cross entropy loss

Where:

alpha(i) = #Negative samples / Total samples if y(i)=1

alpha(i) = #Positive samples / Total samples if y(i)=0

Is it correct? I cannot find any similar formula on the internet.
Thank you!

答:
The alpha(i) value inside the summation block seems misplaced.
The binary loss value is calculated for each sample which is then summated to get the total binary log loss/binary cross entropy. But the alpha(i) does not belong to the sample, it is an aggregate property.
Hence the formula is not logical. Refer ->
https://www.analyticsvidhya.com/blog/2021/03/binary-cross-entropy-log-loss-for-binary-classification/</p>


问:
Call function of class ONE from class TWO without extend?
If i have two classes A, B and one does not extend another they are separate but both loaded into script can i still reference function in A from B?</p>

```<code>class A {
    function one() {
        echo "Class A";
    }
}

class B {
    function two() {
        echo "Class B";
        A::one();
    }
}

$a new A;
$b = new B;

$b->two();
</code>```

答: You can define one as static, but why would you do such a thing?</p>

Body:
If i have two classes A, B and one does not extend another they are separate but both loaded into script can i still reference function in A from B?

class A {
    function one() {
        echo "Class A";
    }
}

class B {
    function two() {
        echo "Class B";
        A::one();
    }
}

$a new A;
$b = new B;

$b->two();


问:
Type Conversion in Python using ord()
```<code>s = '4'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
</code>```

output: After converting character to integer : 52

I don't understand the value of output. Can someone please explain why 52 is printed?

Title: Type Conversion in Python using ord()

Body:
s = '4'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)

output: After converting character to integer : 52

I don't understand the value of output. Can someone please explain why 52 is printed?

Body:
Python’s built-in function chr() is used for converting an Integer to a Character, while the function ord() is used to do the reverse, i.e, convert a Character to an Integer.

For example :

print([(chr(i),i) for i in range(49, 123)])

output is :

[('1', 49), ('2', 50), ('3', 51), ('4', 52), ('5', 53), ('6', 54), ('7', 55), ('8', 56), ('9', 57), (':', 58), (';', 59), ('<', 60), ('=', 61), ('>', 62), ('?', 63), ('@', 64), ('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90), ('[', 91), ('\', 92), (']', 93), ('^', 94), ('_', 95), ('`', 96), ('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]

The ord() function takes a string argument of a single Unicode character and returns its integer Unicode code point value. It does the reverse of chr().


问:
VBA find same cell values, count and calculate
I want to count all the same values in column C and calculate something from the number of the same values * 10 / the associated B value of the cells.

example

If C3, C6 and C8 are the same then

Number of same values -> (3) * 10 / (B3B6B8)/4

So far I've only found one way to compare the whole thing.

```<code>Sub Check()

Dim CRange As Range
Dim myValue
Dim allSame As Boolean

Set CRange = Range("C1:C30")

myValue = CRange(1, 1).Value

allSame = (WorksheetFunction.CountA(CRange) = WorksheetFunction.CountIf(CRange, myValue))
MsgBox allSame
</code>```

End Sub

答:
Please, test the next way:

```<code>Sub testEvaluateFormula()
  Dim CRange  As Range, myValue As Range, allSame As Double

  Set CRange = Range("C1:C30")
  Set myValue = CRange(1, 1)

  allSame = Evaluate("=COUNTIF(" & CRange.Address & "," & myValue.Address & ")*10/(SUMIF(" & _
                  CRange.Address & "," & myValue.Address & "," & CRange.Offset(0, -1).Address & ")/4)")
  MsgBox "allSame = " & allSame
End Sub
</code>```

The above code can be easily adapted to return for any two used ranges. I can even transform it in a function...

Edited:

Please, use the next function:

```<code>Function makeCalculation(CRange As Range, myVal As Range) As Double
     makeCalculation = Evaluate("=COUNTIF(" & CRange.Address & "," & myVal.Address & ")*10/(SUMIF(" & _
                        CRange.Address & "," & myVal.Address & "," & CRange.Offset(0, -1).Address & ")/4)")
End Function
</code>```

It can be called as:

```<code>Sub testAllSame()
  Dim CRange  As Range, myValue As Range, allSame As Double

  Set CRange = Range("C1:C30")
  Set myValue = CRange(1, 1)
  allSame = makeCalculation(CRange, myValue)

  MsgBox "allSame = " & allSame
End Sub
</code>```

You can call the function for any CRange and myValue range. It will return on the same logic: Counting the in CRange the myValue value occurrences, multiplies them with 10 and divides the result at SumIf for the column before CRange divided by 4.

Body:
I want to count all the same values in column C and calculate something from the number of the same values * 10 / the associated B value of the cells.

example

If C3, C6 and C8 are the same then

Number of same values -> (3) * 10 / (B3B6B8)/4

So far I've only found one way to compare the whole thing.

Sub Check()

Dim CRange As Range
Dim myValue
Dim allSame As Boolean

Set CRange = Range("C1:C30")

myValue = CRange(1, 1).Value

allSame = (WorksheetFunction.CountA(CRange) = WorksheetFunction.CountIf(CRange, myValue))
MsgBox allSame

End Sub

Body:
Please, test the next way:

Sub testEvaluateFormula()
  Dim CRange  As Range, myValue As Range, allSame As Double

  Set CRange = Range("C1:C30")
  Set myValue = CRange(1, 1)

  allSame = Evaluate("=COUNTIF(" & CRange.Address & "," & myValue.Address & ")*10/(SUMIF(" & _
                  CRange.Address & "," & myValue.Address & "," & CRange.Offset(0, -1).Address & ")/4)")
  MsgBox "allSame = " & allSame
End Sub

The above code can be easily adapted to return for any two used ranges. I can even transform it in a function...

Edited:

Please, use the next function:

Function makeCalculation(CRange As Range, myVal As Range) As Double
     makeCalculation = Evaluate("=COUNTIF(" & CRange.Address & "," & myVal.Address & ")*10/(SUMIF(" & _
                        CRange.Address & "," & myVal.Address & "," & CRange.Offset(0, -1).Address & ")/4)")
End Function

It can be called as:

Sub testAllSame()
  Dim CRange  As Range, myValue As Range, allSame As Double

  Set CRange = Range("C1:C30")
  Set myValue = CRange(1, 1)
  allSame = makeCalculation(CRange, myValue)

  MsgBox "allSame = " & allSame
End Sub

You can call the function for any CRange and myValue range. It will return on the same logic: Counting the in CRange the myValue value occurrences, multiplies them with 10 and divides the result at SumIf for the column before CRange divided by 4.


问:
Sending emails via NodeMailer in MERN Stack
I have a question about the whole process, I managed to finish a reset password flow via email, but the emails that I'm sending are going into spam. Do you guys know a way for my emails to go into the inbox and not into the spam folder? Did you ever met this case?</p>

答:
Try gmail credentials

https://kb.synology.com/en-global/SRM/tutorial/How_to_use_Gmail_SMTP_server_to_send_emails_for_SRM

if it works, you have to change the domain of your user credentials


问:
MariaDB vs PostgreSQL INSERT - PostgreSQL 2-4 times faster
I'm comparing MariaDB 10.6 vs PostgreSQL 14 in INSERT operation.
I created a table in both databases, then I tried to insert 1 Million rows in both.
In PostgreSQL, it takes only 2 seconds to INSERT 1 million rows.
But in MariaDB, it takes 9 seconds to INSERT 1 million rows.
But I want to work with MariaDB, so I tried to improve the my.ini but still PostgreSQL is about 2-4 times faster than MariaDB.
This is my table in both databases (no index in both, except the primary key with autoincrement)

```<code>CREATE TABLE `project_user` (
    `user_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_username` VARCHAR(16) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_mobile` VARCHAR(16) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_email` VARCHAR(64) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_first_name` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_first_name_en` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_last_name` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_last_name_en` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_country` TINYINT(3) UNSIGNED NULL DEFAULT NULL,
    `user_gender` BIT(1) NULL DEFAULT NULL,
    `user_registered_ip` INT(10) UNSIGNED NOT NULL,
    `user_registered_at` INT(10) UNSIGNED NOT NULL,
    `user_status` BIT(1) NOT NULL DEFAULT b'1',
    PRIMARY KEY (`user_id`) USING BTREE
)
COLLATE='ascii_general_ci'
ENGINE=InnoDB
;
</code>```

in PostgreSQL is equal to this table too (except the tinyint which i used bit) ...

In PostgreSQL, I used this operation to insert 1 million rows

```<code>INSERT INTO project_user (user_registered_ip,user_registered_at)
SELECT i,i+1
FROM generate_series(1, 1000000) AS i;
</code>```

And in MariaDB I used this function

```<code>BEGIN
    FOR i IN 1..1000000
    DO
        INSERT INTO `project_user` (`user_registered_ip`,`user_registered_at`)
        VALUES (i, i+1);
    END FOR;
    RETURN 1;
END
</code>```

And this is my.ini

```<code>[mysqld]
datadir=C:/Program Files/MariaDB 10.6/data
port=3306
max_connections=8192
max_allowed_packet=1G
skip_external_locking
skip_name_resolve
default_storage_engine=InnoDB
innodb_file_per_table=1
innodb_buffer_pool_size=24G
innodb_buffer_pool_instances=24
innodb_flush_log_at_trx_commit=0
innodb_flush_method=O_DIRECT
innodb_log_buffer_size=8M
innodb_log_file_size=2G
innodb_sort_buffer_size=16M
innodb_stats_on_metadata=0
innodb_thread_concurrency=6
innodb_read_io_threads=64
innodb_write_io_threads=64
key_buffer_size=512M
concurrent_insert=2
back_log=512
thread_cache_size=100
thread_stack=192K
interactive_timeout=60
wait_timeout=60
join_buffer_size=4M
read_buffer_size=3M
read_rnd_buffer_size=4M
sort_buffer_size=4M
table_definition_cache=40000
table_open_cache=40000
open_files_limit=60000
max_heap_table_size=128M
tmp_table_size=128M
slow_query_log=0
long_query_time=5
log_queries_not_using_indexes=0

[mysqldump]
quick
max_allowed_packet=1024M

[mysql]
no-auto-rehash

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
open-files-limit = 8192

[client]
port=3306
plugin-dir=C:/Program Files/MariaDB 10.6/lib/plugin
</code>```

Is there any way to improve the INSERT speed of mariadb ?

答:
You should try a (slightly) more comparable method, for example a set-based insert in MariaDB using a cross join to create a set:

```<code>insert into project_user (user_registered_ip, user_registered_at)
select r, r+1
from (
  select Row_Number() over(order by (select null) ) r
  from information_schema.COLUMNS x
  cross join information_schema.COLUMNS y
  limit 1000000
)x;
</code>```

For another comparision, on my local SQL Server (2019), using a similar while loop and single-row insert / values, 1 million rows takes 7 seconds; using the above single insert from a cross-join method it's 1 second.

Body:
I'm comparing MariaDB 10.6 vs PostgreSQL 14 in INSERT operation.
I created a table in both databases, then I tried to insert 1 Million rows in both.
In PostgreSQL, it takes only 2 seconds to INSERT 1 million rows.
But in MariaDB, it takes 9 seconds to INSERT 1 million rows.
But I want to work with MariaDB, so I tried to improve the my.ini but still PostgreSQL is about 2-4 times faster than MariaDB.
This is my table in both databases (no index in both, except the primary key with autoincrement)

CREATE TABLE `project_user` (
    `user_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_username` VARCHAR(16) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_mobile` VARCHAR(16) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_email` VARCHAR(64) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_first_name` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_first_name_en` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_last_name` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_last_name_en` VARCHAR(32) NULL DEFAULT NULL COLLATE 'ascii_general_ci',
    `user_country` TINYINT(3) UNSIGNED NULL DEFAULT NULL,
    `user_gender` BIT(1) NULL DEFAULT NULL,
    `user_registered_ip` INT(10) UNSIGNED NOT NULL,
    `user_registered_at` INT(10) UNSIGNED NOT NULL,
    `user_status` BIT(1) NOT NULL DEFAULT b'1',
    PRIMARY KEY (`user_id`) USING BTREE
)
COLLATE='ascii_general_ci'
ENGINE=InnoDB
;

in PostgreSQL is equal to this table too (except the tinyint which i used bit) ...

In PostgreSQL, I used this operation to insert 1 million rows

INSERT INTO project_user (user_registered_ip,user_registered_at)
SELECT i,i+1
FROM generate_series(1, 1000000) AS i;

And in MariaDB I used this function

BEGIN
    FOR i IN 1..1000000
    DO
        INSERT INTO `project_user` (`user_registered_ip`,`user_registered_at`)
        VALUES (i, i+1);
    END FOR;
    RETURN 1;
END

And this is my.ini

[mysqld]
datadir=C:/Program Files/MariaDB 10.6/data
port=3306
max_connections=8192
max_allowed_packet=1G
skip_external_locking
skip_name_resolve
default_storage_engine=InnoDB
innodb_file_per_table=1
innodb_buffer_pool_size=24G
innodb_buffer_pool_instances=24
innodb_flush_log_at_trx_commit=0
innodb_flush_method=O_DIRECT
innodb_log_buffer_size=8M
innodb_log_file_size=2G
innodb_sort_buffer_size=16M
innodb_stats_on_metadata=0
innodb_thread_concurrency=6
innodb_read_io_threads=64
innodb_write_io_threads=64
key_buffer_size=512M
concurrent_insert=2
back_log=512
thread_cache_size=100
thread_stack=192K
interactive_timeout=60
wait_timeout=60
join_buffer_size=4M
read_buffer_size=3M
read_rnd_buffer_size=4M
sort_buffer_size=4M
table_definition_cache=40000
table_open_cache=40000
open_files_limit=60000
max_heap_table_size=128M
tmp_table_size=128M
slow_query_log=0
long_query_time=5
log_queries_not_using_indexes=0

[mysqldump]
quick
max_allowed_packet=1024M

[mysql]
no-auto-rehash

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
open-files-limit = 8192

[client]
port=3306
plugin-dir=C:/Program Files/MariaDB 10.6/lib/plugin

Is there any way to improve the INSERT speed of mariadb ?

Body:
You should try a (slightly) more comparable method, for example a set-based insert in MariaDB using a cross join to create a set:

insert into project_user (user_registered_ip, user_registered_at)
select r, r+1
from (
  select Row_Number() over(order by (select null) ) r
  from information_schema.COLUMNS x
  cross join information_schema.COLUMNS y
  limit 1000000
)x;

For another comparision, on my local SQL Server (2019), using a similar while loop and single-row insert / values, 1 million rows takes 7 seconds; using the above single insert from a cross-join method it's 1 second.


问:
Simple way to bind two different properties together?
In my application I always want hscrollbar.LargeChange to equal panel.Width. Currently I set hscrollbar.LargeChange to panel.Widthin resizing events, painting events, et cetera. I do not know much about binding so I'm wondering if it is possible to do this.

Sorry if this is a simple question but when I tried googling binding and c# I got a lot of complicated information about other platforms.

答: Yes, the way you are doing it, in the panel.Resize event is the only way to do it in windows forms.</p>


问:
Passing object method to array_map()
```<code>    class theClass{
         function doSomeWork($var){
            return ($var + 2);
         }

         public $func = "doSomeWork";

         function theFunc($min, $max){
            return (array_map(WHAT_TO_WRITE_HERE, range($min, $max)));
         }
    }

$theClass = new theClass;
print_r(call_user_func_array(array($theClass, "theFunc"), array(1, 5)));
exit;
</code>```

Can any one tell what i can write at WHAT_TO_WRITE_HERE, so that doSomeWork function get pass as first parameter to array_map. and code work properly.

And give out put as

```<code>Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 7
)
</code>```

答:
I tried search for solution but it not works, so I created custom small map function that will do the task for 1 variable passed to the function it simple but will act like map

```<code>class StyleService {
  function check_css_block($str){
    $check_end = substr($str,-1) == ';';
    $check_sprator =  preg_match_all("/:/i", $str) == 1;
    $check_sprator1 =  preg_match_all("/;/i", $str) == 1;
    if ( $check_end && $check_sprator && $check_sprator1){
      return $str;
    } else {
      return false;
    }
  }

  function mymap($function_name, $data){
    $result = array();
    $current_methods = get_class_methods($this);
    if (!in_array($function_name, $current_methods)){
      return False;
    }
    for ($i=0; $i<count($data); $i++){
      $function_result = $this->{$function_name}($data[$i]);
      array_push($result, $function_result);
    }
    return $result;
  }

  function get_advanced_style_data($data)

  {
    return $this->mymap('check_css_block', $data);
  }
}
</code>```

this way you can call a function name as string $this->{'function_name'}() in php

Title: Passing object method to array_map()

Body:
    class theClass{
         function doSomeWork($var){
            return ($var + 2);
         }

         public $func = "doSomeWork";

         function theFunc($min, $max){
            return (array_map(WHAT_TO_WRITE_HERE, range($min, $max)));
         }
    }

$theClass = new theClass;
print_r(call_user_func_array(array($theClass, "theFunc"), array(1, 5)));
exit;

Can any one tell what i can write at WHAT_TO_WRITE_HERE, so that doSomeWork function get pass as first parameter to array_map. and code work properly.

And give out put as

Array
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 7
)

Body:
I tried search for solution but it not works, so I created custom small map function that will do the task for 1 variable passed to the function it simple but will act like map

class StyleService {
  function check_css_block($str){
    $check_end = substr($str,-1) == ';';
    $check_sprator =  preg_match_all("/:/i", $str) == 1;
    $check_sprator1 =  preg_match_all("/;/i", $str) == 1;
    if ( $check_end && $check_sprator && $check_sprator1){
      return $str;
    } else {
      return false;
    }
  }

  function mymap($function_name, $data){
    $result = array();
    $current_methods = get_class_methods($this);
    if (!in_array($function_name, $current_methods)){
      return False;
    }
    for ($i=0; $i<count($data); $i++){
      $function_result = $this->{$function_name}($data[$i]);
      array_push($result, $function_result);
    }
    return $result;
  }

  function get_advanced_style_data($data)

  {
    return $this->mymap('check_css_block', $data);
  }
}

this way you can call a function name as string $this->{'function_name'}() in php


问:
Change a state value in React Testing Library
Having the following component:

```<code>import { useState } from 'react';

export function MyComponent() {
  const [val, setVal] = useState(false);

  return (
    <div>
      big container
      <button onClick={() => setVal(!val)}>click</button>
      {val && <div>small container</div>}
    </div>
  );
}

export default MyComponent;
</code>```

There is a div containing the text "small container", which only appears when val is true.

I want to write a test in jest for this but don't know how to mock the value of val there

Here is my code so far:

```<code>  it('small container visible only when val is true', () => {
    const { queryByText } = render(<MyComponent />);
    const toTest = queryByText('small container');
    expect(toTest).not.toBeInTheDocument();
  });
</code>```

this test passes, but how can be added val set to true in order to test that toTest is present in the document?

答:
You can click the button which will set the val to true.

```<code>it('small container visible only when val is true', () => {
  const {queryByText, getByTestId} = render(<MyComponent />);
  const clickButton = getByTestId('your.button.test.id');
  fireEvent.click(clickButton);
  expect(queryByText('small container')).toBeInDocument();
});

</code>```

React testing library does not recommend to test implementation details as per documented here. That's why you might not want to access internal state of component while testing.

Body:
Having the following component:

import { useState } from 'react';

export function MyComponent() {
  const [val, setVal] = useState(false);

  return (

      big container
      <button onClick={() => setVal(!val)}>click</button>
      {val &&
small container
}

  );
}

export default MyComponent;

There is a div containing the text "small container", which only appears when val is true.

I want to write a test in jest for this but don't know how to mock the value of val there

Here is my code so far:

  it('small container visible only when val is true', () => {
    const { queryByText } = render(<MyComponent />);
    const toTest = queryByText('small container');
    expect(toTest).not.toBeInTheDocument();
  });

this test passes, but how can be added val set to true in order to test that toTest is present in the document?

Body:
You can click the button which will set the val to true.

it('small container visible only when val is true', () => {
  const {queryByText, getByTestId} = render(<MyComponent />);
  const clickButton = getByTestId('your.button.test.id');
  fireEvent.click(clickButton);
  expect(queryByText('small container')).toBeInDocument();
});

React testing library does not recommend to test implementation details as per documented here. That's why you might not want to access internal state of component while testing.


问:
Sorting a generic list of two types
```<code>  List.add(new TheDList("abc123", 9986));
  List.add(new TheDList("ads314", 9986));
  List.add(new TheDList("dal192", 3214));
  List.add(new TheDList("sam273", 3214));
  List.add(new TheDList("wor213", 7643));
  List.add(new TheDList("wos987", 1292));
  List.add(new TheDList("cat202", 9986));
  List.add(new TheDList("jga213", 1292));
  List.add(new TheDList("gog113", 1493));
  List.add(new TheDList("aba231", 9831));
</code>```

There's a Class called TheDList and it has the name and value
as final variables, but it also has a constructor and (get) methods.

The list above is from a method called sort and the elements in the list above are shuffled before the list is sent to me through this method.

there are two methods within the Class TheDList, getValue and getString
how do I sort this using Collector or sort methods within Java?

答:
Use the reversed() method of Comparator to sort descending and employ the thenComparing() method to break ties.

Using Comparator methods, it’s a one-liner:

```<code>public void sort(List<TheDList> list) {
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
}
</code>```

To leave the original list unchanged and instead return a new, sorted list, use ArrayList’s copy constructor before sorting:

```<code>public List<TheDList> sort(List<TheDList> list) {
    list = new ArrayList(list);
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
    return list;
}
</code>```

Title: Sorting a generic list of two types

Body:
  List.add(new TheDList("abc123", 9986));
  List.add(new TheDList("ads314", 9986));
  List.add(new TheDList("dal192", 3214));
  List.add(new TheDList("sam273", 3214));
  List.add(new TheDList("wor213", 7643));
  List.add(new TheDList("wos987", 1292));
  List.add(new TheDList("cat202", 9986));
  List.add(new TheDList("jga213", 1292));
  List.add(new TheDList("gog113", 1493));
  List.add(new TheDList("aba231", 9831));

There's a Class called TheDList and it has the name and value
as final variables, but it also has a constructor and (get) methods.

The list above is from a method called sort and the elements in the list above are shuffled before the list is sent to me through this method.

there are two methods within the Class TheDList, getValue and getString
how do I sort this using Collector or sort methods within Java?

Body:
Use the reversed() method of Comparator to sort descending and employ the thenComparing() method to break ties.

Using Comparator methods, it’s a one-liner:

public void sort(List<TheDList> list) {
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
}

To leave the original list unchanged and instead return a new, sorted list, use ArrayList’s copy constructor before sorting:

public List<TheDList> sort(List<TheDList> list) {
    list = new ArrayList(list);
    list.sort(
      comparing(TheDList::getValue)
      .reversed()
      .thenComparing(TheDList::getString));
    return list;
}


问:
Using mod_rewrite to convert folders to querystring
What's the easiest way to convert these requests:

```<code>http://www.example.com/en/
http://www.example.com/en/index.php
</code>```

To:

```<code>http://www.example.com/index.php?language_id=en
</code>```

There's various PHP files, so the rule would also need to map

```<code>http://www.example.com/en/anyfile.php
</code>```

To:

```<code>http://www.example.com/anyfile.php?language_id=en
</code>```

The language ID can be any two letter code (it's checked within the PHP script, to ensure it's valid).

Presumably, I'll need to use .htaccess, and any advice on how to implement the above would be greatly appreciated.  Thanks.

Update

The following worked for me.

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ([a-z]+)/(css|js|images)/(.+) /$2/$3 [L]
  RewriteRule ([a-z]+)/(.+).php /$2.php?language_id=$1 [QSA,L]
  RewriteRule ([a-z]+)/$ /index.php?language_id=$1 [QSA,L]
</IfModule>
</code>```

This also re-routes requests to the css, js, and images folders back to the root folder.  It also works if no filename is entered, automatically redirecting to index.php.

答:
```<code>RewriteRule /en/(.*) /$1?language_id=en
</code>```

It's untested but in theory it should map anything after en to be a variable becore the ?language_id=en

You could also do

```<code>RewriteRule /([a-zA-Z0-9+])/(.*) /$2?language_id=$1
</code>```

This should also map

http://www.example.com/is/index.php

To

http://www.example.com/index.php?language_id=is

OwnerDisplayName: Mun

ContentLicense: CC BY-SA 2.5

Body:
What's the easiest way to convert these requests:

http://www.example.com/en/
http://www.example.com/en/index.php

To:

http://www.example.com/index.php?language_id=en

There's various PHP files, so the rule would also need to map

http://www.example.com/en/anyfile.php

To:

http://www.example.com/anyfile.php?language_id=en

The language ID can be any two letter code (it's checked within the PHP script, to ensure it's valid).

Presumably, I'll need to use .htaccess, and any advice on how to implement the above would be greatly appreciated.  Thanks.

Update

The following worked for me.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ([a-z]+)/(css|js|images)/(.+) /$2/$3 [L]
  RewriteRule ([a-z]+)/(.+).php /$2.php?language_id=$1 [QSA,L]
  RewriteRule ([a-z]+)/$ /index.php?language_id=$1 [QSA,L]
</IfModule>

This also re-routes requests to the css, js, and images folders back to the root folder.  It also works if no filename is entered, automatically redirecting to index.php.

LastEditorDisplayName: Mun

Body:
RewriteRule /en/(.*) /$1?language_id=en

It's untested but in theory it should map anything after en to be a variable becore the ?language_id=en

You could also do

RewriteRule /([a-zA-Z0-9+])/(.*) /$2?language_id=$1

This should also map

http://www.example.com/is/index.php

To

http://www.example.com/index.php?language_id=is

OwnerDisplayName: Ólafur Waage


问:
How execute script from command prompt in python
I have mysql dump command that I would like to run from from windows shell
or command prompt. I have used shell it does work.

```<code>  d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql"
  fn = dn+d
  cmd="""mysqldump -u hapopdy -p   > %s""" %fn
  print cmd
</code>```

Edit:::::::
The -p needs to be a raw input.

答:
You should save the password in mysql's local configuration file for the user.(In Unix it's ~/.my.cnf) or you can give it on the command line with --password=MYPASSWORD.

Either way, the password will be visible to a large audience. In the .my.cnf case, it will be visible to anyone with read access to the file. In the second case, it will be visible to anyone who can get a process listing on the system, in addition to those who have read access to your script.

Body:
I have mysql dump command that I would like to run from from windows shell
or command prompt. I have used shell it does work.

  d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql"
  fn = dn+d
  cmd="""mysqldump -u hapopdy -p   > %s""" %fn
  print cmd

Edit:::::::
The -p needs to be a raw input.


问:
Text won't start in the top left of Text Box
I have an input description box with a fixed height and width and its own style. The text is centred but I want it to start in the top left.

HTML

```<code><input id="eventDescriptionInput" placeholder="Description" />
</code>```

CSS

```<code>#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;[enter image description here][1]
box-shadow: 0px 0px 3px gray;
}
</code>```

答:
If you want to continue using input instead of textarea you want to remove height: 200px; and add padding-bottom: <number>px:

#eventDescriptionInput {
padding: 10px;
width: 100%;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
padding-bottom: 200px; /* new line */
}
```

Though I would recommend using textarea as mentioned by someone else

Body:
I have an input description box with a fixed height and width and its own style. The text is centred but I want it to start in the top left.

HTML

<input id="eventDescriptionInput" placeholder="Description" />

CSS

#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;[enter image description here][1]
box-shadow: 0px 0px 3px gray;
}

Body:
If you want to continue using input instead of textarea you want to remove height: 200px; and add padding-bottom: <number>px:

#eventDescriptionInput {
padding: 10px;
width: 100%;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
padding-bottom: 200px; /* new line */
}

Though I would recommend using textarea as mentioned by someone else


问:
Copy constructor and returning by value
I'm learning about return value optimization and copy elision in C++ and wrote a test vector class to experiment with it in which I allocate memory for an integer array in the constructor:

```<code>
    //Constructor:
    Vector::Vector(int s): elem{new double[s]}, sz{s} {std::cout << "Constructor called"<<std::endl;}

    //Destructor:
    Vector::~Vector(){
        delete[] elem;
        std::cout << "Destructor is called" << std::endl;
    }

    double& Vector::operator[](int i){ return elem[i];}

    //Move constructor:
    Vector::Vector(Vector&& v): elem{v.elem}, sz{v.sz}
    {
    std::cout << "Move constructor is called" << std::endl;
        v.elem = nullptr;
        v.sz=0;
    }

    //Copy constructor:
    Vector::Vector(Vector& v): elem{v.elem }, sz{v.sz}
    {
    std::cout << "Copy constructor is called" << std::endl;
    }

</code>```

In a main file I write a function in which I create a vector from an integer array and return it by value:

```<code>
    Vector make(int s,int array[]){

    Vector v(s);

    for(int i =0; i<s; i++){
    v[i] = array[i];
    }

    return v;
    }

</code>```

I call this in the main function as follows:

```<code>
    int main(){

    int a[] = {1,2,3,4};

    Vector v = make(4,a);

    return 0;
    }
</code>```

When I then use the compiler option -fno-elide-constructors
the move constructor gets called when returning from function. If I get what is written in this post: move constructor called on return instead of copy, the first thing the compiler tries to do is to use the move constructor and when this is not available it uses the copy constructor. So I thought that if I deleted the move constructor:

```<code>  Vector(Vector&&)=delete;
</code>```

the copy constructor would be used as a last resort. If I do this however, the compiler complains that

```<code>error: use of deleted function ‘Vector::Vector(Vector&&)’

Vector v = make(4,a);
</code>```

I wonder if someone can explain to me what is going on here? I know it's probably what I would want to do, but is it possible to make the copy constructor being called when returning the object from the function?

答:
copy constructor should have a const parameter :

```<code>Vector::Vector(const Vector& v)
</code>```

without it cannot accept a rvalue than make return

Title: Copy constructor and returning by value

Body:
I'm learning about return value optimization and copy elision in C++ and wrote a test vector class to experiment with it in which I allocate memory for an integer array in the constructor:

    //Constructor:
    Vector::Vector(int s): elem{new double[s]}, sz{s} {std::cout << "Constructor called"<<std::endl;}

    //Destructor:
    Vector::~Vector(){
        delete[] elem;
        std::cout << "Destructor is called" << std::endl;
    }

    double& Vector::operator[](int i){ return elem[i];}

    //Move constructor:
    Vector::Vector(Vector&& v): elem{v.elem}, sz{v.sz}
    {
    std::cout << "Move constructor is called" << std::endl;
        v.elem = nullptr;
        v.sz=0;
    }

    //Copy constructor:
    Vector::Vector(Vector& v): elem{v.elem }, sz{v.sz}
    {
    std::cout << "Copy constructor is called" << std::endl;
    }

In a main file I write a function in which I create a vector from an integer array and return it by value:

    Vector make(int s,int array[]){

    Vector v(s);

    for(int i =0; i<s; i++){
    v[i] = array[i];
    }

    return v;
    }

I call this in the main function as follows:

    int main(){

    int a[] = {1,2,3,4};

    Vector v = make(4,a);

    return 0;
    }

When I then use the compiler option -fno-elide-constructors
the move constructor gets called when returning from function. If I get what is written in this post: move constructor called on return instead of copy, the first thing the compiler tries to do is to use the move constructor and when this is not available it uses the copy constructor. So I thought that if I deleted the move constructor:

  Vector(Vector&&)=delete;

the copy constructor would be used as a last resort. If I do this however, the compiler complains that

error: use of deleted function ‘Vector::Vector(Vector&&)’

Vector v = make(4,a);

I wonder if someone can explain to me what is going on here? I know it's probably what I would want to do, but is it possible to make the copy constructor being called when returning the object from the function?

Body:
copy constructor should have a const parameter :

Vector::Vector(const Vector& v)

without it cannot accept a rvalue than make return


问:
How to return the "third nested" association in findAll of Sequelize.js
I am having a hard time how to do that, I googled a lot but couldn't find.

I have a product that have a subcategory and the subcategory has a category.

```<code>product                subcategory            category
id_subcategory           id                     id
                         id_category

 findAll({include: Category}); //didn't work
</code>```

答:
That was a hard one, after a million tries:</p>
```<code>  let anunciosPesquisa = await anuncio.findAll({  include: [{ model: Subcategoria, include: { model: Categoria} }]  });
</code>```

Body:
I am having a hard time how to do that, I googled a lot but couldn't find.

I have a product that have a subcategory and the subcategory has a category.

product                subcategory            category
id_subcategory           id                     id
                         id_category

 findAll({include: Category}); //didn't work

Body:
That was a hard one, after a million tries:

  let anunciosPesquisa = await anuncio.findAll({  include: [{ model: Subcategoria, include: { model: Categoria} }]  });


问:
ReactJS problem with
 element visibility
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

```<code>const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (
    <div>
        <p style={{visibility: isVisible ? "visible" : "hidden"}}>{errorText}</p>
    </div>
    )
}
</code>```

Error is rendered by the following button inside a return:

```<code><button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>
</code>```

答:
I would refactor component in this way, then it should work as you want

```<code>const Error = (props) => {
    const [error, setError] = useState({errorText: '', isVisible: false})

    useEffect(() => {
      if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        setError({errorText: "Error in field: name", isVisible: true})
      }
    },[])

    return (
    <div>
        {error?.isVisible && <p>{error?.errorText}</p>}
    </div>
    )
}
</code>```

Working example https://codesandbox.io/s/bold-chihiro-bnlw5?file=/src/App.js

Title: ReactJS problem with <p> element visibility

Body:
I have 3 input fields with Name, Address and Year. I pass the length of all the 3 variables as props to this Error component. The errorText should be hidden by default and turn visible if the name is less than 4 letters.

Problem is when I input a name that is less than 4 letters, it changes the errorText variable to the correct "Error in field: name", which I can see by the alert, but the P element still does not change and stays empty.

Also reason why the errorText is not already the one I need by default is, I have more If statements for every alternative instance. For example, if Address and Name are less than 4, then it needs to say "Error in field: address, name".

What could be the issue here? Thanks in advance.

const Error = (props) => {
    let errorText = '';
    let isVisible = false;

    if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        errorText = "Error in field: name"
        isVisible = true;
        alert("errorText: " + errorText); //This alert is only for testing
    }

    return (

{errorText}

    )
}

Error is rendered by the following button inside a return:

<button type="submit" onClick={() => Error({nameLength, addressLength, yearLength})}>Add</button>

Body:
I would refactor component in this way, then it should work as you want

const Error = (props) => {
    const [error, setError] = useState({errorText: '', isVisible: false})

    useEffect(() => {
      if (props.nameLength < 4 && props.addressLength >= 4 && props.yearLength >= 4) {
        setError({errorText: "Error in field: name", isVisible: true})
      }
    },[])

    return (
    <div>
        {error?.isVisible && <p>{error?.errorText}</p>}
    </div>
    )
}

Working example https://codesandbox.io/s/bold-chihiro-bnlw5?file=/src/App.js


问:
Query or filter pandas dataframe on multiple columns and cell values
I've tried to figure this one out, but all methods end up with errors.

Quick background info: I have a dataframe with US states and info when a state has adopted a new law. In addition, the dataframe tells which are the neighbouring states. Here's a quick mockup:

(df: treated_states)

```<code>| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | AZ    |1999   |100   |CA        |AK        |WV        |1      |
| 1999     | AZ    |1999   |50    |CA        |AK        |WV        |1      |
</code>```

(df: not_treated)

```<code>| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | WV    |0      |100   |CA        |AK        |WV        |0      |
| 1999     | AK    |0      |80    |CA        |AK        |WV        |0      |
</code>```

In reality the dataframe includes all US states and all their neighbouring states in separate columns. There are data points before and and after the change in legislation.

I have filtered states that have adopted the new BC_law (df: treated_states) and those that haven't (df: not_treated). Now I should find out if the adoption of the new law affects the neighbouring states.

My problem:
I should filter and store into a new dataframe the treated_states dataframes' Neighbor1, Neighbor2, Neighbor3 that exist in the dataframe not_treated

In case you wonder why I need to filter those:
I'll do a difference-in-difference regression to determine if adopting the new law affects the neighboring states that don't adopt the BC_law.

答:
Here is a more concise approach:

Filter the Neighbour like columns

Create boolean mask with DataFrame.isin to check whether each element in dataframe is contained in state column of non_treated

Reduce the boolean mask along the columns axis with any

cols = treated_states.filter(like='Neigh')
mask = cols.isin(not_treated.state).any(axis=1)
```
<hr />
```>>> treated_states[mask]

   year state  BC_law  n_ipo Neighbor1 Neighbor2 Neighbor3  Treated
0  1980    AZ    1999    100        CA        AK        WV        1
1  1999    AZ    1999     50        CA        AK        WV        1
```

Body:
I've tried to figure this one out, but all methods end up with errors.

Quick background info: I have a dataframe with US states and info when a state has adopted a new law. In addition, the dataframe tells which are the neighbouring states. Here's a quick mockup:

(df: treated_states)

| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | AZ    |1999   |100   |CA        |AK        |WV        |1      |
| 1999     | AZ    |1999   |50    |CA        |AK        |WV        |1      |

(df: not_treated)

| year     | state |BC_law |n_ipo |Neighbor1 |Neighbor2 |Neighbor3 |Treated|
| -------- | ----- |-------|------|----------|----------|----------|-------|
| 1980     | WV    |0      |100   |CA        |AK        |WV        |0      |
| 1999     | AK    |0      |80    |CA        |AK        |WV        |0      |

In reality the dataframe includes all US states and all their neighbouring states in separate columns. There are data points before and and after the change in legislation.

I have filtered states that have adopted the new BC_law (df: treated_states) and those that haven't (df: not_treated). Now I should find out if the adoption of the new law affects the neighbouring states.

My problem:
I should filter and store into a new dataframe the treated_states dataframes' Neighbor1, Neighbor2, Neighbor3 that exist in the dataframe not_treated

In case you wonder why I need to filter those:
I'll do a difference-in-difference regression to determine if adopting the new law affects the neighboring states that don't adopt the BC_law.

Body:
Here is a more concise approach:

Filter the Neighbour like columns

Create boolean mask with DataFrame.isin to check whether each element in dataframe is contained in state column of non_treated

Reduce the boolean mask along the columns axis with any

cols = treated_states.filter(like='Neigh')
mask = cols.isin(not_treated.state).any(axis=1)

>>> treated_states[mask]

   year state  BC_law  n_ipo Neighbor1 Neighbor2 Neighbor3  Treated
0  1980    AZ    1999    100        CA        AK        WV        1
1  1999    AZ    1999     50        CA        AK        WV        1


答:
You can directly store it in a .txt file like this

```<code>sink('Output.txt')
for (id in unique(df$name)){
  seq <- df[which(df$name == id), 'sequence']
  cat(id, seq, '\n')
}
sink()
</code>```

Output.txt then looks like this:

```<code>9073050 1 15 1 10 1 4 16 7
9079078 18 19
9085376 22 14 23 14 24
</code>```

And for completeness, if you also want to store it within R a list is probably the most convenient data structure:

```<code>lst <- list()
for (id in unique(df$name)){
  seq <- df[which(df$name == id), 'sequence']
  lst[[as.character(id)]] = seq
}
</code>```

which yields

```<code>> lst
$`9073050`
[1]  1 15  1 10  1  4 16  7

$`9079078`
[1] 18 19

$`9085376`
[1] 22 14 23 14 24
</code>```

Title: R how to pivot a table (with two columns) with categories of different length?

Body:
I have a table, shown as below. I need to pivot it so that data is spread horizontally and store it in a txt file with sep = space. But since the number of items per category differs, I am not sure what data structure is the best to use.

I have been stuck with this for 3 days. Could anyone please kindly help me?

Many thanks

data.frame(
 name=c(9073050,9073050,9073050,9073050,9073050,9073050,9073050,9073050,9079078,9079078,9085376,9085376,9085376,9085376,9085376),
 sequence=c(1,15, 1,10,1, 4, 16,7,18,19,22,14,23,14,24)
)

    name sequence
1  9073050        1
2  9073050       15
3  9073050        1
4  9073050       10
5  9073050        1
6  9073050        4
7  9073050       16
8  9073050        7
9  9079078       18
10 9079078       19
11 9085376       22
12 9085376       14
13 9085376       23
14 9085376       14
15 9085376       24

9073050       1      15       1      10       1       4      16       7
9079078      18      19
9085376      22      14      23      14      24

Body:
You can directly store it in a .txt file like this

sink('Output.txt')
for (id in unique(df$name)){
  seq <- df[which(df$name == id), 'sequence']
  cat(id, seq, '\n')
}
sink()

Output.txt then looks like this:

9073050 1 15 1 10 1 4 16 7
9079078 18 19
9085376 22 14 23 14 24

And for completeness, if you also want to store it within R a list is probably the most convenient data structure:

lst <- list()
for (id in unique(df$name)){
  seq <- df[which(df$name == id), 'sequence']
  lst[[as.character(id)]] = seq
}

which yields

> lst
$`9073050`
[1]  1 15  1 10  1  4 16  7

$`9079078`
[1] 18 19

$`9085376`
[1] 22 14 23 14 24


问:
Styling django non-field errors on forms
If I look in Django's forms.py, as_p() calls _html_output(), which styles field errors with self.error_class() (although I can't locate the definition of that).

However, _html_output() does NOT style non_field_errors (a.k.a. top_errors in the code).

How does one style the non-field errors?  Cut and paste all of _html_output?

I am using Django 1.0.

答:
Can be done without complicating the template language. In Django 3 the non_field_errors list has classes "errorlist nonfield", so you can simply use CSS to style them:

In your CSS file:

```<code>.errorlist.nonfield {
    color: red;
}
</code>```

In your html template:

```<code>{{ form.as_p }}
</code>```

Body:
Can be done without complicating the template language. In Django 3 the non_field_errors list has classes "errorlist nonfield", so you can simply use CSS to style them:

In your CSS file:

.errorlist.nonfield {
    color: red;
}

In your html template:

{{ form.as_p }}


问:
localstorage values resetting after refresh and localstorage is not defined
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

```<code>"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

</code>```

Getting the object

```<code>export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}
</code>```

This is my function

```<code>//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

    <div className="grid grid-cols-3 rows-2 text-lg font-bold">
         {storage}

    </div>

<div className="grid grid-cols-3 grid-rows-2 gap-2 bg-black text-white border-white">
        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>

</code>```

答:
What you need to do first is setting the item in localstorage:

```<code>function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}
</code>```

now after you refresh the page you can retrieve it from the localstorage:

```<code>function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}
</code>```

That should be it. Also make sure you are not in inkognito mode on the browser, which might reset the storage on reloading the page.

To clarify furthermore your script would look something like this:

```<code>const myTestItem = 'test item';

function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}

setItem('test', myTestItem);

// after reload you can check wether it's there.
console.log(getItem('test')); // <-- just to log it to console, also u could check the application tab in chrome console and check the localstorage.
</code>```

React Example in codesandbox:

Codesandbox

regards

Body:
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

Getting the object

export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

This is my function

//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

         {storage}

        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>

Body:
What you need to do first is setting the item in localstorage:

function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

now after you refresh the page you can retrieve it from the localstorage:

function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}

That should be it. Also make sure you are not in inkognito mode on the browser, which might reset the storage on reloading the page.

To clarify furthermore your script would look something like this:

const myTestItem = 'test item';

function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}

setItem('test', myTestItem);

// after reload you can check wether it's there.
console.log(getItem('test')); // <-- just to log it to console, also u could check the application tab in chrome console and check the localstorage.

React Example in codesandbox:

Codesandbox

regards


问:
TypeError: The 'compilation' argument must be an instance of Compilation
for some reason I have to use angular-builders to custom webpack.

when I update webpack version to ^5.11.0 and I try to use terser-webpack-plugin to compressed code.

there some error throw out,but I dont know how to fix it.because I configuration with documentation.

npm run build error:

```<code>0% compiling
An error occurred during the build:
TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/webpack/lib/javascript/JavascriptModulesPlugin.js:119:10)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/terser-webpack-plugin/dist/index.js:566:67
    at SyncHook.eval [as call] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:85:1)
    at SyncHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.newCompilation (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:631:26)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:667:29
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.compile (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:662:28)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:321:11
    at Compiler.readRecords (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:529:11)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:318:10
    at eval (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/CachePlugin.js:50:13
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:7:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
An unhandled exception occurred: The 'compilation' argument must be an instance of Compilation
See "/private/var/folders/zj/qw9n84kj6hsb0011brv_8c5w0000gn/T/ng-NaStay/angular-errors.log" for further details.
npm ERR! code 127
npm ERR! path /Users/kuubee/Desktop/self_porject/fontend/ng-blog
npm ERR! command failed
npm ERR! command sh -c ng build --prod

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/kuubee/.npm/_logs/2020-12-28T05_51_41_395Z-debug.log
</code>```

my environment:

```<code>Angular CLI: 11.0.5
Node: 15.3.0
OS: darwin x64

Angular: 11.0.5
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1002.1
@angular-devkit/build-angular   0.1100.5
@angular-devkit/core            10.2.1
@angular-devkit/schematics      11.0.5
@angular/cdk                    11.0.3
@angular/flex-layout            11.0.0-beta.33
@angular/material               11.0.3
@schematics/angular             11.0.5
@schematics/update              0.1100.5
rxjs                            6.6.3
typescript                      4.0.5
webpack                         5.11.0
</code>```

webpack.prod.config.js:

const {
  merge
} = require('webpack-merge');
const base = require('./webpack.config')
// if I annotate this line everything is ok
const TerserPlugin = require("terser-webpack-plugin");
module.exports = merge(base, {
// and below block
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({
      cache: true,
      parallel: true
    })],
  },
})
```
<p>angular.json:</p>
<pre class="lang-json prettyprint-override"><code>{
...
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist/ng-blog",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.json",
            "aot": true,
            "styles": [],
            "scripts": []
          },
          "configurations": {
            "production": {
              "customWebpackConfig": {
                "path": "webpack.prod.config.js",
                "mergeStrategies": {
                  "optimization": "replace"
                },
                "replaceDuplicatePlugins": false
              },
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": false,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
            "development": {
              "customWebpackConfig": {
                "path": "webpack.dev.config.js",
                "replaceDuplicatePlugins": true
              }
            }
          }
        },
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "ng-blog:build:development"
          },
          "configurations": {
            "production": {
              "browserTarget": "ng-blog:build:production"
            },
            "development": {
              "browserTarget": "ng-blog:build:development"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ng-blog:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ng-blog:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ng-blog:serve:production"
            }
          }
        }
      }
...
}
</code>```

答:
I also encountered this error with webpack. I solved the problem by adding capital letters into the path to the directory in which the command is executed.

Let's take the following case:

I develop an application in the directory :

```<code>C:\Users\username\Desktop\myApp
</code>```

I compile the assets of this application with webpack. The Compilation type error is triggered if I execute the npm run dev command in c:\users\username\desktop\myapp because webpack can't find the node_modules folder. To fix the error you just have to run your command into the right directory with also capital letters.

```<code>C:\Users\username\Desktop\myApp> npm run dev
</code>```

Webpack should find the node_modules folder and you won't have any more errors.

Body:
for some reason I have to use angular-builders to custom webpack.

when I update webpack version to ^5.11.0 and I try to use terser-webpack-plugin to compressed code.

there some error throw out,but I dont know how to fix it.because I configuration with documentation.

npm run build error:

0% compiling
An error occurred during the build:
TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/webpack/lib/javascript/JavascriptModulesPlugin.js:119:10)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/terser-webpack-plugin/dist/index.js:566:67
    at SyncHook.eval [as call] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:85:1)
    at SyncHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.newCompilation (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:631:26)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:667:29
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.compile (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:662:28)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:321:11
    at Compiler.readRecords (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:529:11)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/Compiler.js:318:10
    at eval (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
    at /Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/webpack/lib/CachePlugin.js:50:13
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:7:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/kuubee/Desktop/self_porject/fontend/ng-blog/node_modules/@angular-builders/custom-webpack/node_modules/tapable/lib/Hook.js:154:20)
An unhandled exception occurred: The 'compilation' argument must be an instance of Compilation
See "/private/var/folders/zj/qw9n84kj6hsb0011brv_8c5w0000gn/T/ng-NaStay/angular-errors.log" for further details.
npm ERR! code 127
npm ERR! path /Users/kuubee/Desktop/self_porject/fontend/ng-blog
npm ERR! command failed
npm ERR! command sh -c ng build --prod

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/kuubee/.npm/_logs/2020-12-28T05_51_41_395Z-debug.log

my environment:

Angular CLI: 11.0.5
Node: 15.3.0
OS: darwin x64

Angular: 11.0.5
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1002.1
@angular-devkit/build-angular   0.1100.5
@angular-devkit/core            10.2.1
@angular-devkit/schematics      11.0.5
@angular/cdk                    11.0.3
@angular/flex-layout            11.0.0-beta.33
@angular/material               11.0.3
@schematics/angular             11.0.5
@schematics/update              0.1100.5
rxjs                            6.6.3
typescript                      4.0.5
webpack                         5.11.0

webpack.prod.config.js:

const {
  merge
} = require('webpack-merge');
const base = require('./webpack.config')
// if I annotate this line everything is ok
const TerserPlugin = require("terser-webpack-plugin");
module.exports = merge(base, {
// and below block
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({
      cache: true,
      parallel: true
    })],
  },
})

angular.json:

{
...
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist/ng-blog",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.json",
            "aot": true,
            "styles": [],
            "scripts": []
          },
          "configurations": {
            "production": {
              "customWebpackConfig": {
                "path": "webpack.prod.config.js",
                "mergeStrategies": {
                  "optimization": "replace"
                },
                "replaceDuplicatePlugins": false
              },
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": false,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
            "development": {
              "customWebpackConfig": {
                "path": "webpack.dev.config.js",
                "replaceDuplicatePlugins": true
              }
            }
          }
        },
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "ng-blog:build:development"
          },
          "configurations": {
            "production": {
              "browserTarget": "ng-blog:build:production"
            },
            "development": {
              "browserTarget": "ng-blog:build:development"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ng-blog:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ng-blog:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ng-blog:serve:production"
            }
          }
        }
      }
...
}

Body:
I also encountered this error with webpack. I solved the problem by adding capital letters into the path to the directory in which the command is executed.

Let's take the following case:

I develop an application in the directory :

C:\Users\username\Desktop\myApp

I compile the assets of this application with webpack. The Compilation type error is triggered if I execute the npm run dev command in c:\users\username\desktop\myapp because webpack can't find the node_modules folder. To fix the error you just have to run your command into the right directory with also capital letters.

C:\Users\username\Desktop\myApp> npm run dev

Webpack should find the node_modules folder and you won't have any more errors.


问:
Add my own class file in ASP.NET MVC, and it couldn't be referenced?
I am currently stuck trying to add my own class file into ASP.NET MVC project, so it could
be referenced by my controller. But Visual studio 2010 always complain about "The type or name 'Products' could not be found (are your missing a using directive or assembly reference?)

I am not sure where to put my class file and tried add the class to Models or Controllers directory, and it wouldn't work either. My the class is under the right namespace, and I did reference the Models namespace in my Controller. It could be something obvious, but I couldn't get it working:(

答:
Based on a comment to a different answer, it appears you're trying to add a utility or helper class.  I suggest you put it in a Helpers folder under the root of the project.

So first add the Helpers folder under the root of the project.  You should have the following structure when done (there may be other folders as well):

```<code>[project]
  - Content
  - Helpers
  - Controllers
  - Views
</code>```

Now, add a new class to the Helpers folder.  Call this class ProductsHelper (in the Add New Item dialog make sure to put ProductsHelper.cs, as it's asking for the file name).

Now have a look in the new ProductsHelper.cs file.  Copy the namespace found in said file, to be used in the controller.

Now, add a using directive at the top of your controller that looks like the following:

```<code>using [copied namespace];
</code>```

Sometimes projects are set up to use default namespaces that don't match the project name, in which case the namespace in your newly-added class file might be different than what you thought you should add as the using directive.  If you're wondering what the default namespace for your project is, you can see it in the project's properties, on the Application tab, in the "Default namespace" textbox (you can change it here as well).

Body:
Based on a comment to a different answer, it appears you're trying to add a utility or helper class.  I suggest you put it in a Helpers folder under the root of the project.

So first add the Helpers folder under the root of the project.  You should have the following structure when done (there may be other folders as well):

[project]
  - Content
  - Helpers
  - Controllers
  - Views

Now, add a new class to the Helpers folder.  Call this class ProductsHelper (in the Add New Item dialog make sure to put ProductsHelper.cs, as it's asking for the file name).

Now have a look in the new ProductsHelper.cs file.  Copy the namespace found in said file, to be used in the controller.

Now, add a using directive at the top of your controller that looks like the following:

using [copied namespace];

Sometimes projects are set up to use default namespaces that don't match the project name, in which case the namespace in your newly-added class file might be different than what you thought you should add as the using directive.  If you're wondering what the default namespace for your project is, you can see it in the project's properties, on the Application tab, in the "Default namespace" textbox (you can change it here as well).


问:
Truncate table with a trigger
I want to create a trigger that after insert on another table it truncates another and after that inserts the data from the first table into the truncated one. I have managed the insert part but i don't know how to incorporate the truncate command into the same trigger.</p>

```<code>CREATE OR REPLACE TRIGGER TEST_TRIGGER AFTER INSERT ON TEST

FOR EACH ROW
BEGIN

    INSERT INTO TEST2
       (col1, col2, col3)
    VALUES
       (:NEW.col1, :NEW.col2, :NEW.col3);
END;
</code>```

答:
```<code>CREATE OR REPLACE TRIGGER TEST_TRIGGER AFTER INSERT ON TEST

FOR EACH ROW
BEGIN
    DELETE FROM TEST2 WHERE true ;
    INSERT INTO TEST2
       (col1, col2, col3)
    VALUES
       (:NEW.col1, :NEW.col2, :NEW.col3);
END;
</code>```

Title: Truncate table with a trigger

Body:
I want to create a trigger that after insert on another table it truncates another and after that inserts the data from the first table into the truncated one. I have managed the insert part but i don't know how to incorporate the truncate command into the same trigger.

CREATE OR REPLACE TRIGGER TEST_TRIGGER AFTER INSERT ON TEST

FOR EACH ROW
BEGIN

    INSERT INTO TEST2
       (col1, col2, col3)
    VALUES
       (:NEW.col1, :NEW.col2, :NEW.col3);
END;