问:
How to show default values for text with onChange input?
I have an object that I'm passing to a state variable:

```<code>const values = [
value1:'value1',
value2:'value2',
value3:'value3',
value4:'value4'
]

const [inputValues,setInputValues] = useState(values)
</code>```

I am able to modify these values as well as display them e.g:

```<code><Text>{inputValues.value1}</Text>
<Input value={inputValues.value1} onChange={onChange} name={value1}/>
</code>```

The problem is when I'm resetting the values in the input to empty strings it will reset in the text as well, leaving it blank while the input values are changed. I currently have other state variables that will display the values separately for the text, but I don't see the point since I now have two values that does the same thing:

```<code>const [value1, setValue1] = useState()
</code>```

How can I modify the input values without affecting the text fields?

答:
You can't modify the inputValues without affecting the text fields, because both values are using the same variable, you are using the same state.

...

This would be an option if your Text were to show the default value only

const values = [
value1:'value1',
value2:'value2',
value3:'value3',
value4:'value4'
]

const [inputValues,setInputValues] = useState(values)
...
//this should be taken from your values, to be static. or from another state
<Text>{values.value1}</Text>
<Input value={inputValues.value1} onChange={onChange} name={value1}/>```

Body:
I have an object that I'm passing to a state variable:

const values = [
value1:'value1',
value2:'value2',
value3:'value3',
value4:'value4'
]

const [inputValues,setInputValues] = useState(values)

I am able to modify these values as well as display them e.g:

<Text>{inputValues.value1}</Text>
<Input value={inputValues.value1} onChange={onChange} name={value1}/>

The problem is when I'm resetting the values in the input to empty strings it will reset in the text as well, leaving it blank while the input values are changed. I currently have other state variables that will display the values separately for the text, but I don't see the point since I now have two values that does the same thing:

const [value1, setValue1] = useState()

How can I modify the input values without affecting the text fields?


来源: stackexchange

问:
unbuffered std streambuf implementation
for some quick testing of a serialization library I want to create a streambuf that can read/write to/from a socket. I do not want to use a buffer in the streambuf, but let the socket handle this. I am sure the serialization lib will only call std::istream::read and std::ostream::write. A quick look at Microsoft's basic_streambuf implementation shows that these calls are practically directly forwarded to xsputn and xsgetn.

The question is: can I derive from a streambuf and just implement xsputn and xsgetn, and be sure that the streams that use my implementation will always call these methods, and not sync/overflow/underflow/pback/... ? Or else should I override sync etc to return errors, or does the standard guarantee that the default implementations are fine? Preferrably this should work on any common platform, and I cannot use the boost::iostreams.

Practically I'd use something like this:

```<code>class socket_buf : public std::streambuf
{
public:
    //Socket is a class with std::stream-like read/write methods
  MyBuf( Socket& s ) : sock( s ) {}

protected:
  std::streamsize xsputn( const char* s, std::streamsize n )
  {
    return sock.write( s, n );
  }

  std::streamsize xsgetn( char* s, std::streamsize n )
  {
    return sock.read( s, n );
  }

private:
  Socket& sock;
};
</code>```

答: It's (almost?) impossible to implement a std::streambuf without a buffer. You will have to overload underflow and overflow as many of the public interfaces to std::streambuf won't go via xsputn or xsgetn. E.g. sputc, sbumpc, etc. Even sputn is not guaranteed to cause a call xsputn depending on the state of the internal buffer and the particular std::streambuf implementation.

ContentLicense: CC BY-SA 3.0

Title: unbuffered std streambuf implementation

Body:
for some quick testing of a serialization library I want to create a streambuf that can read/write to/from a socket. I do not want to use a buffer in the streambuf, but let the socket handle this. I am sure the serialization lib will only call std::istream::read and std::ostream::write. A quick look at Microsoft's basic_streambuf implementation shows that these calls are practically directly forwarded to xsputn and xsgetn.

The question is: can I derive from a streambuf and just implement xsputn and xsgetn, and be sure that the streams that use my implementation will always call these methods, and not sync/overflow/underflow/pback/... ? Or else should I override sync etc to return errors, or does the standard guarantee that the default implementations are fine? Preferrably this should work on any common platform, and I cannot use the boost::iostreams.

Practically I'd use something like this:

class socket_buf : public std::streambuf
{
public:
    //Socket is a class with std::stream-like read/write methods
  MyBuf( Socket& s ) : sock( s ) {}

protected:
  std::streamsize xsputn( const char* s, std::streamsize n )
  {
    return sock.write( s, n );
  }

  std::streamsize xsgetn( char* s, std::streamsize n )
  {
    return sock.read( s, n );
  }

private:
  Socket& sock;
};


问:
E2153 ';' not allowed before 'ELSE'
When I compile my schedule:

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  Speed: Double;
  myStringList: TStringList;
  b: array[0..512] of Char;
  Memory: tMemoryStatus;
  i : Integer;
begin
  Speed := GetCPUSpeed;

  myStringList := TStringList.Create;

  TIdStack.IncUsage;

  GetTempPath(511,b);

  memory.dwLength := sizeof(memory);

  GlobalMemoryStatus(memory);

  i := Languages.IndexOf(SysLocale.DefaultLCID);

  try
    myStringList.Add('IP: ' + GStack.LocalAddress);
  finally
    TIdStack.DecUsage;
  end;

  If waveOutGetNumDevs > 0 then myStringList.Add('Scheda Audio: Presente');

  else myStringList.Add('Scheda Audio: Assente');

  myStringList.Add('');

  Memo1.Lines.Assign(myStringList);

  myStringList.Free;
end;
</code>```

It gives me this error:

[DCC Error] Unit1.pas(198): E2153 ';' not allowed before 'ELSE'

on this line:

else myStringList.Add('Scheda Audio: Assente');
```

答:
This is covered in Delphi's documentation:

Declarations and Statements (Delphi): If Statements

Notice that a semicolon between the then clause and the word else is never used. You can place a semicolon after an entire if statement to separate it from the next statement in its block, but the then and else clauses require nothing more than a space or carriage return between them. Placing a semicolon immediately before else (in an if statement) is a common programming error.

Also related:

Declarations and Statements (Delphi): Compound_Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

begin
  Z := X;
  X := Y;
  X := Y;
end;
```
<p><strong>The last semicolon before <code>end</code> is optional.</strong> So this could have been written as:</p>
<pre class="lang-pascal prettyprint-override"><code>begin
  Z := X;
  X := Y;
  Y := Z
end;
</code>```

A common misconception for Delphi is that semicolon is a statement terminator.  In some languages, like C/C++, that is true.  But in Delphi, that is not true.  Semicolon is a statement separator instead.  There is a subtle difference.  You have to place a semicolon between consecutive statements, but you DO NOT need to place a semicolon at the end of a statement when it is the last statement in an enclosing block.

This is even mentioned in the documentation for the error message in question:

E2153 ';' not allowed before 'ELSE' (Delphi)

You have placed a ';' directly before an ELSE in an IF-ELSE statement. The reason for this is that the ';' is treated as a statement separator, not a statement terminator - IF-ELSE is one statement, a ';' cannot appear in the middle (unless you use compound statements).

...

The Delphi language does not allow a ';' to be placed directly before an ELSE statement. In the code above, an error will be flagged because of this fact.

...

There are two easy solutions to this problem. The first is to remove the offending ';'. The second is to create compound statements for each part of the IF-ELSE...

On a side note: you need to protect your TStringList with a try..finally block.  And the call to TIdStack.IncUsage() should be moved directly above the try of the finally that calls TIdStack.DecUsage().

Try something more like this:

procedure TForm1.FormCreate(Sender: TObject);
var
  Speed: Double;
  myStringList: TStringList;
  b: array[0..MAX_PATH] of Char;
  Memory: tMemoryStatus;
  i : Integer;
begin
  myStringList := TStringList.Create;
  try
    Speed := GetCPUSpeed;
    // add Speed to myStringList as needed...

    GetTempPath(MAX_PATH, b);
    // add b to myStringList as needed...

    memory.dwLength := sizeof(memory);
    GlobalMemoryStatus(memory);
    // add memory info to myStringList as needed...

    i := Languages.IndexOf(SysLocale.DefaultLCID);
    // add language info to myStringList as needed...

    TIdStack.IncUsage;
    try
      myStringList.Add('IP: ' + GStack.LocalAddress);
    finally
      TIdStack.DecUsage;
    end;

    if waveOutGetNumDevs > 0 then
      myStringList.Add('Scheda Audio: Presente')
    else
      myStringList.Add('Scheda Audio: Assente');

    myStringList.Add('');

    Memo1.Lines.Assign(myStringList);
  finally
    myStringList.Free;
  end;
end;
```

ContentLicense: CC BY-SA 4.0

Title: E2153 ';' not allowed before 'ELSE'

Body:
When I compile my schedule:

procedure TForm1.FormCreate(Sender: TObject);
var
  Speed: Double;
  myStringList: TStringList;
  b: array[0..512] of Char;
  Memory: tMemoryStatus;
  i : Integer;
begin
  Speed := GetCPUSpeed;

  myStringList := TStringList.Create;

  TIdStack.IncUsage;

  GetTempPath(511,b);

  memory.dwLength := sizeof(memory);

  GlobalMemoryStatus(memory);

  i := Languages.IndexOf(SysLocale.DefaultLCID);

  try
    myStringList.Add('IP: ' + GStack.LocalAddress);
  finally
    TIdStack.DecUsage;
  end;

  If waveOutGetNumDevs > 0 then myStringList.Add('Scheda Audio: Presente');

  else myStringList.Add('Scheda Audio: Assente');

  myStringList.Add('');

  Memo1.Lines.Assign(myStringList);

  myStringList.Free;
end;

It gives me this error:

[DCC Error] Unit1.pas(198): E2153 ';' not allowed before 'ELSE'

on this line:

else myStringList.Add('Scheda Audio: Assente');

Body:
This is covered in Delphi's documentation:

Declarations and Statements (Delphi): If Statements

Notice that a semicolon between the then clause and the word else is never used. You can place a semicolon after an entire if statement to separate it from the next statement in its block, but the then and else clauses require nothing more than a space or carriage return between them. Placing a semicolon immediately before else (in an if statement) is a common programming error.

Also related:

Declarations and Statements (Delphi): Compound_Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

begin
  Z := X;
  X := Y;
  X := Y;
end;

The last semicolon before end is optional. So this could have been written as:

begin
  Z := X;
  X := Y;
  Y := Z
end;

A common misconception for Delphi is that semicolon is a statement terminator.  In some languages, like C/C++, that is true.  But in Delphi, that is not true.  Semicolon is a statement separator instead.  There is a subtle difference.  You have to place a semicolon between consecutive statements, but you DO NOT need to place a semicolon at the end of a statement when it is the last statement in an enclosing block.

This is even mentioned in the documentation for the error message in question:

E2153 ';' not allowed before 'ELSE' (Delphi)

You have placed a ';' directly before an ELSE in an IF-ELSE statement. The reason for this is that the ';' is treated as a statement separator, not a statement terminator - IF-ELSE is one statement, a ';' cannot appear in the middle (unless you use compound statements).

...

The Delphi language does not allow a ';' to be placed directly before an ELSE statement. In the code above, an error will be flagged because of this fact.

...

There are two easy solutions to this problem. The first is to remove the offending ';'. The second is to create compound statements for each part of the IF-ELSE...

On a side note: you need to protect your TStringList with a try..finally block.  And the call to TIdStack.IncUsage() should be moved directly above the try of the finally that calls TIdStack.DecUsage().

Try something more like this:

procedure TForm1.FormCreate(Sender: TObject);
var
  Speed: Double;
  myStringList: TStringList;
  b: array[0..MAX_PATH] of Char;
  Memory: tMemoryStatus;
  i : Integer;
begin
  myStringList := TStringList.Create;
  try
    Speed := GetCPUSpeed;
    // add Speed to myStringList as needed...

    GetTempPath(MAX_PATH, b);
    // add b to myStringList as needed...

    memory.dwLength := sizeof(memory);
    GlobalMemoryStatus(memory);
    // add memory info to myStringList as needed...

    i := Languages.IndexOf(SysLocale.DefaultLCID);
    // add language info to myStringList as needed...

    TIdStack.IncUsage;
    try
      myStringList.Add('IP: ' + GStack.LocalAddress);
    finally
      TIdStack.DecUsage;
    end;

    if waveOutGetNumDevs > 0 then
      myStringList.Add('Scheda Audio: Presente')
    else
      myStringList.Add('Scheda Audio: Assente');

    myStringList.Add('');

    Memo1.Lines.Assign(myStringList);
  finally
    myStringList.Free;
  end;
end;


问:
Not using node.js : Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../"
i have this simple js sample which i test via visual studio code with live preview server build in:
i don't use node.js in this sample
all js files under js dir :

```<code>C:\Dev\my\javascript\ThreeJS\tests\js>ls -1
GLTFLoader.js
OrbitControls.js
main.js
three.js
three.min.js
three.module.js
</code>```

HTML:

but i keep getting this general error :

```<code>   Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".
</code>```

```<code><html>
    <head>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8" />
        <title>My first three.js app</title>
        <link href="main.css" rel="stylesheet" type="text/css">
        <script type="module" src="js/main.js"></script>
    </head>
    <body>
        <div id="scene-container">
            <canvas></canvas>
        </div>
    </body>
</html>
</code>```

in js/main.js

```<code>import {
  BoxBufferGeometry,
  Color,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
} from 'three';

// Get a reference to the container element that will hold our scene
const container = document.querySelector('#scene-container');

// create a Scene
const scene = new Scene();

// Set the background color
scene.background = new Color('skyblue');

// Create a camera
const fov = 35; // AKA Field of View
const aspect = container.clientWidth / container.clientHeight;
const near = 0.1; // the near clipping plane
const far = 100; // the far clipping plane

const camera = new PerspectiveCamera(fov, aspect, near, far);

// every object is initially created at ( 0, 0, 0 )
// move the camera back so we can view the scene
camera.position.set(0, 0, 10);

// create a geometry
const geometry = new BoxBufferGeometry(2, 2, 2);

// create a default (white) Basic material
const material = new MeshBasicMaterial();

// create a Mesh containing the geometry and material
const cube = new Mesh(geometry, material);

// add the mesh to the scene
scene.add(cube);

// create the renderer
const renderer = new WebGLRenderer();

// next, set the renderer to the same size as our container element
renderer.setSize(container.clientWidth, container.clientHeight);

// finally, set the pixel ratio so that our scene will look good on HiDPI displays
renderer.setPixelRatio(window.devicePixelRatio);

// add the automatically created <canvas> element to the page
container.append(renderer.domElement);

// render, or 'create a still image', of the scene
renderer.render(scene, camera);
</code>```

答:
Also since 26th of January this year three.js released r137 update and since r137 using ES6 modules like GLTFLoader in the browser requires an import map.

```<code><script type="importmap">
{
    "imports": {
        "three": "../master/three.js-master/build/three.module.js"
    }
}
</code>```

The three.js import statement in your scripts.js looks like so then:

```<code>import * as THREE from 'three'
</code>```

https://github.com/Kramzin/threejs-task - Here you can see updated and previous code, after these changes everything is working.

Body:
i have this simple js sample which i test via visual studio code with live preview server build in:
i don't use node.js in this sample
all js files under js dir :

C:\Dev\my\javascript\ThreeJS\tests\js>ls -1
GLTFLoader.js
OrbitControls.js
main.js
three.js
three.min.js
three.module.js

HTML:

but i keep getting this general error :

   Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8" />
        <title>My first three.js app</title>
        <link href="main.css" rel="stylesheet" type="text/css">

            <canvas></canvas>

in js/main.js

import {
  BoxBufferGeometry,
  Color,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  Scene,
  WebGLRenderer,
} from 'three';

// Get a reference to the container element that will hold our scene
const container = document.querySelector('#scene-container');

// create a Scene
const scene = new Scene();

// Set the background color
scene.background = new Color('skyblue');

// Create a camera
const fov = 35; // AKA Field of View
const aspect = container.clientWidth / container.clientHeight;
const near = 0.1; // the near clipping plane
const far = 100; // the far clipping plane

const camera = new PerspectiveCamera(fov, aspect, near, far);

// every object is initially created at ( 0, 0, 0 )
// move the camera back so we can view the scene
camera.position.set(0, 0, 10);

// create a geometry
const geometry = new BoxBufferGeometry(2, 2, 2);

// create a default (white) Basic material
const material = new MeshBasicMaterial();

// create a Mesh containing the geometry and material
const cube = new Mesh(geometry, material);

// add the mesh to the scene
scene.add(cube);

// create the renderer
const renderer = new WebGLRenderer();

// next, set the renderer to the same size as our container element
renderer.setSize(container.clientWidth, container.clientHeight);

// finally, set the pixel ratio so that our scene will look good on HiDPI displays
renderer.setPixelRatio(window.devicePixelRatio);

// add the automatically created <canvas> element to the page
container.append(renderer.domElement);

// render, or 'create a still image', of the scene
renderer.render(scene, camera);

Body:
Also since 26th of January this year three.js released r137 update and since r137 using ES6 modules like GLTFLoader in the browser requires an import map.

<script type="importmap">
{
    "imports": {
        "three": "../master/three.js-master/build/three.module.js"
    }
}

The three.js import statement in your scripts.js looks like so then:

import * as THREE from 'three'

https://github.com/Kramzin/threejs-task - Here you can see updated and previous code, after these changes everything is working.


问:
brownie-config remappings error when trying to import from chainlink
I am trying to import this code

```<code>import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
</code>```

but "Source "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" not found: File import callback not supported" error messages appear when i try to compile.

My brownie-config.yaml file has

```<code>dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@1.1.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'
</code>```

but the code still results in the same error. Are there any fixes to this?

答:
I solved it by doing: npm install @chainlink/contracts --save

and in the yaml file doing:

Body:
I am trying to import this code

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";

but "Source "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol" not found: File import callback not supported" error messages appear when i try to compile.

My brownie-config.yaml file has

dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@1.1.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'

but the code still results in the same error. Are there any fixes to this?


问:
"Websocket connection failed" when proxying requests to Next.js app via Apache server
Since upgrading to Next.js 12 I'm getting the following error in the console when I run my Next.js app:

WebSocket connection to 'wss://mysite.local/_next/webpack-hmr' failed

I've discovered that this is related with Next.js 12 using web sockets for HMR connection (unlike previous Next.js versions). In the guide to upgrading to Next.js 12, the docs provide the following snippet as a fix when using Nginx:

```<code>location /_next/webpack-hmr {
    proxy_pass http://localhost:3000/_next/webpack-hmr;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}
</code>```

However, I use Apache to proxy requests to my Next.js app and can't find an example on how to do this with Apache. I know very little about server configuration or web sockets, so I would appreciate some help in removing that annoying error.

I've searched around and tried a few things on my own, but had no success. Here's one attempt I've made (notice the rewrite rules at the bottom):

```<code><VirtualHost *:443>
   ServerName mysite.local
   DocumentRoot "/Users/grazianodev/Projects/mysite"
   SSLEngine On
   SSLCertificateFile "/Users/grazianodev/Projects/.crt/mysite.local.pem"
   SSLCertificateKeyFile "/Users/grazianodev/Projects/.crt/mysite.local-key.pem"
   ProxyPass / http://localhost:3000/
   ProxyPassReverse / http://localhost:3000/
   RewriteEngine on
   RewriteCond %{HTTP:Upgrade} websocket [NC]
   RewriteCond %{HTTP:Connection} upgrade [NC]
   RewriteRule ^/?(.*) "wss://mysite.local/$1" [P,L]
</VirtualHost>
</code>```

答:
You can try something like the following for Apache. You might have to tweak the ports and I haven't tested it:</p>
```<code><VirtualHost *:443>
   ServerName mysite.local
   DocumentRoot "/Users/grazianodev/Projects/mysite"
   SSLEngine On
   SSLCertificateFile "/Users/grazianodev/Projects/.crt/mysite.local.pem"
   SSLCertificateKeyFile "/Users/grazianodev/Projects/.crt/mysite.local-key.pem"
   ProxyPass / http://localhost:3000/
   ProxyPassReverse / http://localhost:3000/
   RewriteEngine on
   RewriteCond %{HTTP:Upgrade} websocket [NC]
   RewriteCond %{HTTP:Connection} upgrade [NC]

   ## Match webpack-hmr to mysite.local
   ProxyPreserveHost On
   ProxyPassMatch ^/(_next/webpack-hmr)$  wss://mysite.local/$1
</VirtualHost>
</code>```

Body:
Since upgrading to Next.js 12 I'm getting the following error in the console when I run my Next.js app:

WebSocket connection to 'wss://mysite.local/_next/webpack-hmr' failed

I've discovered that this is related with Next.js 12 using web sockets for HMR connection (unlike previous Next.js versions). In the guide to upgrading to Next.js 12, the docs provide the following snippet as a fix when using Nginx:

location /_next/webpack-hmr {
    proxy_pass http://localhost:3000/_next/webpack-hmr;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

However, I use Apache to proxy requests to my Next.js app and can't find an example on how to do this with Apache. I know very little about server configuration or web sockets, so I would appreciate some help in removing that annoying error.

I've searched around and tried a few things on my own, but had no success. Here's one attempt I've made (notice the rewrite rules at the bottom):

<VirtualHost *:443>
   ServerName mysite.local
   DocumentRoot "/Users/grazianodev/Projects/mysite"
   SSLEngine On
   SSLCertificateFile "/Users/grazianodev/Projects/.crt/mysite.local.pem"
   SSLCertificateKeyFile "/Users/grazianodev/Projects/.crt/mysite.local-key.pem"
   ProxyPass / http://localhost:3000/
   ProxyPassReverse / http://localhost:3000/
   RewriteEngine on
   RewriteCond %{HTTP:Upgrade} websocket [NC]
   RewriteCond %{HTTP:Connection} upgrade [NC]
   RewriteRule ^/?(.*) "wss://mysite.local/$1" [P,L]
</VirtualHost>

Body:
You can try something like the following for Apache. You might have to tweak the ports and I haven't tested it:

<VirtualHost *:443>
   ServerName mysite.local
   DocumentRoot "/Users/grazianodev/Projects/mysite"
   SSLEngine On
   SSLCertificateFile "/Users/grazianodev/Projects/.crt/mysite.local.pem"
   SSLCertificateKeyFile "/Users/grazianodev/Projects/.crt/mysite.local-key.pem"
   ProxyPass / http://localhost:3000/
   ProxyPassReverse / http://localhost:3000/
   RewriteEngine on
   RewriteCond %{HTTP:Upgrade} websocket [NC]
   RewriteCond %{HTTP:Connection} upgrade [NC]

   ## Match webpack-hmr to mysite.local
   ProxyPreserveHost On
   ProxyPassMatch ^/(_next/webpack-hmr)$  wss://mysite.local/$1
</VirtualHost>


问:
How to get the name of person by passing city property from array of JS object
I have this array of objects

```<code>const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
</code>```

I want to write a function when I pass paris, I want to get back chris, how to achieve this?

Here is what I have tried

```<code>const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val) == "city") {if (val.city == cityname) console.log(val.name)}})//nothing is printed
}

fetchname("paris");
</code>```

答:
You able to use filter

const arrofobj = [
  {city:"paris", name: "chris"},
  {city:"berlin", name: "john"},
  {city:"moscow", name: "jev"}
];

console.log(arrofobj.filter((arro) =>arro.city == 'paris')[0].name);```

Body:
I have this array of objects

const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

I want to write a function when I pass paris, I want to get back chris, how to achieve this?

Here is what I have tried

const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val) == "city") {if (val.city == cityname) console.log(val.name)}})//nothing is printed
}

fetchname("paris");


问:
Can I have two different input fields and one column in the database?
I want to have two input fields, but only one column in the database.
The first input is stored data in numbers and the other one is stored data in numbers divided by 24.
You can put data only in one field.
Is there any possible way to do this?

UPD:
Migration:

def change
  add_column :employees, :hourly_payment , :integer
end
```
<p>View:
employees/_form.html.erb</p>
```<%= simple_form_for @employee do |form| %>
  <%= form.input :name %>
  <%= form.input :hourly_payment %>
  <%= form.input :monthly_payment %>
  <%= form.button :submit, class: "btn btn-success" %>
<% end %>
```

答:
Your model and database tables are the internals of your application and are not actually tied to the view by anything except how easy ActiveRecord makes it to use convention over configuration to link the two*.

In Rails style MVC the controller is responsible for passing user input to the model. Usually you would just do this with simple mass assignment:

```<code>class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user)
          .permit(:email, :salary)
  end
end
</code>```

This is basically just passing a whitelisted hash of parameters straight to the model as is and it all gets passed to the setters that ActiveRecord magically created for you by reading the database schema.

But there is nothing stopping you from assigning attributes manually:

```<code>class UsersController < ApplicationController
  def create
    @user = User.new(user_params) do |user|
      user.salary = calculated_salary
    end
    # ...
  end

  private

  def user_params
    params.require(:user)
          .permit(:email)
  end

  def calculated_salary
     if params[:user][:hourly_payment].present?
       params[:user][:hourly_payment]
     elsif params[:user][:monthly_payment].present?
       params[:user][:monthly_payment].to_i / 168
     else
        0 # sorry no cookies for you
     end
  end
end
</code>```

Or monkeying with the parameters object:

```<code>def user_params
  params.require(:user)
        .permit(:email)
        .merge(salary: calculated_salary)
end
</code>```

It is after all just a hash on steroids. The only thing that Rails will prevent you from is passing a parameters object that has not been whitelisted.

There is no stone tablet for what you can do in a controller. The only thing to bear in mind is that controllers are notoriously hard to test and fat controllers are a recipe for disaster.

If you're doing anything more complicated there are better solutions such as form objects, decorators or service objects.

Body:
I want to have two input fields, but only one column in the database.
The first input is stored data in numbers and the other one is stored data in numbers divided by 24.
You can put data only in one field.
Is there any possible way to do this?

UPD:
Migration:

def change
  add_column :employees, :hourly_payment , :integer
end

View:
employees/_form.html.erb

<%= simple_form_for @employee do |form| %>
  <%= form.input :name %>
  <%= form.input :hourly_payment %>
  <%= form.input :monthly_payment %>
  <%= form.button :submit, class: "btn btn-success" %>
<% end %>

Body:
Your model and database tables are the internals of your application and are not actually tied to the view by anything except how easy ActiveRecord makes it to use convention over configuration to link the two*.

In Rails style MVC the controller is responsible for passing user input to the model. Usually you would just do this with simple mass assignment:

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user)
          .permit(:email, :salary)
  end
end

This is basically just passing a whitelisted hash of parameters straight to the model as is and it all gets passed to the setters that ActiveRecord magically created for you by reading the database schema.

But there is nothing stopping you from assigning attributes manually:

class UsersController < ApplicationController
  def create
    @user = User.new(user_params) do |user|
      user.salary = calculated_salary
    end
    # ...
  end

  private

  def user_params
    params.require(:user)
          .permit(:email)
  end

  def calculated_salary
     if params[:user][:hourly_payment].present?
       params[:user][:hourly_payment]
     elsif params[:user][:monthly_payment].present?
       params[:user][:monthly_payment].to_i / 168
     else
        0 # sorry no cookies for you
     end
  end
end

Or monkeying with the parameters object:

def user_params
  params.require(:user)
        .permit(:email)
        .merge(salary: calculated_salary)
end

It is after all just a hash on steroids. The only thing that Rails will prevent you from is passing a parameters object that has not been whitelisted.

There is no stone tablet for what you can do in a controller. The only thing to bear in mind is that controllers are notoriously hard to test and fat controllers are a recipe for disaster.

If you're doing anything more complicated there are better solutions such as form objects, decorators or service objects.


问:
Why is my submit event not being caught by jQuery in ASP.NET?
I wrote this on a simple ASP.NET page:

```<code>jQuery(document).ready(function() {
 jQuery("form").submit(function() {
   alert("kikoo");
   return false
  });
});
</code>```

and when I submit (by clicking on a button, link, ...), I never see the alert box.

Is there something in asp.net page that "bypass" the submit (I think about the dopostback javascript method)

Can anyone tell me why?

答:
Is it possible you are confused about the usage of the jQuery submit() function?

It sounds like you're expecting the alert dialog to happen on page load because you think the submit function is actually submitting your form.  But with the way you are using it, the submit() function is just attaching an event to your form so that when you actually do submit it, your function will run.

To actually trigger the submit from your code, you have to use submit() without any arguments like this:

```<code>$("form").submit();
</code>```

Here's an expanded example, using Mike C's answer as the basis:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $("form").submit(function() {
            alert("kikoo"); return false
        });
        // you could also chain this onto the end of the previous function
        $("form").submit();
    });
    </script>
</head>
<body>
    <form><input type="submit" /></form>
</body>
</html>
</code>```

OwnerDisplayName: Fatboss

ContentLicense: CC BY-SA 2.5

Body:
I wrote this on a simple ASP.NET page:

jQuery(document).ready(function() {
 jQuery("form").submit(function() {
   alert("kikoo");
   return false
  });
});

and when I submit (by clicking on a button, link, ...), I never see the alert box.

Is there something in asp.net page that "bypass" the submit (I think about the dopostback javascript method)

Can anyone tell me why?

LastEditorDisplayName: Fatboss

Body:
Is it possible you are confused about the usage of the jQuery submit() function?

It sounds like you're expecting the alert dialog to happen on page load because you think the submit function is actually submitting your form.  But with the way you are using it, the submit() function is just attaching an event to your form so that when you actually do submit it, your function will run.

To actually trigger the submit from your code, you have to use submit() without any arguments like this:

$("form").submit();

Here's an expanded example, using Mike C's answer as the basis:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $("form").submit(function() {
            alert("kikoo"); return false
        });
        // you could also chain this onto the end of the previous function
        $("form").submit();
    });
    </script>
</head>
<body>
    <form><input type="submit" /></form>
</body>
</html>

OwnerDisplayName: Ryan

LastEditorDisplayName: Ryan


问:
GCC and TC giving different outputs?
Consider the following code:

```<code>#include <stdio.h>

int main()
{
        printf("%d", 300 * 300 / 300);
        return 0;
}
</code>```

This code when run on a standard GCC compiler gives the result as 300 but when i run it using Turbo C, the result is 81. Why is it so?
I understand that TC uses 2 bytes for storing integers, and the result 300 * 300 would clearly exceed this limit, but before it is printed it is again divided with a 300 right?
And additionally what is computed first? 300 / 300 or 300 * 300?)
What is the reason for this behavior??

答:
In Turbo C, int is 16 bits wide. 300 * 300 = 90000 = 15F90h 15F90h will be truncated into 5F90h = 24464. If you divide 24464 with 300, you get 81 left.

In GCC int is typically 32 bits (not sure about GCC in DOS, and other exotic/outdated platforms). 32 bits are enough to hold 90000.

Title: GCC and TC giving different outputs?

Body:
Consider the following code:

#include <stdio.h>

int main()
{
        printf("%d", 300 * 300 / 300);
        return 0;
}

This code when run on a standard GCC compiler gives the result as 300 but when i run it using Turbo C, the result is 81. Why is it so?
I understand that TC uses 2 bytes for storing integers, and the result 300 * 300 would clearly exceed this limit, but before it is printed it is again divided with a 300 right?
And additionally what is computed first? 300 / 300 or 300 * 300?)
What is the reason for this behavior??


问:
Spark coalesce changing the order of unionAll
I have 2 data frames that I try to perform unionAll on.

DF3=DF1.unionAll(DF2)

DF3.coalesce(1).write.csv("/location")

DF1 always is placed under DF2 after coalesce and I see the reason is because the smaller partitions comes last as per this:
https://stackoverflow.com/a/59838761/3357735 .

Is there any way that we can have the same order as my union? is DF1 comes first and DF2 after coalesce.

答:
Did you try using row_number before coalesce?

```<code>from pyspark.sql import SparkSession, functions as F
from pyspark.sql.window import Window

DF3 = DF1.unionAll(DF2)\
    .withColumn("p", F.row_number().over(Window.orderBy(F.lit(None))))\
    .coalesce(1)\
    .orderBy(F.col("p"))\
    .drop("p")

DF3.write.csv("/location")
</code>```

I'm creating a new column called "p" and assigning an incremental number to each row using row_number and order By None (You can use any column name if you wish to order by that particular column)

After coalesce we are sorting the rows back to the initial order

dropping the column "p" before writing the csv

Body:
Did you try using row_number before coalesce?

from pyspark.sql import SparkSession, functions as F
from pyspark.sql.window import Window

DF3 = DF1.unionAll(DF2)\
    .withColumn("p", F.row_number().over(Window.orderBy(F.lit(None))))\
    .coalesce(1)\
    .orderBy(F.col("p"))\
    .drop("p")

DF3.write.csv("/location")

I'm creating a new column called "p" and assigning an incremental number to each row using row_number and order By None (You can use any column name if you wish to order by that particular column)

After coalesce we are sorting the rows back to the initial order

dropping the column "p" before writing the csv


问:
Minimum supported Gradle version is 6.1.1. Current version is 5.6.4
I'm facing this issue after updating to android studio 4.0 while Having older gradle version:

After that I have download the latest gradle version 6.4.1, after the complete download it give error of

```<code>Unable to find method
 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.
</code>```

Here is an image of error:

I already tried with invalid caches/Restart , Clean Project and rebuild project
and also deleted the cache folder but still facing the same issue,
now I can't use lower gradel.

答:
Go to gradle->wrapper->gradle-wrapper.properties
then change the version in the distribution url to whatever the error message says is minimum requirement</p>

Body:
I'm facing this issue after updating to android studio 4.0 while Having older gradle version:

After that I have download the latest gradle version 6.4.1, after the complete download it give error of

Unable to find method
 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

Here is an image of error:

I already tried with invalid caches/Restart , Clean Project and rebuild project
and also deleted the cache folder but still facing the same issue,
now I can't use lower gradel.


问:
Time spent on the game server
I'm trying to calculate the total time spent on the server by a Player.

I have a PHP cron job every 5 minutes that will query the details from the server  https://developer.valvesoftware.com/wiki/Server_queries

```<code>array (
  'id' => '1',
  'name' => 'Player',
  'score' => '3',
  'time' => '1234',
),
array (
  'id' => '2',
  'name' => 'Player 2',
  'score' => '12',
  'time' => '2453',
) + other 100k players.
// The 'time' is starting from 0 seconds when the player join the server, if she leave and then join again the time is starting from 0 seconds
</code>```

Just adding the live data to DB from the PHP Query

```<code>| id | name     | last_score | total_score | last_time | total_time |
| -- | -------- | ---------- | ----------- | --------- | ---------- |
| 1  | Player   | 3          | 0           | 1234      | 0          |
| 2  | Player 2 | 12         | 0           | 2453      | 0          |
</code>```

I'm not the owner of the servers where the players are online so i can't instantly LOG when the player leaves.

I'm trying to do something like this https://www.gametracker.com/server_info/109.120.135.78:2302/top_players/

答:
Solved!</p>
```<code>  $time = $query['Time'];
  $last = $db_players['last_time'];
  $total = $db_players['total_time'];

  if ($time < $last) {
    $total += $time;
  } else {
    $total += ($time - $last);
  }
</code>```

Title: Time spent on the game server

Body:
I'm trying to calculate the total time spent on the server by a Player.

I have a PHP cron job every 5 minutes that will query the details from the server  https://developer.valvesoftware.com/wiki/Server_queries

array (
  'id' => '1',
  'name' => 'Player',
  'score' => '3',
  'time' => '1234',
),
array (
  'id' => '2',
  'name' => 'Player 2',
  'score' => '12',
  'time' => '2453',
) + other 100k players.
// The 'time' is starting from 0 seconds when the player join the server, if she leave and then join again the time is starting from 0 seconds

Just adding the live data to DB from the PHP Query

| id | name     | last_score | total_score | last_time | total_time |
| -- | -------- | ---------- | ----------- | --------- | ---------- |
| 1  | Player   | 3          | 0           | 1234      | 0          |
| 2  | Player 2 | 12         | 0           | 2453      | 0          |

I'm not the owner of the servers where the players are online so i can't instantly LOG when the player leaves.

I'm trying to do something like this https://www.gametracker.com/server_info/109.120.135.78:2302/top_players/

Body:
Solved!

  $time = $query['Time'];
  $last = $db_players['last_time'];
  $total = $db_players['total_time'];

  if ($time < $last) {
    $total += $time;
  } else {
    $total += ($time - $last);
  }


问:
How to Manually Check for Duplicates in a 3x3 Array?
I am working on an assignment where I write a bool function that checks for duplicates in an array.

I want to see if any numbers between 1 and 9 appear more than once, then return true or a statement if they don't. However, I am stuck on going through the array and completing a check. How would I incorporate the array from my make_array() function into this.. the bool statement is supposed to check that function but no matter how I write it, it doesn't.

```<code>#include <iostream>
#include <ctime>
using namespace std;

int numbers[3][3] = {};

void make_array()
{
  for (int row = 0; row < 3; row++)
  {
    for (int column = 0; column < 3; column++)
    {
       numbers[row][column] = rand() % 9 + 1;
       cout << numbers[row][column] << " ";
    }
    cout << endl;
  }
}

bool appears_once()
{
    bool unique = true;

    for ( int copy_row = 0; copy_row < 3; copy_row++ )
    {
        for ( int copy_column = copy_row + 1; copy_column < 3; copy_column++ )
        {
            if (numbers[copy_row][copy_row] == numbers[ copy_column][ copy_column] )
            unique = true;
            cout << unique;
        }
    }

    return !unique;

}
int main()
{
  int row, column = 0;
  srand(time(0));
  make_array();
  appears_once();
}
</code>```

答:
This inner for loop

```<code>for (int ccolumn = check_row + 1; ccolumn < 3; ccolumn++)
{
  if (check_row != ccolumn)
  {
    return true;
  }
  else
  {
   return false;
  }

}
</code>```

does not make a sense. At least there are no comparisons of elements of the array.

The function can be defined for example the following way

```<code>bool appears_once()
{
    bool unique = true;

    for ( size_t i = 0; unique && i < 9; i++ )
    {
        for ( size_t j = i + 1; unique && j < 9; j++ )
        {
            if ( numbers[i / 3][i % 3] == numbers[ j / 3 ][ j % 3] ) unique = false;
        }
    }

    return unique;
}
</code>```

Body:
I am working on an assignment where I write a bool function that checks for duplicates in an array.

I want to see if any numbers between 1 and 9 appear more than once, then return true or a statement if they don't. However, I am stuck on going through the array and completing a check. How would I incorporate the array from my make_array() function into this.. the bool statement is supposed to check that function but no matter how I write it, it doesn't.

#include <iostream>
#include <ctime>
using namespace std;

int numbers[3][3] = {};

void make_array()
{
  for (int row = 0; row < 3; row++)
  {
    for (int column = 0; column < 3; column++)
    {
       numbers[row][column] = rand() % 9 + 1;
       cout << numbers[row][column] << " ";
    }
    cout << endl;
  }
}

bool appears_once()
{
    bool unique = true;

    for ( int copy_row = 0; copy_row < 3; copy_row++ )
    {
        for ( int copy_column = copy_row + 1; copy_column < 3; copy_column++ )
        {
            if (numbers[copy_row][copy_row] == numbers[ copy_column][ copy_column] )
            unique = true;
            cout << unique;
        }
    }

    return !unique;

}
int main()
{
  int row, column = 0;
  srand(time(0));
  make_array();
  appears_once();
}

Body:
This inner for loop

for (int ccolumn = check_row + 1; ccolumn < 3; ccolumn++)
{
  if (check_row != ccolumn)
  {
    return true;
  }
  else
  {
   return false;
  }

}

does not make a sense. At least there are no comparisons of elements of the array.

The function can be defined for example the following way

bool appears_once()
{
    bool unique = true;

    for ( size_t i = 0; unique && i < 9; i++ )
    {
        for ( size_t j = i + 1; unique && j < 9; j++ )
        {
            if ( numbers[i / 3][i % 3] == numbers[ j / 3 ][ j % 3] ) unique = false;
        }
    }

    return unique;
}


问:
How can I make overlay buttons that always stay over the same part of the picture that is under them?
I have an interesting issue or objective here. I have an image that is a yellow rectangle with 3 red rectangles in it. I'd like to add clickable buttons as an overlay on top of the picture, right over the red rectangles.

Thing is, I would like those buttons to always be exactly over each red rectangles, same size/position, no matter the aspect ratio of the pciture, the screen resolution of the user, or the zoom percentage of his browser (as if the buttons were part of the image)

As an example, I've included a picture where the yellow rectangles and the red rectangles are part of the same image, and the dotted green line would be the overlay buttons or their respective divs.

[Not enough reputation for picture, but here] : https://i.imgur.com/ms4xmMZ.png

MY HTML SO FAR

```<code><body>
    <div class="image-container">
        <img src="img/justelimage.png" alt="Nature" class="video" />

        <a href=“#”></a>

    </div>
</body>
</code>```

MY CSS SO FAR WORKS BUT THERE SHOULD BE A BETTER WAY ?
(works when I resize window, and change browser's zoom percentage, but what if we change the aspect ratio?)

```<code>
.image-container {
    display: inline-block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 80vw;
    height: auto;
    z-index:0;

}

.video {
    position: absolute;
    width: 100%;
    height: auto;
    z-index:1;

}

.image-container a{
    position: absolute;
    margin-top:4.5%;

    margin-left: 57%;
    width:28.3vw;
    height: 7vw;
    color:white;
    border: 0.25vw solid green;
    z-index: 999;

}

}

</code>```

Any idea how I could manage to get this in a more logical way?

Any suggestions would be gladly appreciated. Thanks!

答:
The best way to keep buttons in place with respective to an image will be to have the container as

position: relative;

and buttons inside the div as

position: absolute;

and placed top and left with px or any unit that doesn't change with size.

But one major thing you can do is have your image as the background of image-container.
That way buttons always stay on top of the image and u can restrict resizing of the container to make the buttons stay in position better.

I hope this helps.

.image-container {
position: relative;
  background-image: url("https://cdn.pixabay.com/photo/2014/12/28/13/20/wordpress-581849_960_720.jpg");
  background-size: contain;
  background-position: center;
  width: 600px;
  height:200px;
}
.btn{
width:20px;
height:20px;
background-color: green;
border:none;
position: absolute;
}
.one{
    top:10px;
    left:300px;
}
.two{
    top:100px;
    left:100px;
}
.three{
    top:50px;
    left:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="image-container">
<button href="#" class="btn one"></button>
<button href="#" class="btn two"></button>
<button href="#" class="btn three"></button>

</div>

</body>
</html></code>```

Body:
I have an interesting issue or objective here. I have an image that is a yellow rectangle with 3 red rectangles in it. I'd like to add clickable buttons as an overlay on top of the picture, right over the red rectangles.

Thing is, I would like those buttons to always be exactly over each red rectangles, same size/position, no matter the aspect ratio of the pciture, the screen resolution of the user, or the zoom percentage of his browser (as if the buttons were part of the image)

As an example, I've included a picture where the yellow rectangles and the red rectangles are part of the same image, and the dotted green line would be the overlay buttons or their respective divs.

[Not enough reputation for picture, but here] : https://i.imgur.com/ms4xmMZ.png

MY HTML SO FAR

MY CSS SO FAR WORKS BUT THERE SHOULD BE A BETTER WAY ?
(works when I resize window, and change browser's zoom percentage, but what if we change the aspect ratio?)

.image-container {
    display: inline-block;
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 80vw;
    height: auto;
    z-index:0;

}

.video {
    position: absolute;
    width: 100%;
    height: auto;
    z-index:1;

}

.image-container a{
    position: absolute;
    margin-top:4.5%;

    margin-left: 57%;
    width:28.3vw;
    height: 7vw;
    color:white;
    border: 0.25vw solid green;
    z-index: 999;

}

}

Any idea how I could manage to get this in a more logical way?

Any suggestions would be gladly appreciated. Thanks!

Body:
The best way to keep buttons in place with respective to an image will be to have the container as

position: relative;

and buttons inside the div as

position: absolute;

and placed top and left with px or any unit that doesn't change with size.

But one major thing you can do is have your image as the background of image-container.
That way buttons always stay on top of the image and u can restrict resizing of the container to make the buttons stay in position better.

I hope this helps.

.image-container {
position: relative;
  background-image: url("https://cdn.pixabay.com/photo/2014/12/28/13/20/wordpress-581849_960_720.jpg");
  background-size: contain;
  background-position: center;
  width: 600px;
  height:200px;
}
.btn{
width:20px;
height:20px;
background-color: green;
border:none;
position: absolute;
}
.one{
    top:10px;
    left:300px;
}
.two{
    top:100px;
    left:100px;
}
.three{
    top:50px;
    left:200px;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="image-container">
<button href="#" class="btn one"></button>
<button href="#" class="btn two"></button>
<button href="#" class="btn three"></button>

</div>

</body>
</html>


问:
How can I fix this Import problem with vsCode
I'm having a little problem. I would like to import bs4 and request on my vscode file but I can't in tells me that there is a missign module source. I tried to change the interpreter but when I do it only one of them is recognized. So if anyone knows how I can import both of them I would gradely appreciate, thanks.

The error message that I get

答:
Take a look at this post regarding the same subject. Also this guide could hold the answer to your problem.

You may have installed the libraries inside a virtual environment and you are using a python interpreter that is not inside the environment.

Edit: It could be that just one of your libraries is inside (or outside) the environment.


答:
you must use filter method as follow:

const arrofobj = [
    {city:"paris", name: "chris"},
    {city:"berlin", name: "john"},
    {city:"moscow", name: "jev"}
    ];

    function getByCity(city) {
        var result = arrofobj.filter(obj => {
            return obj.city === city
        })
        return result;
    }

    console.log(getByCity('paris')[0].name)```

Title: How to get the name of person by passing city property from array of JS object


问:
Host a Django project on Apache2 locally
I have finished a Django project and want to deploy it over Apache2 locally over LAN. I have figured out how to connect Django with Apache2 using mod_wsgi and it worked great because I was able to use Apace2 to actually host Django on localhost.
Now I want to actually make this project available to anyone on my local network. Like for instance assuming that my local IP address was 10.10.10.51 I could go to a different device connected to my local network and type in 10.10.10.51 to actually get to the Apache2 server homepage. It does that successfully.
My Django project is hosted on my Apache2 localhost server at djangoproject.localhost and it works fine just on my PC. When I move on to the other PC and go to djangoproject.localhost the site is not up there. Yes they are both connected to the same LAN network.
I used this tutorial to host Django on Apache2: Host Django on Apache2 with mod_wsgi</p>

答:
I suppose you are on windows ...
If you run your app on pc1 and want to call it from pc2, you need to call it either

via ip adress of pc1

via djangoproject.localhost

but then you need to edit the hosts file on pc2:

C:\Windows\System32\drivers\etc\hosts

and add something like  (x.x.x.x =  ip adress of pc1)

```<code>x.x.x.x  djangoproject.localhost
</code>```

because on pc2 your brwoser does not know what to do with djangoproject.localhost as in a LAN in general you do not have a local domain name server running.

If your firewall on pc1 blocks access to apache you need to got to "windows defender firewall" (type "defender" in search bar) and add a rule for apache application.

Body:
I suppose you are on windows ...
If you run your app on pc1 and want to call it from pc2, you need to call it either

via ip adress of pc1

via djangoproject.localhost

but then you need to edit the hosts file on pc2:

C:\Windows\System32\drivers\etc\hosts

and add something like  (x.x.x.x =  ip adress of pc1)

x.x.x.x  djangoproject.localhost

because on pc2 your brwoser does not know what to do with djangoproject.localhost as in a LAN in general you do not have a local domain name server running.

If your firewall on pc1 blocks access to apache you need to got to "windows defender firewall" (type "defender" in search bar) and add a rule for apache application.


问:
Get certain fields in document firestore flutter
I'm currently working on an application where users can create groups and invite others in it.
I would like people in the same group to be able to see their first and last names.
To do that, I have a collection named Users where each of the users have a document contains all their personnal data, like first and last names, phone, position , ...
I have also another collection named Groups, where all of my groups are stored, with their name, and an array contaning the ID of the members.

When an user open the app, a first request is done for request his groups (he recieve the groups names and the arrays of members). After, if he want to know the user in a certain group, another request is done for search only the first and last name of all the members.

So, I imagine that there is a query that will return me only the fields that I would like to retrieve, and that there is a rule allowing a potential hacker to be refused access to the entire user document except if the user is the owner of the document.

```<code>// For retrieving my user's groups
Stream<List<Group>?> get organizations {
  return firestore
    .collection('Groups')
    .where('members', arrayContains: this.uid)
    .snapshots()
    .map(_groupsFromSnapshot);
}
</code>```
```<code>// For retrieving names of the members of a group
Stream<List<Member>?> getMembers(Group group){
  return firestore
    .collection('Users')
    // and i dont know what to do here ...
}
</code>```

答:
With the Client SDKs and the Flutter plugin it is not possible to get only a subset of the fields of a Document. When you fetch a Document you get it with all its fields.

If you want to get only a subset of the fields of a document, you can implements the two following approaches:

Denormalize your data: You create another collection which contains documents that only contain the fields you want to expose. You need to synchronize the two collections (the Users collection, which is the "master", and the new collection): for that it's quite common to use a Cloud Function. Note also that it's a good idea to use the same documentID for the linked documents in the two collections.

Use the Firestore REST API to fetch the data: With the REST API you can use a DocumentMask when you fetch one document with the get method or a Projection when you query a Collection. The DocumentMask or the Projection will "restrict a get operation on a document to a subset of its fields". You can use the http package for calling the API from your Flutter app.

HOWEVER, the second approach is not valid if you want to protect the other users data: a malicious user could call the Firestore REST API with the same request but without a DocumentMask or a Projection. In other words, this approach is interesting if you just want to minimize the network traffic, not if you want to keep secret certain fields of a document.

So, for your specific use case, you need to go for the first solution.

Body:
I'm currently working on an application where users can create groups and invite others in it.
I would like people in the same group to be able to see their first and last names.
To do that, I have a collection named Users where each of the users have a document contains all their personnal data, like first and last names, phone, position , ...
I have also another collection named Groups, where all of my groups are stored, with their name, and an array contaning the ID of the members.

When an user open the app, a first request is done for request his groups (he recieve the groups names and the arrays of members). After, if he want to know the user in a certain group, another request is done for search only the first and last name of all the members.

So, I imagine that there is a query that will return me only the fields that I would like to retrieve, and that there is a rule allowing a potential hacker to be refused access to the entire user document except if the user is the owner of the document.

// For retrieving my user's groups
Stream<List<Group>?> get organizations {
  return firestore
    .collection('Groups')
    .where('members', arrayContains: this.uid)
    .snapshots()
    .map(_groupsFromSnapshot);
}

// For retrieving names of the members of a group
Stream<List<Member>?> getMembers(Group group){
  return firestore
    .collection('Users')
    // and i dont know what to do here ...
}


问:
Applescript or Automator: Run Acrobat X Pro to batch OCR multiple PDF files, more
I'm using a ScanSnap S1500M to scan all paper documents to the folder /PDF-scans/ – I'd like to use Adobe Acrobat X Professional to OCR the text.

I'd like to automate this process (daily):

open Acrobat X Pro

batch OCR process PDF files in /PDF-scans/, append "-OCR" to filename

after OCR, move files to /PDF-ocr/

delete original PDF files in /PDF-scans/

Should I use Automator?  Is there a script that can do this?  Does it have to be tied to iCal's repeating events?

Thank you.

答:
I would download PDFPen which allows you to ocr documents easily. Once you've done that, you can use this script:</p>

```<code>set the PDF_folder to "where:Ever:Your:PDF:folder:is:" as alias
set the OCR_folder to "/where/ever/you/want/the/new/folder/to/be" as POSIX file

tell application "Finder"
    repeat with this_PDF in (every item of the PDF_folder)
        my ocr(this_PDF)
    end repeat
end tell

on ocr(this_PDF)
    tell application "PDFpen"
        open this_PDF as alias
        tell document 1
            ocr --simple
            repeat while performing ocr
                delay 1
            end repeat
            delay 1
        end tell
        set this_PDF to (save document 1 in this_PDF)
        close document 1
    end tell
    tell application "Finder"
        if not exists OCR_folder then set the OCR_folder to (make new folder at (the OCR_folder as alias with properties {name:"ocr"})
        move this_PDF to the OCR_folder with replacing
    end tell
end ocr
</code>```

Body:
I would download PDFPen which allows you to ocr documents easily. Once you've done that, you can use this script:

set the PDF_folder to "where:Ever:Your:PDF:folder:is:" as alias
set the OCR_folder to "/where/ever/you/want/the/new/folder/to/be" as POSIX file

tell application "Finder"
    repeat with this_PDF in (every item of the PDF_folder)
        my ocr(this_PDF)
    end repeat
end tell

on ocr(this_PDF)
    tell application "PDFpen"
        open this_PDF as alias
        tell document 1
            ocr --simple
            repeat while performing ocr
                delay 1
            end repeat
            delay 1
        end tell
        set this_PDF to (save document 1 in this_PDF)
        close document 1
    end tell
    tell application "Finder"
        if not exists OCR_folder then set the OCR_folder to (make new folder at (the OCR_folder as alias with properties {name:"ocr"})
        move this_PDF to the OCR_folder with replacing
    end tell
end ocr


问:
How to count number of files in each directory?
I am able to list all the directories by

```<code>find ./ -type d
</code>```

I attempted to list the contents of each directory and count the number of files in each directory by using the following command

```<code>find ./ -type d | xargs ls -l | wc -l
</code>```

But this summed the total number of lines returned by

```<code>find ./ -type d | xargs ls -l
</code>```

Is there a way I can count the number of files in each directory?

答:
My answer is a little different, due to the options of find, you can actually be much more flexible. Just try:

```<code>find . -type f -printf "%h\n" | sort | uniq -c
</code>```

With the "%h" option to "-printf", find prints only the directory of the files it found. Then sort and count with "uniq -c". This prints the number of search result entries with the same directory, per directory.

Using further options on find, you can be much more flexible. For example, to get an overview how many files in which directory have been modified at a certain date, use:

```<code>find . -newermt "2022-01-01 00:00:00" -type f -printf "%TY-%Tm-%Td %h\n" | sort | uniq -c
</code>```

This finds all files that have been modified since 1. January 2022, prints (with "-printf") the modification date and the directory, then sorts and counts them. In this example, each line in the result has the number of files, the date of modification (without time), and the directory.

Note that "-printf" may not be available in all versions of find I think.

Body:
I am able to list all the directories by

find ./ -type d

I attempted to list the contents of each directory and count the number of files in each directory by using the following command

find ./ -type d | xargs ls -l | wc -l

But this summed the total number of lines returned by

find ./ -type d | xargs ls -l

Is there a way I can count the number of files in each directory?

Body:
My answer is a little different, due to the options of find, you can actually be much more flexible. Just try:

find . -type f -printf "%h\n" | sort | uniq -c

With the "%h" option to "-printf", find prints only the directory of the files it found. Then sort and count with "uniq -c". This prints the number of search result entries with the same directory, per directory.

Using further options on find, you can be much more flexible. For example, to get an overview how many files in which directory have been modified at a certain date, use:

find . -newermt "2022-01-01 00:00:00" -type f -printf "%TY-%Tm-%Td %h\n" | sort | uniq -c

This finds all files that have been modified since 1. January 2022, prints (with "-printf") the modification date and the directory, then sorts and counts them. In this example, each line in the result has the number of files, the date of modification (without time), and the directory.

Note that "-printf" may not be available in all versions of find I think.


问:
Can somebody review my RecyclerView adapter? Text watcher crashes after 4-5 changes in text
My textchanged listener is for updatestockdetail() is working very weirdly, it crashes after 4-5 times changing the text and it also shows the first item when i change the text for the third time. I believe i am ding something majorly wrong. If somebody could help me, would be very glad.

```<code>class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
    var _binding: UploadItemViewBinding? = null
    val binding get() = _binding!!

        override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerViewAdapterU.ViewHolder {

        val v =
            LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
        _binding = UploadItemViewBinding.bind(v)

        return ViewHolder(binding.root)
    }

    fun getUpdatedDetails(skucode:String,pos:Int){
       // val skuDetails:ArrayList<ModelClass>
        val call: Call<List<ModelClass>>? =
            ApiClient.instance?.myApi?.getfromsku(skucode)!!
        call!!.enqueue(object : Callback<List<ModelClass>?> {
            override fun onResponse(
                call: Call<List<ModelClass>?>,
                response: Response<List<ModelClass>?>
            ) {
                val skuDetails=response.body()
                if (!skuDetails.isNullOrEmpty()) {
                    val x=dataList[pos].sku_code
                    for (i in skuDetails.indices){
                        println(skuDetails[i].sku_code)
                        println(".........$pos")
                        if (skuDetails[i].sku_code!=x){
                            dataList.removeAt(pos)
                            dataList.add(pos,skuDetails[i])
                            notifyItemChanged(pos)
                        }
                    }
                }

            }

            override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
            }
        })

    }

    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {

        bindItems(dataList[position])
        holder.getStock()
      holder.updateStockDetail()

    }
    fun bindItems(data: ModelClass) {

        binding.apply {
            itemquant.text=data.item_quant
            uploadItemName.text = data.item_name
            uploadMfg.text = data.mfg
            skuStock.setText(data.item_stock.toString())
             skuCode.setText(data.sku_code)
        }

    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun getStock() {

            binding.skuStock.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun afterTextChanged(editable: Editable) {
                    if (binding.skuStock.isFocused){
                    for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
                        if (editable.toString().trim()!=""){
                            var x= editable.toString().trim().toInt()

                            RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
                            //getting current itemstock before pushing update.
                            //assigning latest itemstock to the data for the update
                        }
                    }
                }}

            })
        }

        fun updateStockDetail(){
            binding.skuCode.addTextChangedListener(object : TextWatcher{
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                }
                override fun afterTextChanged(editable: Editable) {
                    binding.skuCode.removeTextChangedListener(this)
                    var pos:Int=adapterPosition
                    var x= editable.toString().trim()

                    //RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
                    println("$x in textwatcher and $pos")

                    //getting edited text and calling the function to get updated details.

                    getUpdatedDetails(x,pos)
                   binding.skuCode.addTextChangedListener(this)

                }
            })

        }

    }
}
</code>```

Before anyone asks, ob.dataselected comes from another rcv adapter. There is a issue in notifyitemchanged(pos) in getupdateddetails() which is called from updateStockDetail().

答:
```<code>binding.skuCode.addTextChangedListener(this)
</code>```

above code is causing the loop. You have to get rid of this line.

Body:
My textchanged listener is for updatestockdetail() is working very weirdly, it crashes after 4-5 times changing the text and it also shows the first item when i change the text for the third time. I believe i am ding something majorly wrong. If somebody could help me, would be very glad.

class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
    var _binding: UploadItemViewBinding? = null
    val binding get() = _binding!!

        override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerViewAdapterU.ViewHolder {

        val v =
            LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
        _binding = UploadItemViewBinding.bind(v)

        return ViewHolder(binding.root)
    }

    fun getUpdatedDetails(skucode:String,pos:Int){
       // val skuDetails:ArrayList<ModelClass>
        val call: Call<List<ModelClass>>? =
            ApiClient.instance?.myApi?.getfromsku(skucode)!!
        call!!.enqueue(object : Callback<List<ModelClass>?> {
            override fun onResponse(
                call: Call<List<ModelClass>?>,
                response: Response<List<ModelClass>?>
            ) {
                val skuDetails=response.body()
                if (!skuDetails.isNullOrEmpty()) {
                    val x=dataList[pos].sku_code
                    for (i in skuDetails.indices){
                        println(skuDetails[i].sku_code)
                        println(".........$pos")
                        if (skuDetails[i].sku_code!=x){
                            dataList.removeAt(pos)
                            dataList.add(pos,skuDetails[i])
                            notifyItemChanged(pos)
                        }
                    }
                }

            }

            override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
            }
        })

    }

    override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {

        bindItems(dataList[position])
        holder.getStock()
      holder.updateStockDetail()

    }
    fun bindItems(data: ModelClass) {

        binding.apply {
            itemquant.text=data.item_quant
            uploadItemName.text = data.item_name
            uploadMfg.text = data.mfg
            skuStock.setText(data.item_stock.toString())
             skuCode.setText(data.sku_code)
        }

    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun getStock() {

            binding.skuStock.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun afterTextChanged(editable: Editable) {
                    if (binding.skuStock.isFocused){
                    for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
                        if (editable.toString().trim()!=""){
                            var x= editable.toString().trim().toInt()

                            RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
                            //getting current itemstock before pushing update.
                            //assigning latest itemstock to the data for the update
                        }
                    }
                }}

            })
        }

        fun updateStockDetail(){
            binding.skuCode.addTextChangedListener(object : TextWatcher{
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                }
                override fun afterTextChanged(editable: Editable) {
                    binding.skuCode.removeTextChangedListener(this)
                    var pos:Int=adapterPosition
                    var x= editable.toString().trim()

                    //RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
                    println("$x in textwatcher and $pos")

                    //getting edited text and calling the function to get updated details.

                    getUpdatedDetails(x,pos)
                   binding.skuCode.addTextChangedListener(this)

                }
            })

        }

    }
}

Before anyone asks, ob.dataselected comes from another rcv adapter. There is a issue in notifyitemchanged(pos) in getupdateddetails() which is called from updateStockDetail().

Body:
binding.skuCode.addTextChangedListener(this)

above code is causing the loop. You have to get rid of this line.


问:
How to pass data to a text field - FLUTTER
```<code>**[![I want to achieve this, where a calculator input is shown to the user, and the user input and output of calculations is shown inside the text field
</code>```

Please give me suggestions how can I achieve this functionality... ]1]1**

答:
you can assign a controller to the text field and then you can change the text of that controller using the following statement</p>
```<code>_controller.text="Your Text goes here";
</code>```

Body:
**[![I want to achieve this, where a calculator input is shown to the user, and the user input and output of calculations is shown inside the text field

Please give me suggestions how can I achieve this functionality... ]1]1**

Body:
you can assign a controller to the text field and then you can change the text of that controller using the following statement

_controller.text="Your Text goes here";


问:
Crosstab and pivot on Snowflake
I have a table like so -

```<code>entity  category  cnt
324     Yankees   132
983     Orioles   323
</code>```

How do I return -

```<code>entity  yankees_cnt  orioles_cnt
324     132          NULL
983     NULL         323
</code>```

答:
This PIVOT SQL does what you have asked:

```<code>WITH data(entity,  category,  cnt) AS (
    select * FROM VALUES
    (324     ,'Yankees',   132 ),
    (983     ,'Orioles',   323 )
)
SELECT *
FROM data
PIVOT ( SUM ( cnt ) FOR category IN ( 'Yankees', 'Orioles' ))
     AS p (entity  , yankees_cnt,  orioles_cnt);
</code>```

gives:

ENTITY
YANKEES_CNT
ORIOLES_CNT

324
132

983

323

Title: Crosstab and pivot on Snowflake

Body:
I have a table like so -

entity  category  cnt
324     Yankees   132
983     Orioles   323

How do I return -

entity  yankees_cnt  orioles_cnt
324     132          NULL
983     NULL         323

Body:
This PIVOT SQL does what you have asked:

WITH data(entity,  category,  cnt) AS (
    select * FROM VALUES
    (324     ,'Yankees',   132 ),
    (983     ,'Orioles',   323 )
)
SELECT *
FROM data
PIVOT ( SUM ( cnt ) FOR category IN ( 'Yankees', 'Orioles' ))
     AS p (entity  , yankees_cnt,  orioles_cnt);

gives:

ENTITY
YANKEES_CNT
ORIOLES_CNT

324
132

983

323


问:
Jest :TypeError: (intermediate value) is not iterable
I have 2 methods below.

searchCertificates() is a private method which is called inside findAll().

```<code>   async findAll(queryCertificateDto: QueryCertificateDto): Promise<PaginatedResult> {
        const { data, meta } = await this.searchCertificates(queryCertificateDto);

        return {
            data,
            meta,
        };
    }

    private async searchCertificates(
        queryCertificateDto: QueryCertificateDto
    ): Promise<PaginatedResult> {
        const {
            page,
            take,
            certificateNo,
            startDate,
            endDate,
        } = queryCertificateDto;

        const query = this.certificateRepository.createQueryBuilder('certificate');

        if (certificateNo) {
            query.andWhere('certificate.certificateNo=:certificateNo', { certificateNo });
        }
        if (startDate && endDate) {
            query.andWhere('CAST(certificate.createdAt as Date) BETWEEN :startDate AND :endDate', {
                startDate,
                endDate,
            });
        } else if (startDate) {
            query.andWhere('CAST(certificate.startDate as Date)=:startDate', { startDate });
        } else if (endDate) {
            query.andWhere('CAST(certificate.endDate as Date)=:endDate', { endDate });
        }

        const [certificates, total] = await query
            .orderBy('certificate.certificateNo', 'ASC')
            .take(take)
            .skip((page - 1) * take)
            .getManyAndCount();

        return {
            data: certificates,
            meta: {
                total,
                page,
                last_page: Math.ceil(total / take),
            },
        };
    }
</code>```

I wrote below test case to cover startDate.

```<code>useValue: {
                        find: jest.fn().mockReturnValue(certificate),
                        createQueryBuilder: jest.fn(() => ({
                            andWhere: jest.fn().mockReturnValue(certificate),
                            getManyAndCount: jest.fn().mockReturnValueOnce(certificate),
                            orderBy: jest.fn().mockReturnThis(),
                            take: jest.fn().mockReturnThis(),
                            skip: jest.fn().mockReturnThis(),
                            page: jest.fn().mockReturnThis(),
                        })),
                        findOne: jest.fn().mockReturnValue(certificate),
                        save: jest.fn().mockReturnValue(new Certificate()),
                        softRemove: jest.fn().mockReturnValue(new Certificate()),
                    },
</code>```

Below is the test case.

```<code>  it('return the Certificate list for start date', async () => {
        const queryCertificateDto = new QueryCertificateDto();
        queryCertificateDto.startDate = '23-MAR-2019';
        const result = await service.findAll(queryCertificateDto);
        expect(result['startDate']).toEqual(certificate.startDate);
    });
</code>```

It is getting failing.

I don't know even the reason for it. Could you please help me to understand?

答: Your getManyAndCount mock should return a resolved value, and be mockResolvedValueOnce so that it can be awaited. It hsould also return an array of values, as you deconstruct the array into two parts, the certificates and the total

Body:
I have 2 methods below.

searchCertificates() is a private method which is called inside findAll().

   async findAll(queryCertificateDto: QueryCertificateDto): Promise<PaginatedResult> {
        const { data, meta } = await this.searchCertificates(queryCertificateDto);

        return {
            data,
            meta,
        };
    }

    private async searchCertificates(
        queryCertificateDto: QueryCertificateDto
    ): Promise<PaginatedResult> {
        const {
            page,
            take,
            certificateNo,
            startDate,
            endDate,
        } = queryCertificateDto;

        const query = this.certificateRepository.createQueryBuilder('certificate');

        if (certificateNo) {
            query.andWhere('certificate.certificateNo=:certificateNo', { certificateNo });
        }
        if (startDate && endDate) {
            query.andWhere('CAST(certificate.createdAt as Date) BETWEEN :startDate AND :endDate', {
                startDate,
                endDate,
            });
        } else if (startDate) {
            query.andWhere('CAST(certificate.startDate as Date)=:startDate', { startDate });
        } else if (endDate) {
            query.andWhere('CAST(certificate.endDate as Date)=:endDate', { endDate });
        }

        const [certificates, total] = await query
            .orderBy('certificate.certificateNo', 'ASC')
            .take(take)
            .skip((page - 1) * take)
            .getManyAndCount();

        return {
            data: certificates,
            meta: {
                total,
                page,
                last_page: Math.ceil(total / take),
            },
        };
    }

I wrote below test case to cover startDate.

useValue: {
                        find: jest.fn().mockReturnValue(certificate),
                        createQueryBuilder: jest.fn(() => ({
                            andWhere: jest.fn().mockReturnValue(certificate),
                            getManyAndCount: jest.fn().mockReturnValueOnce(certificate),
                            orderBy: jest.fn().mockReturnThis(),
                            take: jest.fn().mockReturnThis(),
                            skip: jest.fn().mockReturnThis(),
                            page: jest.fn().mockReturnThis(),
                        })),
                        findOne: jest.fn().mockReturnValue(certificate),
                        save: jest.fn().mockReturnValue(new Certificate()),
                        softRemove: jest.fn().mockReturnValue(new Certificate()),
                    },

Below is the test case.

  it('return the Certificate list for start date', async () => {
        const queryCertificateDto = new QueryCertificateDto();
        queryCertificateDto.startDate = '23-MAR-2019';
        const result = await service.findAll(queryCertificateDto);
        expect(result['startDate']).toEqual(certificate.startDate);
    });

It is getting failing.

I don't know even the reason for it. Could you please help me to understand?


问:
How to fix error "cannot run C compiled programs" when using ASAN
Issue: running configure scripts work fine, the C compiler can be used and the generated programs run. As soon as ASAN is added the configure script complains that the generated programs cannot run.

```<code>./configure
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
...
</code>```

vs.

```<code>./configure CFLAGS="-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -fstack-protector" LDFLAGS="-fsanitize=undefined -fsanitize=address" --enable-debug
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether CFLAGS can be modified... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... configure: error: in `/tmp/test-asan':
configure: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details
</code>```

config.log shows:

```<code>configure:3653: checking whether we are cross compiling
configure:3661: gcc -o conftest -fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -fstack-protector  -fsanitize=undefined -fsanitize=address conftest.c  >&5
configure:3665: $? = 0
configure:3672: ./conftest
==9941==LeakSanitizer has encountered a fatal error.
==9941==HINT: For debugging, try setting environment variable LSAN_OPTIONS=verbosity=1:log_threads=1
==9941==HINT: LeakSanitizer does not work under ptrace (strace, gdb, etc)
configure:3676: $? = 1
configure:3683: error: in `/tmp/test-asan':
configure:3685: error: cannot run C compiled programs.
</code>```

答: I ran into the same issue when using "podman build" ("docker build" works). Adding ptrace as a capability is probably doable. But another workaround is to set ASAN_OPTIONS=detect_leaks=0 (during ./configure and make test in my case).

Body:
Issue: running configure scripts work fine, the C compiler can be used and the generated programs run. As soon as ASAN is added the configure script complains that the generated programs cannot run.

./configure
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
...

vs.

./configure CFLAGS="-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -fstack-protector" LDFLAGS="-fsanitize=undefined -fsanitize=address" --enable-debug
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether CFLAGS can be modified... yes
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... configure: error: in `/tmp/test-asan':
configure: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details

config.log shows:

configure:3653: checking whether we are cross compiling
configure:3661: gcc -o conftest -fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer -fstack-protector  -fsanitize=undefined -fsanitize=address conftest.c  >&5
configure:3665: $? = 0
configure:3672: ./conftest
==9941==LeakSanitizer has encountered a fatal error.
==9941==HINT: For debugging, try setting environment variable LSAN_OPTIONS=verbosity=1:log_threads=1
==9941==HINT: LeakSanitizer does not work under ptrace (strace, gdb, etc)
configure:3676: $? = 1
configure:3683: error: in `/tmp/test-asan':
configure:3685: error: cannot run C compiled programs.


问:
How to copy python from one stage to another during a multi-stage docker build
I'm using nvidia/cudagl:11.4.2-base-ubuntu20.04, which does not include python. This is ok for me, since I need a very specific python version (3.9.9) anyhow. One way should be to compile python myself (e.g. according to https://askubuntu.com/a/890959). However, I thought maybe I could use a multi-stage build and just copy the required python executables from python:3.9.9-slim, so that I don't have to deal with the compilation and its remnants.

Is that a feasible idea? And what exactly would need to be copied over?

答:
As David Maze pointed out, it is apparently not a good idea to copy over a Python install. Unfortunately, the popular deadsnakes repository that he suggested, does not supply patch versions of Python, i.e. only the latest patch of Python 3.9 (at the time of writing 3.9.10) and not previous versions like 3.9.9.

I found that pyenv is a pretty convenient way to install a specific Python version (originally posted here):

```<code>FROM ubuntu:16.04

ENV PYTHON_VERSION 2.7.10

#Set of all dependencies needed for pyenv to work on Ubuntu systems
RUN apt-get update \
        && apt-get install -y --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget ca-certificates curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev mecab-ipadic-utf8 git

# Set-up necessary Env vars for PyEnv
ENV PYENV_ROOT /root/.pyenv
ENV PATH $PYENV_ROOT/shims:$PYENV_ROOT/bin:$PATH

# Install pyenv
RUN set -ex \
    && curl https://pyenv.run | bash \
    && pyenv update \
    && pyenv install $PYTHON_VERSION \
    && pyenv global $PYTHON_VERSION \
    && pyenv rehash

# Optional : Checks Pyenv version on container start-up
ENTRYPOINT [ "pyenv","version" ]
</code>```

Body:
As David Maze pointed out, it is apparently not a good idea to copy over a Python install. Unfortunately, the popular deadsnakes repository that he suggested, does not supply patch versions of Python, i.e. only the latest patch of Python 3.9 (at the time of writing 3.9.10) and not previous versions like 3.9.9.

I found that pyenv is a pretty convenient way to install a specific Python version (originally posted here):

FROM ubuntu:16.04

ENV PYTHON_VERSION 2.7.10

#Set of all dependencies needed for pyenv to work on Ubuntu systems
RUN apt-get update \
        && apt-get install -y --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget ca-certificates curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev mecab-ipadic-utf8 git

# Set-up necessary Env vars for PyEnv
ENV PYENV_ROOT /root/.pyenv
ENV PATH $PYENV_ROOT/shims:$PYENV_ROOT/bin:$PATH

# Install pyenv
RUN set -ex \
    && curl https://pyenv.run | bash \
    && pyenv update \
    && pyenv install $PYTHON_VERSION \
    && pyenv global $PYTHON_VERSION \
    && pyenv rehash

# Optional : Checks Pyenv version on container start-up
ENTRYPOINT [ "pyenv","version" ]


问:
How to get the name of person by passing city property from array of JS object
I have this array of objects

```<code>const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
</code>```

I want to write a function when I pass paris, I want to get back chris, how to achieve this?

Here is what I have tried

```<code>const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val) == "city") {if (val.city == cityname) console.log(val.name)}})//nothing is printed
}

fetchname("paris");
</code>```

答:
I made one little change to your code that you provided and it works fine now

```<code>const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val)[0] == "city") {if (val.city
== cityname) console.log(val.name)}})//works fine now
}

fetchname("paris");
</code>```

Object.keys returns an array of keys of the object city key is at first index hence [0] since you used object.keys and were comparing it without [0] it was comparing the array object hence getting false and not printing

Body:
I have this array of objects

const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

I want to write a function when I pass paris, I want to get back chris, how to achieve this?

Here is what I have tried

const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val) == "city") {if (val.city == cityname) console.log(val.name)}})//nothing is printed
}

fetchname("paris");

Body:
I made one little change to your code that you provided and it works fine now

const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];

function fetchname(cityname) {
  arrofobj.forEach((val)=>{if(Object.keys(val)[0] == "city") {if (val.city
== cityname) console.log(val.name)}})//works fine now
}

fetchname("paris");

Object.keys returns an array of keys of the object city key is at first index hence [0] since you used object.keys and were comparing it without [0] it was comparing the array object hence getting false and not printing


问:
How to limit the time vehicles are in scenario and make vehicles leave automatically?
I'm implementing some attacks in veins and using Sumo I made a map and added all the 120(120 vehicles but during the simulation totally 30 vehicles must be in the map at the same time) vehicles I need, the problem is that all the vehicles are inserted but not departed at all. I want to have some sort of lifetime for vehicles and each stay for around 15 seconds. I would appreciate if someone help me with this problem.

Bests

答:
http://www.grc.upv.es/Software/oldsw/vacamobil.html

The above link has a solution for your scenario.  The work tries to keep the number of cars a constant value during the simulation. meanNumberOfCars is the parameter to look at.