问:
Check if tab exists in TabControl c#
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

```<code>private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}
</code>```

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

答:
This is a better way:</p>
```<code>if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    VulnTab = new TabPage("Vulnerability");
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}
</code>```

Title: Check if tab exists in TabControl c#

Body:
I want to dynamically change the Tabs in a Tab Control depending on what options the user selects.

I have followed the example here TabControl.TabPageCollection.Contains Method (TabPage)

My code is as follows;

private TabPage VulnTab;

VulnTab = new TabPage("Vulnerability");
if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}

This is fired on a button click.

On the first run, there is no VulnTab so it creates one successfully. However, on re-clicking the button it creates a new one again, and so on.

I want it to note on the 2nd button click that the tab page already exists and just go there.

How can I achieve this?

Body:
This is a better way:

if (tabControl1.TabPages.Contains(VulnTab) == true)
{
    tabControl1.SelectedTab = VulnTab;
}
else
{
    VulnTab = new TabPage("Vulnerability");
    tabControl1.TabPages.Add(VulnTab);

    tabControl1.SelectedTab = VulnTab;
    var vuln = new vulnerability();
    tabControl1.SelectedTab.Controls.Add(vuln);
}


来源: stackexchange

问:
R STM Topic Proportion table
I'm trying to make a table for my STM model just like this.

I am new to R programming language and STM.

I have been searching in the documentation about this and do not know
if there is a function that makes just like this format
or if I have to manually make it like this.

Can I get some example on how to make a table like this and where can I get
Topic Proportions in % and if the topic has Appeared in Literate or not?

答:
As for expected topic proportion tables, the STM packages gives you a few options. For example, once you've generated your stm topic model object, you can pass the model through plot.STM(mod, type = "summary", main = "title") where mod is your stored model object, summary is the default table that this function generates, showing the expected proportion of the text corpus that belongs to a given topic (STM package, Roberts et al., 2018), and main = "title" is simply an optional command you can use to  label your figure. Alternatively, you can also pass your stored topic model through plot(mod, type = "summary") for a similar result.

As for extracting the exact % expected proportion by topic, I've had a similar question myself. Below is a custom workaround that I've recently implemented using the make.dt function from STM which outputs topic proportions by document.

# custom proportion extraction  proportions_table <- make.dt(mod)  summarize_all(proportions_table, mean)

ContentLicense: CC BY-SA 4.0

Title: R STM Topic Proportion table


问:
Saving And Loading Entire Scenes In Unity C#
I am making a game where you can build stuff while playing, im trying to figure out how to save a entire scene and load it, like with a json file or saving data of blocks placed in  a array with playerprefs. thanks</p>

答: You ideally want to place all of the data you are looking to save into a struct, then save via JSON. You can then read the JSON and then reinstate what was build previously.</p>


问:
Why does the converted image seem laggy when it is moving?
I was trying to create a simple pygame game that uses sprites, but when i compiled the code the movement seemed to have some kind of lag spikes. I did some debugging and extracted the problem into the code below. The image moves smoothly for most of a second, but then a lag spike occurs and so on.
I've seen that converting images helped a lot of people, but nothing changed for me.</p>
```<code>import pygame, sys

class Game():
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((1280, 720))
        pygame.display.set_caption("Spaceshooter")
        self.clock = pygame.time.Clock()
        self.image = pygame.image.load("player.png").convert_alpha()
        self.rect = self.image.get_rect()

    def run(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            self.screen.fill("black")
            self.rect.x += 5
            self.screen.blit(self.image, self.rect)
            self.clock.tick(60)
            pygame.display.update()

if __name__ == "__main__":
    game = Game()
    game.run()
</code>```

答: Try to reduce the movement speed and increase the fps. I believe it will help you, Adam.</p>

Body:
I was trying to create a simple pygame game that uses sprites, but when i compiled the code the movement seemed to have some kind of lag spikes. I did some debugging and extracted the problem into the code below. The image moves smoothly for most of a second, but then a lag spike occurs and so on.
I've seen that converting images helped a lot of people, but nothing changed for me.

import pygame, sys

class Game():
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((1280, 720))
        pygame.display.set_caption("Spaceshooter")
        self.clock = pygame.time.Clock()
        self.image = pygame.image.load("player.png").convert_alpha()
        self.rect = self.image.get_rect()

    def run(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            self.screen.fill("black")
            self.rect.x += 5
            self.screen.blit(self.image, self.rect)
            self.clock.tick(60)
            pygame.display.update()

if __name__ == "__main__":
    game = Game()
    game.run()


问:
Getting com.android.volley.ServerError using the Volley library. What are some possible causes?
When I make a request in Volley, I'm receiving com.android.volley.ServerError and response code 400.

I'm doing something like this (generic example code):

final String param1 = "...";
final String param2 = "...";
// etc.

StringRequest stringRequest = new StringRequest(Request.Method.POST, API_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("PARAM_1", param1);
        params.put("PARAM_2",password);
        return params;
    }

};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
```

What are possible causes for this?

答: Double check your parameters (there should be no null parameter). If it's ok then If you are using JSONObjectRequest then remove Request.Method.GET as per new google policy.

Body:
When I make a request in Volley, I'm receiving com.android.volley.ServerError and response code 400.

I'm doing something like this (generic example code):

final String param1 = "...";
final String param2 = "...";
// etc.

StringRequest stringRequest = new StringRequest(Request.Method.POST, API_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("PARAM_1", param1);
        params.put("PARAM_2",password);
        return params;
    }

};

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

What are possible causes for this?


问:
DOM input .value returns null using getElementById in function
index.html

<!DOCTYPE html>

    <input id="LinkInput" type="text">
    <button id="Add">Add Link</button>

```
<p>main.js</p>
<pre class="lang-js prettyprint-override"><code>document.addEventListener("DOMContentLoaded", (event) => {
    document.getElementById("Add").addEventListener("click", addLink);
});

var addLink = function () {
    let link = document.getElementById("LinkInput").value;
    console.log("link is " + link);
}
</code>```

Paste a link into the input element and then click the button. The following is printed to the console.

```<code>link is null
</code>```

If I instead console.log the return of 'document.getElementById("LinkInput")', this is returned:

```<code><input id="LinkInput" type="text">
</code>```

Browser-Sync version 2.27.7 is being used to serve the files. The CLI command used was:

browser-sync start --server --directory --files "*/**"
```

Question

Based on this w3schools js example, .value should return the value typed into the <input> instead of null. Why does it not?

答:
The problem originates with browser-sync, not the code or the browser.

Run

```<code>npm update browser-sync
</code>```

and then try again.

Body:
index.html

<!DOCTYPE html>

    <input id="LinkInput" type="text">
    <button id="Add">Add Link</button>

main.js

document.addEventListener("DOMContentLoaded", (event) => {
    document.getElementById("Add").addEventListener("click", addLink);
});

var addLink = function () {
    let link = document.getElementById("LinkInput").value;
    console.log("link is " + link);
}

Paste a link into the input element and then click the button. The following is printed to the console.

link is null

If I instead console.log the return of 'document.getElementById("LinkInput")', this is returned:

<input id="LinkInput" type="text">

Browser-Sync version 2.27.7 is being used to serve the files. The CLI command used was:

browser-sync start --server --directory --files "*/**"

Question

Based on this w3schools js example, .value should return the value typed into the <input> instead of null. Why does it not?

Body:
The problem originates with browser-sync, not the code or the browser.

Run

npm update browser-sync

and then try again.


问:
Error: While updating laravel 8 to 9. Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Nothing to install, update or remove
Generating optimized autoload files
Class App\Helpers\Helper located in C:/wamp64/www/vuexylaravel/app\Helpers\helpers.php does not comply
with psr-4 autoloading standard. Skipping.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

```<code>   Error

  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
     45▕      *
     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
     47▕      */
  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
     49▕
     50▕ ];
     51▕

  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
      require()

  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
</code>```

答:
If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware.

Within your app/Http/Middleware/TrustProxies.php file, update:

use Fideloper\Proxy\TrustProxies as Middleware

to

use Illuminate\Http\Middleware\TrustProxies as Middleware

Next, within app/Http/Middleware/TrustProxies.php, you should update the $headers property definition:

// Before...

```<code>protected $headers = Request::HEADER_X_FORWARDED_ALL;
</code>```

// After...

```<code>protected $headers =
    Request::HEADER_X_FORWARDED_FOR |
    Request::HEADER_X_FORWARDED_HOST |
    Request::HEADER_X_FORWARDED_PORT |
    Request::HEADER_X_FORWARDED_PROTO |
    Request::HEADER_X_FORWARDED_AWS_ELB;
</code>```

Then run composer update

Make sure you are using PHP 8.0

Body:
Nothing to install, update or remove
Generating optimized autoload files
Class App\Helpers\Helper located in C:/wamp64/www/vuexylaravel/app\Helpers\helpers.php does not comply
with psr-4 autoloading standard. Skipping.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   Error

  Undefined constant Illuminate\Http\Request::HEADER_X_FORWARDED_ALL
  at C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php:48
     44▕      * - 'HEADER_X_FORWARDED_AWS_ELB' (If you are using AWS Elastic Load Balancer)
     45▕      *
     46▕      * @link https://symfony.com/doc/current/deployment/proxies.html
     47▕      */
  ➜  48▕     'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
     49▕
     50▕ ];
     51▕

  1   C:\wamp64\www\vuexylaravel\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:138
      require()

  2   C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\src\TrustedProxyServiceProvider.php:28
      Illuminate\Support\ServiceProvider::mergeConfigFrom("C:\wamp64\www\vuexylaravel\vendor\fideloper\proxy\config\trustedproxy.php", "trustedproxy")
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Body:
If you are upgrading your Laravel 8 project to Laravel 9 by importing your existing application code into a totally new Laravel 9 application skeleton, you may need to update your application's "trusted proxy" middleware.

Within your app/Http/Middleware/TrustProxies.php file, update:

use Fideloper\Proxy\TrustProxies as Middleware

to

use Illuminate\Http\Middleware\TrustProxies as Middleware

Next, within app/Http/Middleware/TrustProxies.php, you should update the $headers property definition:

// Before...

protected $headers = Request::HEADER_X_FORWARDED_ALL;

// After...

protected $headers =
    Request::HEADER_X_FORWARDED_FOR |
    Request::HEADER_X_FORWARDED_HOST |
    Request::HEADER_X_FORWARDED_PORT |
    Request::HEADER_X_FORWARDED_PROTO |
    Request::HEADER_X_FORWARDED_AWS_ELB;

Then run composer update

Make sure you are using PHP 8.0


问:
Get http in Flask
I am starter to python and using Python Flask and generating REST API service.

I want to check authorization header which is sent the client.

But I can't find way to get HTTP header in flask.

Any help for getting HTTP header authorization is appreciated.

答:
If we are talking about using basic HTTP Auth then you can get the username and password with Flask like this:

```<code>from flask import request

@app.route('/route')
def route():
    username = request.authorization.username
    password = request.authorization.password
    ...
</code>```

Be advised: there are some security concerns when using basic HTTP Auth

Title: Get http in Flask

Body:
If we are talking about using basic HTTP Auth then you can get the username and password with Flask like this:

from flask import request

@app.route('/route')
def route():
    username = request.authorization.username
    password = request.authorization.password
    ...

Be advised: there are some security concerns when using basic HTTP Auth


问:
Visual Studio 2022 - missing references - template engine
screenshot

Hello,

I would like to write a script for Rhinoceros 3d, and therefore I need to download extension "RhinoCommon and Grasshopper templates for Rhino7".

But I can't, because of the missing references: Microsoft Visual Studio Template Engine. Take a look at screenshot in attachment.

How can I fix it?

答:
You may need to install the Visual Studio SDK based on the VSIX Documentation:

To use VSIX projects, you must install the Visual Studio SDK. For more information about the Visual Studio SDK, see Visual Studio SDK.

VSIX Documetnation. See VS SDK install instructions here.

This may be a result of an oversight by McNeal based on comments received by a developer who had similar errors being reported by some users but not most. This service forum:

You listed “Microsoft Visual Studio Template Engine” as a dependency. A dependency is the notion that your extension depends on another extension to be installed, and “Microsoft Visual Studio Template Engine” is not an extension. Are you perhaps trying to list it as a prerequisite? Prerequisites indicate which VS components need to be installed in order to support your extension.


问:
ng-material-multilevel-menu ERROR NullInjectorError: No provider for MultilevelMenuService. Angular 12
I am using angular 12 and want to implement the ng-material-multilevel-menu, I followed this link to implement the multilevel menu.

It complied successfully but still showing error in the browser.

By doing some google I found that adding ɵb in the app.module.ts will solve the problem but it didn't work out in my case.

Error that I am getting:

```<code>ERROR NullInjectorError: R3InjectorError(AppModule)[MultilevelMenuService -> MultilevelMenuService -> MultilevelMenuService]:
  NullInjectorError: No provider for MultilevelMenuService!
</code>```

app.html

```<code><ng-material-multilevel-menu [configuration]='config' [items]='appitems' (selectedItem)="selectedItem($event)">
</ng-material-multilevel-menu>
</code>```

app.component.ts

```<code>  appitems = [
    {
      label: 'Item 1 (with Font awesome icon)',
      faIcon: 'fab fa-500px',
      items: [
        {
          label: 'Item 1.1',
          link: '/item-1-1',
          faIcon: 'fab fa-accusoft'
        },
        {
          label: 'Item 1.2',
          faIcon: 'fab fa-accessible-icon',
          items: [
            {
              label: 'Item 1.2.1',
              link: '/item-1-2-1',
              faIcon: 'fas fa-allergies'
            },
            {
              label: 'Item 1.2.2',
              faIcon: 'fas fa-ambulance',
              items: [
                {
                  label: 'Item 1.2.2.1',
                  link: 'item-1-2-2-1',
                  faIcon: 'fas fa-anchor'
                }
              ]
            }
          ]
        }
      ]
    },
    {
      label: 'Item 2',
      icon: 'alarm',
      items: [
        {
          label: 'Item 2.1',
          link: '/item-2-1',
          icon: 'favorite'
        },
        {
          label: 'Item 2.2',
          link: '/item-2-2',
          icon: 'favorite_border'
        }
      ]
    },
    {
      label: 'Item 3',
      link: '/item-3',
      icon: 'offline_pin'
    },
    {
      label: 'Item 4',
      link: '/item-4',
      icon: 'star_rate',
      hidden: true
    }
  ];

  config = {
    paddingAtStart: true,
    classname: 'my-custom-class',
    listBackgroundColor: 'rgb(208, 241, 239)',
    fontColor: 'rgb(8, 54, 71)',
    backgroundColor: 'rgb(208, 241, 239)',
    selectedListFontColor: 'red',
  };

ngOnInit() {}

selectedItem($event:any) {
  console.log($event);
}
</code>```

package.json

```<code> "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.13",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "jquery": "^3.6.0",
    "ng-material-multilevel-menu": "^5.5.3",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
</code>```

app.module.ts

```<code>import { NgMaterialMultilevelMenuModule,ɵb } from 'ng-material-multilevel-menu';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
     .....
    NgMaterialMultilevelMenuModule
  ],
  providers: [ɵb],
</code>```

So is this some dependency issue or some version. Also if this cannot be implemented in the angular-12 so is there any other library for angular-12 that work like this so that I can implement the multi level dropdown in angular.

答:
Provide the service in providers. https://angular.io/guide/dependency-injection-providers#specifying-a-provider-token Also in the link you provided I don't see a reason to import/provide ɵb, may want to remove that.

@NgModule({
  declarations: [
    ...
  ],
  imports: [
     .....
    NgMaterialMultilevelMenuModule
  ],
  providers: [ɵb, NgMaterialMultilevelMenuModule],
```

Body:
I am using angular 12 and want to implement the ng-material-multilevel-menu, I followed this link to implement the multilevel menu.

It complied successfully but still showing error in the browser.

By doing some google I found that adding ɵb in the app.module.ts will solve the problem but it didn't work out in my case.

Error that I am getting:

ERROR NullInjectorError: R3InjectorError(AppModule)[MultilevelMenuService -> MultilevelMenuService -> MultilevelMenuService]:
  NullInjectorError: No provider for MultilevelMenuService!

app.html

<ng-material-multilevel-menu [configuration]='config' [items]='appitems' (selectedItem)="selectedItem($event)">
</ng-material-multilevel-menu>

app.component.ts

  appitems = [
    {
      label: 'Item 1 (with Font awesome icon)',
      faIcon: 'fab fa-500px',
      items: [
        {
          label: 'Item 1.1',
          link: '/item-1-1',
          faIcon: 'fab fa-accusoft'
        },
        {
          label: 'Item 1.2',
          faIcon: 'fab fa-accessible-icon',
          items: [
            {
              label: 'Item 1.2.1',
              link: '/item-1-2-1',
              faIcon: 'fas fa-allergies'
            },
            {
              label: 'Item 1.2.2',
              faIcon: 'fas fa-ambulance',
              items: [
                {
                  label: 'Item 1.2.2.1',
                  link: 'item-1-2-2-1',
                  faIcon: 'fas fa-anchor'
                }
              ]
            }
          ]
        }
      ]
    },
    {
      label: 'Item 2',
      icon: 'alarm',
      items: [
        {
          label: 'Item 2.1',
          link: '/item-2-1',
          icon: 'favorite'
        },
        {
          label: 'Item 2.2',
          link: '/item-2-2',
          icon: 'favorite_border'
        }
      ]
    },
    {
      label: 'Item 3',
      link: '/item-3',
      icon: 'offline_pin'
    },
    {
      label: 'Item 4',
      link: '/item-4',
      icon: 'star_rate',
      hidden: true
    }
  ];

  config = {
    paddingAtStart: true,
    classname: 'my-custom-class',
    listBackgroundColor: 'rgb(208, 241, 239)',
    fontColor: 'rgb(8, 54, 71)',
    backgroundColor: 'rgb(208, 241, 239)',
    selectedListFontColor: 'red',
  };

ngOnInit() {}

selectedItem($event:any) {
  console.log($event);
}

package.json

 "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.13",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "jquery": "^3.6.0",
    "ng-material-multilevel-menu": "^5.5.3",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },

app.module.ts

import { NgMaterialMultilevelMenuModule,ɵb } from 'ng-material-multilevel-menu';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
     .....
    NgMaterialMultilevelMenuModule
  ],
  providers: [ɵb],

So is this some dependency issue or some version. Also if this cannot be implemented in the angular-12 so is there any other library for angular-12 that work like this so that I can implement the multi level dropdown in angular.


问:
Can I set a variable amount of memory for SLURM jobs?
I am on a school server, where we have a login node, and several GPU nodes that can be accessed with SLURM. Specifically, I am running several jobs on a machine with 512 GB RAM, 64 CPUS, and 8 GPUs.

I want to train a large deep-learning model with a ton of text. After some trial and error, it seems I need 100 GB of RAM to load all the text data (12 GB batch file on disk) successfully, before training starts. However, while training, it only uses about 30 GB of RAM. I want to run several versions of this model, so I can only do up to 5 before running out of RAM to allocate.

Is there a way to have SLURM use a variable amount of RAM? I don't want to hog up too many resources unnecessarily. This are the SBATCH directives I am currently using:

```<code>#SBATCH --mem-per-cpu=20G
#SBATCH --cpus-per-task=5
#SBATCH --nodelist=gpu-large
#SBATCH --gpus=1
</code>```

I currently have 3 jobs running, and this is what I see from free:

```<code>              total        used        free      shared  buff/cache   available
Mem:          503Gi        94Gi       246Gi       1.6Gi       161Gi       403Gi
Swap:         4.0Gi        96Mi       3.9Gi
</code>```

So my jobs indeed only are using 30 GB each. Help would be greatly appreciated!

答:
Disclaimer: the following is from memory, I have no access to a slurm cluster ATM to check that.

You should be able to update the memory requirement of the job after it started. AFAIR, as a simple user (as opposed to a slurm admin or root), you can only lower the limits, not increase them (to prevent highjacking priority or ressources). Say, if your job has a memory-intensive step0 followed by a less intensive step1, you could try something like the following:

# Memory intensive part
step0
# Lower ressource reservation
scontrol update JobId=$SLURM_JOBID MinMemoryCPU=6G
# Less intensive step
step1
```

Some general info there: https://slurm.schedmd.com/scontrol.html

Body:
I am on a school server, where we have a login node, and several GPU nodes that can be accessed with SLURM. Specifically, I am running several jobs on a machine with 512 GB RAM, 64 CPUS, and 8 GPUs.

I want to train a large deep-learning model with a ton of text. After some trial and error, it seems I need 100 GB of RAM to load all the text data (12 GB batch file on disk) successfully, before training starts. However, while training, it only uses about 30 GB of RAM. I want to run several versions of this model, so I can only do up to 5 before running out of RAM to allocate.

Is there a way to have SLURM use a variable amount of RAM? I don't want to hog up too many resources unnecessarily. This are the SBATCH directives I am currently using:

#SBATCH --mem-per-cpu=20G
#SBATCH --cpus-per-task=5
#SBATCH --nodelist=gpu-large
#SBATCH --gpus=1

I currently have 3 jobs running, and this is what I see from free:

              total        used        free      shared  buff/cache   available
Mem:          503Gi        94Gi       246Gi       1.6Gi       161Gi       403Gi
Swap:         4.0Gi        96Mi       3.9Gi

So my jobs indeed only are using 30 GB each. Help would be greatly appreciated!

Body:
Disclaimer: the following is from memory, I have no access to a slurm cluster ATM to check that.

You should be able to update the memory requirement of the job after it started. AFAIR, as a simple user (as opposed to a slurm admin or root), you can only lower the limits, not increase them (to prevent highjacking priority or ressources). Say, if your job has a memory-intensive step0 followed by a less intensive step1, you could try something like the following:

# Memory intensive part
step0
# Lower ressource reservation
scontrol update JobId=$SLURM_JOBID MinMemoryCPU=6G
# Less intensive step
step1

Some general info there: https://slurm.schedmd.com/scontrol.html


问:
Cannot find module 'sequelize/types/lib/hooks' or its corresponding type declarations
Getting this error while building:

```<code>node_modules/sequelize-typescript/dist/hooks/shared/hook-meta.d.ts:2:32 - error TS2307: Cannot find module 'sequelize/types/lib/hooks' or its corresponding type declarations.

2 import { SequelizeHooks } from 'sequelize/types/lib/hooks';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/sequelize-typescript/dist/hooks/shared/hooks-service.d.ts:4:32 - error TS2307: Cannot find module 'sequelize/types/lib/hooks' or its corresponding type declarations.

4 import { SequelizeHooks } from 'sequelize/types/lib/hooks';

</code>```

Package.json

```<code>  "dependencies": {
    "@types/cors": "^2.8.12",
    "@types/nodemailer": "^6.4.4",
    "@types/sequelize": "^4.28.11",
    "ajv": "^8.8.2",
    "bcrypt": "^5.0.1",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "errorhandler": "^1.5.1",
    "express": "^4.17.1",
    "express-handlebars": "^6.0.2",
    "jsonwebtoken": "^8.5.1",
    "nodemailer": "^6.7.2",
    "pg": "^8.7.1",
    "reflect-metadata": "^0.1.13",
    "sequelize": "^6.11.0",
    "sequelize-cli": "^6.3.0",
    "sequelize-typescript": "^2.1.1"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/errorhandler": "^1.5.0",
    "@types/express": "^4.17.13",
    "@types/jsonwebtoken": "^8.5.6",
    "@types/node": "^16.11.11",
    "@types/validator": "^13.7.0",
    "@typescript-eslint/eslint-plugin": "^5.5.0",
    "@typescript-eslint/parser": "^5.5.0",
    "eslint": "^8.3.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "nodemon": "^2.0.15",
    "prettier": "^2.5.0",
    "typescript": "^4.5.2"
  }
</code>```

I have tried upgrading version of sequelize, sequelize-cli and sequelize-typescript to latest one, but it is still not working.

Please do let me know, where I am doing it wrong.

答:
In your *.model.ts files, replace

import { HookReturn } from 'sequelize/types/lib/hooks';

by

import { HookReturn } from 'sequelize/types/hooks';

Body:
Getting this error while building:

node_modules/sequelize-typescript/dist/hooks/shared/hook-meta.d.ts:2:32 - error TS2307: Cannot find module 'sequelize/types/lib/hooks' or its corresponding type declarations.

2 import { SequelizeHooks } from 'sequelize/types/lib/hooks';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/sequelize-typescript/dist/hooks/shared/hooks-service.d.ts:4:32 - error TS2307: Cannot find module 'sequelize/types/lib/hooks' or its corresponding type declarations.

4 import { SequelizeHooks } from 'sequelize/types/lib/hooks';

Package.json

  "dependencies": {
    "@types/cors": "^2.8.12",
    "@types/nodemailer": "^6.4.4",
    "@types/sequelize": "^4.28.11",
    "ajv": "^8.8.2",
    "bcrypt": "^5.0.1",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "errorhandler": "^1.5.1",
    "express": "^4.17.1",
    "express-handlebars": "^6.0.2",
    "jsonwebtoken": "^8.5.1",
    "nodemailer": "^6.7.2",
    "pg": "^8.7.1",
    "reflect-metadata": "^0.1.13",
    "sequelize": "^6.11.0",
    "sequelize-cli": "^6.3.0",
    "sequelize-typescript": "^2.1.1"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/errorhandler": "^1.5.0",
    "@types/express": "^4.17.13",
    "@types/jsonwebtoken": "^8.5.6",
    "@types/node": "^16.11.11",
    "@types/validator": "^13.7.0",
    "@typescript-eslint/eslint-plugin": "^5.5.0",
    "@typescript-eslint/parser": "^5.5.0",
    "eslint": "^8.3.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "nodemon": "^2.0.15",
    "prettier": "^2.5.0",
    "typescript": "^4.5.2"
  }

I have tried upgrading version of sequelize, sequelize-cli and sequelize-typescript to latest one, but it is still not working.

Please do let me know, where I am doing it wrong.


问:
How to start ropemacs-mode automatically?
When I open a python file I have to manually start ropemacs-mode to get the key bindings each time. I tried adding something like this to automatically start ropemacs:

```<code>(add-hook 'python-mode-hook (lambda ()
                               (ropemacs-mode)
                               ))
</code>```

But it seems to break flymake. What am I doing wrong here?

答:
My problem was with some code for using autocomplete.el along with ropemacs and yas which I found here:

http://hide1713.wordpress.com/2009/01/30/setup-perfect-python-environment-in-emacs/

Once I commented out the block relating to autocomplete everything else started working as expected.

ContentLicense: CC BY-SA 3.0

Body:
When I open a python file I have to manually start ropemacs-mode to get the key bindings each time. I tried adding something like this to automatically start ropemacs:

(add-hook 'python-mode-hook (lambda ()
                               (ropemacs-mode)
                               ))

But it seems to break flymake. What am I doing wrong here?


问:
How to merge two json array which has same value in react native in a javascript
I have a two json objects. i need to merge those in a single object which has same id.

Example

```<code> const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(() => {
    fetch('first api')
      .then((response) => response.json())
      .then((json) => setOrderdetails(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    fetch('second api')
      .then((response) => response.json())
      .then((json) => setOrdertracking(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);
</code>```

Sample data

First api response in orderdetails

```<code>{
    "statusCode": "200",
    "message": "success",
    "content": [
         { subject_id: 711, topics: ["Test", "Test2"] },
         { subject_id: 712, topics: ["topic1", "Topic2"] }
]
}
</code>```

Second api response in ordertracking

```<code>{
        "statusCode": "200",
        "message": "success",
        "content": [
              {subject_id: 711, subject_name: "Science"},
               {subject_id: 712, subject_name: "Maths"}
    ]
    }
</code>```

I want the merged result to be:

```<code>const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];
</code>```

As you can see there are two api response in a josn format I need to merge those json object which is inside a content which has same 'subject_id'  and rest of the values as a single data.

I need a solution in javascript for my react native app if you can suggest me a react native code

答:
I would suggest instead of making a result an array like this:

```<code> const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];
</code>```

You make it an object mapped with the subject_id:

```<code> const result = {
  "711":{
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  "712":{
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];
</code>```

And your useEffect would be cleaner if you use async/await like this:

```<code> const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(async () => {
   try{
    var res1 = await fetch('first api')
    var data1 = await res1.json()
    var res2 = await fetch('second api')
    var data2 = await res2.json()
    setOrderdetails(data1)
    setOrdertracking(data2)
    var res = {}
    for(let d1 of data1.content){
      res[d1.subject_id] = {
         topics:d1.topics
      }

    }
    for(let d2 of data2.content){
      if(res[d2.subject_id]){
         res[d2.subject_id].subjectName = d2.subjectName
      }

    }
    console.log(res)
   }catch(e){
     console.error(e)
   }finally{
    setLoading(false)
   }
  }, []);
</code>```

If you want to keep result an array use this

```<code> const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(async () => {
   try{
    var res1 = await fetch('first api')
    var data1 = await res1.json()
    var res2 = await fetch('second api')
    var data2 = await res2.json()
    setOrderdetails(data1)
    setOrdertracking(data2)
    var res = []
    for(let d1 of data1.content){
      res.push({...d1,...data2.content.find(d2=>d2.subject_id==d1.subject_id)})

    }
    console.log(res)
   }catch(e){
     console.error(e)
   }finally{
    setLoading(false)
   }
  }, []);
</code>```

Body:
I have a two json objects. i need to merge those in a single object which has same id.

Example

 const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(() => {
    fetch('first api')
      .then((response) => response.json())
      .then((json) => setOrderdetails(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    fetch('second api')
      .then((response) => response.json())
      .then((json) => setOrdertracking(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

Sample data

First api response in orderdetails

{
    "statusCode": "200",
    "message": "success",
    "content": [
         { subject_id: 711, topics: ["Test", "Test2"] },
         { subject_id: 712, topics: ["topic1", "Topic2"] }
]
}

Second api response in ordertracking

{
        "statusCode": "200",
        "message": "success",
        "content": [
              {subject_id: 711, subject_name: "Science"},
               {subject_id: 712, subject_name: "Maths"}
    ]
    }

I want the merged result to be:

const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];

As you can see there are two api response in a josn format I need to merge those json object which is inside a content which has same 'subject_id'  and rest of the values as a single data.

I need a solution in javascript for my react native app if you can suggest me a react native code

Body:
I would suggest instead of making a result an array like this:

 const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];

You make it an object mapped with the subject_id:

 const result = {
  "711":{
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  "712":{
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];

And your useEffect would be cleaner if you use async/await like this:

 const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(async () => {
   try{
    var res1 = await fetch('first api')
    var data1 = await res1.json()
    var res2 = await fetch('second api')
    var data2 = await res2.json()
    setOrderdetails(data1)
    setOrdertracking(data2)
    var res = {}
    for(let d1 of data1.content){
      res[d1.subject_id] = {
         topics:d1.topics
      }

    }
    for(let d2 of data2.content){
      if(res[d2.subject_id]){
         res[d2.subject_id].subjectName = d2.subjectName
      }

    }
    console.log(res)
   }catch(e){
     console.error(e)
   }finally{
    setLoading(false)
   }
  }, []);

If you want to keep result an array use this

 const [orderdetails, setOrderdetails] = useState([]);
  const [ordertracking, setOrdertracking] = useState([]);

  useEffect(async () => {
   try{
    var res1 = await fetch('first api')
    var data1 = await res1.json()
    var res2 = await fetch('second api')
    var data2 = await res2.json()
    setOrderdetails(data1)
    setOrdertracking(data2)
    var res = []
    for(let d1 of data1.content){
      res.push({...d1,...data2.content.find(d2=>d2.subject_id==d1.subject_id)})

    }
    console.log(res)
   }catch(e){
     console.error(e)
   }finally{
    setLoading(false)
   }
  }, []);


问:
Find the min/max element of an array in JavaScript
How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

```<code>let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100
</code>```

答:
Another solution

```<code>   let arr = [1,10,25,15,31,5,7,101];
    let sortedArr = arr.sort((a, b) => a - b)

    let min = sortedArr[0];
    let max = sortedArr[arr.length-1]

    console.log(`min => ${min}. Max => ${max}`)
</code>```

Body:
How can I easily obtain the min or max element of a JavaScript array?

Example pseudocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100

Body:
Another solution

   let arr = [1,10,25,15,31,5,7,101];
    let sortedArr = arr.sort((a, b) => a - b)

    let min = sortedArr[0];
    let max = sortedArr[arr.length-1]

    console.log(`min => ${min}. Max => ${max}`)


问:
using global stylesheets with storybook & angular - SassError: SassError: expected "{"
for a few days now I've been trying to integrate a global stylesheet in storybook. I have already integrated the webpackFinal configs from the documentation for sass support. In the .storybook directory I created a scss-loader.scss file which should load the global stylesheets. In the 'preview.js' file, i import
''!style-loader!css-loader!sass-loader!./scss-loader.scss''

However, I get the following error every time:

```<code>ModuleBuildError: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/sass-loader/dist/cjs.js):
SassError: expected "{".
   ╷
2 │ import API from "! ../../../../../ node_modules / style-loader / dist / runtime / injectStylesIntoStyleTag.js";

projects\svm\ui\_theme.scss 2:101  root stylesheet
    at processResult (F:\sources\svm\UI\node_modules\webpack\lib\NormalModule.js:748:19)
    at F:\sources\svm\UI\node_modules\webpack\lib\NormalModule.js:847:5
    at F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:399:11
    at F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:251:18
    at context.callback (F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:124:13)
    at Object.callback (F:\sources\svm\UI\node_modules\@angular-devkit\build-angular\node_modules\sass-loader\dist\index.js:54:7)
    at Worker.<anonymous> (F:\sources\svm\UI\node_modules\@angular-devkit\build-angular\src\sass\sass-service.js:134:25)
    at Worker.emit (events.js:375:28)
    at MessagePort.<anonymous> (internal/worker.js:216:53)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:399:24)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)
</code>```

Maybe someone has a flash of inspiration, unfortunately I haven't found anything suitable over the last few days

Thank you in advance for your help!!!

答:
Importing styles inside your .storybook/preview.js is not supported any more. From Angular 13 and onwards, the style imports must be added in angular.json, under your-project > (build-)storybook > options > styles.

In your angular.json:

"your-project": {
  ...
  "storybook": {
      "builder": "@nrwl/storybook:storybook",
      "options": {
          ...
          "projectBuildConfig": "your-project:build-storybook",
          "styles": [
              "path-to-the-stylesheet/styles.scss",
              "path-to-the-stylesheet/your-theme.scss"
          ],
          ...
      },
      ...

    },
    ...
}
```

You can find this information in the migration-guide of storybook.

Body:
for a few days now I've been trying to integrate a global stylesheet in storybook. I have already integrated the webpackFinal configs from the documentation for sass support. In the .storybook directory I created a scss-loader.scss file which should load the global stylesheets. In the 'preview.js' file, i import
''!style-loader!css-loader!sass-loader!./scss-loader.scss''

However, I get the following error every time:

ModuleBuildError: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/sass-loader/dist/cjs.js):
SassError: expected "{".
   ╷
2 │ import API from "! ../../../../../ node_modules / style-loader / dist / runtime / injectStylesIntoStyleTag.js";

projects\svm\ui\_theme.scss 2:101  root stylesheet
    at processResult (F:\sources\svm\UI\node_modules\webpack\lib\NormalModule.js:748:19)
    at F:\sources\svm\UI\node_modules\webpack\lib\NormalModule.js:847:5
    at F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:399:11
    at F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:251:18
    at context.callback (F:\sources\svm\UI\node_modules\loader-runner\lib\LoaderRunner.js:124:13)
    at Object.callback (F:\sources\svm\UI\node_modules\@angular-devkit\build-angular\node_modules\sass-loader\dist\index.js:54:7)
    at Worker.<anonymous> (F:\sources\svm\UI\node_modules\@angular-devkit\build-angular\src\sass\sass-service.js:134:25)
    at Worker.emit (events.js:375:28)
    at MessagePort.<anonymous> (internal/worker.js:216:53)
    at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:399:24)
    at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26)

Maybe someone has a flash of inspiration, unfortunately I haven't found anything suitable over the last few days

Thank you in advance for your help!!!

Body:
Importing styles inside your .storybook/preview.js is not supported any more. From Angular 13 and onwards, the style imports must be added in angular.json, under your-project > (build-)storybook > options > styles.

In your angular.json:

"your-project": {
  ...
  "storybook": {
      "builder": "@nrwl/storybook:storybook",
      "options": {
          ...
          "projectBuildConfig": "your-project:build-storybook",
          "styles": [
              "path-to-the-stylesheet/styles.scss",
              "path-to-the-stylesheet/your-theme.scss"
          ],
          ...
      },
      ...

    },
    ...
}

You can find this information in the migration-guide of storybook.


问:
elasticSearch count multiple
I have two profiles, "A" and "B" both have events in the elastic

this is the elastic data for ex:

```<code> {hits: [
   {tag:"A"},
   {tag:"B"},
   {tag:B}
 ]}
</code>```

I want to count how much events tag "a" have and and how much "B" in one request

Ive tried this but it counts them total as 3 and I want A:1 and B:2

```<code>GET forensics/_count
{
"query": {
 "terms": {
   "waas_tag": ["A","B"]
 }
}
}

</code>```

答:
You can use term vector API to get information about the terms of a particular field.

Adding a working example with index data and response

Index Data

```<code>{
    "waas_tag": [
        {
            "tag": "A"
        },
        {
            "tag": "B"
        },
        {
            "tag": "B"
        }
    ]
}
</code>```

Term Vector API:

```<code>GET _termvectors/1?fields=waas_tag.tag
</code>```

Response:

```<code>"term_vectors": {
        "waas_tag.tag": {
            "field_statistics": {
                "sum_doc_freq": 2,
                "doc_count": 1,
                "sum_ttf": 3
            },
            "terms": {
                "a": {
                    "term_freq": 1,                           // note this
                    "tokens": [
                        {
                            "position": 0,
                            "start_offset": 0,
                            "end_offset": 1
                        }
                    ]
                },
                "b": {
                    "term_freq": 2,                           // note this
                    "tokens": [
                        {
                            "position": 101,
                            "start_offset": 2,
                            "end_offset": 3
                        },
                        {
                            "position": 202,
                            "start_offset": 4,
                            "end_offset": 5
                        }
                    ]
                }
            }
        }
    }
</code>```

Title: elasticSearch count multiple

Body:
I have two profiles, "A" and "B" both have events in the elastic

this is the elastic data for ex:

 {hits: [
   {tag:"A"},
   {tag:"B"},
   {tag:B}
 ]}

I want to count how much events tag "a" have and and how much "B" in one request

Ive tried this but it counts them total as 3 and I want A:1 and B:2

GET forensics/_count
{
"query": {
 "terms": {
   "waas_tag": ["A","B"]
 }
}
}

Body:
You can use term vector API to get information about the terms of a particular field.

Adding a working example with index data and response

Index Data

{
    "waas_tag": [
        {
            "tag": "A"
        },
        {
            "tag": "B"
        },
        {
            "tag": "B"
        }
    ]
}

Term Vector API:

GET _termvectors/1?fields=waas_tag.tag

Response:

"term_vectors": {
        "waas_tag.tag": {
            "field_statistics": {
                "sum_doc_freq": 2,
                "doc_count": 1,
                "sum_ttf": 3
            },
            "terms": {
                "a": {
                    "term_freq": 1,                           // note this
                    "tokens": [
                        {
                            "position": 0,
                            "start_offset": 0,
                            "end_offset": 1
                        }
                    ]
                },
                "b": {
                    "term_freq": 2,                           // note this
                    "tokens": [
                        {
                            "position": 101,
                            "start_offset": 2,
                            "end_offset": 3
                        },
                        {
                            "position": 202,
                            "start_offset": 4,
                            "end_offset": 5
                        }
                    ]
                }
            }
        }
    }


问:
Mongoose - Least distance between two co-ordinates (Not GEOJson Data)
From a list of buildings, the operator will choose one.

and click on it from the front end.

The list of buildings is stored in the MongoDB database and each one has a x,y point demonstrating distance from the 0 origin.

The list is stored in MongoDB database and accessed with node.

Each building has a x,y co-ordinate -- sample only, NOT geojson data

like 101,203 etc.

The Mongoose function will :

Operator clicks on a button and that co-ordinates are used

The funciton will search  through the list of buildings and return the nearest one to the one provided --- not the nearest one to the 0 origin.

Any suggestions on how to do with Mongoose?

thanks!
Karen

答:
This is really just a math problem.
Consider a set of building docs with these x,y coords:

var r =   [
    {_id:1, x:7, y:11}
    ,{_id:2, x:15, y:10}
    ,{_id:3, x:10, y:9}
    ,{_id:4, x:1, y:8}
    ,{_id:5, x:3, y:7}
    ,{_id:6, x:16, y:5}
    ,{_id:7, x:4, y:3}
    ,{_id:8, x:7, y:3}
    ,{_id:9, x:6, y:1}
    ,{_id:10, x:21, y:1}
];
```
<p>A button is clicked and produces point <code>6,5</code>:</p>
<pre class="lang-js prettyprint-override"><code>var P = {x:6, y:5};
</code>```

To find buildings closest, just iterate and compute distance using pythagorean theorem:

db.foo.aggregate([
    //  Don't have to worry about absolute value of x-x1 thanks to
    //  pow(2) making it positive
    //  dist = sqrt((x-x1)^2 + (y-y1)^2)
    {$addFields: {dist: {$sqrt: {$add:[{$pow:[{$subtract:['$x',P.x]},2]}, {$pow:[{$subtract:['$y',P.y]},2]}]}} }},
    {$sort: {'dist':1}},
    {$limit: 1}
]);

{ "_id" : 8, "x" : 7, "y" : 3, "dist" : 2.23606797749979 }
```

Remove the $limit or change it to a higher number to see the next closest buidlings.

Body:
This is really just a math problem.
Consider a set of building docs with these x,y coords:

var r =   [
    {_id:1, x:7, y:11}
    ,{_id:2, x:15, y:10}
    ,{_id:3, x:10, y:9}
    ,{_id:4, x:1, y:8}
    ,{_id:5, x:3, y:7}
    ,{_id:6, x:16, y:5}
    ,{_id:7, x:4, y:3}
    ,{_id:8, x:7, y:3}
    ,{_id:9, x:6, y:1}
    ,{_id:10, x:21, y:1}
];

A button is clicked and produces point 6,5:

var P = {x:6, y:5};

To find buildings closest, just iterate and compute distance using pythagorean theorem:

db.foo.aggregate([
    //  Don't have to worry about absolute value of x-x1 thanks to
    //  pow(2) making it positive
    //  dist = sqrt((x-x1)^2 + (y-y1)^2)
    {$addFields: {dist: {$sqrt: {$add:[{$pow:[{$subtract:['$x',P.x]},2]}, {$pow:[{$subtract:['$y',P.y]},2]}]}} }},
    {$sort: {'dist':1}},
    {$limit: 1}
]);

{ "_id" : 8, "x" : 7, "y" : 3, "dist" : 2.23606797749979 }

Remove the $limit or change it to a higher number to see the next closest buidlings.


问:
Working with difficult AM/PM formats and REGEX with lubridate in R
Hello guys I hope everyone is having a good one, I am trying to work with some AM/PM formats in lubridate on R but I cant seem to come up with a proper solution I hope you guys can correct meand help me out please!

I have a HUGE dataset that has date_time formats in a very rare way the format goes as follow:

First a number that represents the day, second an abbreviation of the month OR even the month fully spelled out a 12H time format and the strings " a. m." OR "p. m." or even a combination of more spaces between or missing "dots" then such as "a.  m"  to set an example please take a look at this vector:

```<code>dates<-c("02 dec 05:47 a. m",
"7 November 09:47 p. m.",
"3  jul 12:28 a.m.",
"23 sept 08:53 a m.",
"7 may 09:05 PM")
</code>```

These make up for more than 95% of the rare formats of datetime in the data set I have been trying to use lubridate on R I am trying to use the function

```<code>ydm_hm(paste(2021,dates))
</code>```

this is because all dates are form 2021 but I get always:

```<code>[1] NA                        NA                        NA
[4] NA                        "2021-05-07 21:05:00 UTC"
Warning message:
 4 failed to parse.
</code>```

the 4 that fail to parse give me NAS and the only one that parses is correct I do notice that this one has PM or AM as uppercase letters without dots but most of the time my formats will be like this:

```<code>ydm_hm("7 may 09:05 p.m.")
</code>```

and this gives me NAS...

So I feel as though the only way to get this dates to workout is to change the structure and using REGEX so convert all "a. m." combinations into "AM" and "PM" only after analyzing the data I realized all "p.m" or "a. m." strings come after ONE or TWO spaces after the 12H time format that always have a length of 5 characters and so what should be considered to come up with the patter of the REGEX is the following

the string will begins with one or two numbers then spaces and then letters (for the month abbreviated or fully spelled out after that will have spaces and then 5 characters (that's the 12H time format) and then will have letters spaces and dots for all possible a.m and p.m formats but I have tried with no luck to convert the structure of the date.. if you guys could help me I will be so freaking thankful I dont know if there is a way or another package in R that will even resolve this issue without using regex so thank you everyone for your help !

my desired output will be:

```<code>"2021-12-02 05;47:00 UTC"
"2021-11-07 09:47:00 UTC"
"2021-07-03 12:28:00 UTC"
"2021-09-23 08:53:00 UTC"
"2021-05-07 21:05:00 UTC"
</code>```

答:
Since you raised the issue of regular expression, I thought I might try one way to do that

```<code>library(stringr)

# get boolean for pm dates
pm = str_detect(dates,"(?<=\\d\\d:\\d\\d\\s{1,2})[pP]",)

# convert dates to dates without am/pm
dates = str_extract(dates,"^.*:\\d\\d")

# add pm back to pm dates and am to am dates
dates[pm] <- paste(dates[pm], "PM")
dates[!pm] <- paste(dates[!pm], "AM")

# now your orignal approach works
ydm_hm(paste(2021,dates))
</code>```

Output

```<code>[1] "2021-12-02 05:47:00 UTC" "2021-11-07 21:47:00 UTC" "2021-07-03 00:28:00 UTC" "2021-09-23 08:53:00 UTC"
[5] "2021-05-07 21:05:00 UTC"
</code>```

Body:
Hello guys I hope everyone is having a good one, I am trying to work with some AM/PM formats in lubridate on R but I cant seem to come up with a proper solution I hope you guys can correct meand help me out please!

I have a HUGE dataset that has date_time formats in a very rare way the format goes as follow:

First a number that represents the day, second an abbreviation of the month OR even the month fully spelled out a 12H time format and the strings " a. m." OR "p. m." or even a combination of more spaces between or missing "dots" then such as "a.  m"  to set an example please take a look at this vector:

dates<-c("02 dec 05:47 a. m",
"7 November 09:47 p. m.",
"3  jul 12:28 a.m.",
"23 sept 08:53 a m.",
"7 may 09:05 PM")

These make up for more than 95% of the rare formats of datetime in the data set I have been trying to use lubridate on R I am trying to use the function

ydm_hm(paste(2021,dates))

this is because all dates are form 2021 but I get always:

[1] NA                        NA                        NA
[4] NA                        "2021-05-07 21:05:00 UTC"
Warning message:
 4 failed to parse.

the 4 that fail to parse give me NAS and the only one that parses is correct I do notice that this one has PM or AM as uppercase letters without dots but most of the time my formats will be like this:

ydm_hm("7 may 09:05 p.m.")

and this gives me NAS...

So I feel as though the only way to get this dates to workout is to change the structure and using REGEX so convert all "a. m." combinations into "AM" and "PM" only after analyzing the data I realized all "p.m" or "a. m." strings come after ONE or TWO spaces after the 12H time format that always have a length of 5 characters and so what should be considered to come up with the patter of the REGEX is the following

the string will begins with one or two numbers then spaces and then letters (for the month abbreviated or fully spelled out after that will have spaces and then 5 characters (that's the 12H time format) and then will have letters spaces and dots for all possible a.m and p.m formats but I have tried with no luck to convert the structure of the date.. if you guys could help me I will be so freaking thankful I dont know if there is a way or another package in R that will even resolve this issue without using regex so thank you everyone for your help !

my desired output will be:

"2021-12-02 05;47:00 UTC"
"2021-11-07 09:47:00 UTC"
"2021-07-03 12:28:00 UTC"
"2021-09-23 08:53:00 UTC"
"2021-05-07 21:05:00 UTC"

Body:
Since you raised the issue of regular expression, I thought I might try one way to do that

library(stringr)

# get boolean for pm dates
pm = str_detect(dates,"(?<=\\d\\d:\\d\\d\\s{1,2})[pP]",)

# convert dates to dates without am/pm
dates = str_extract(dates,"^.*:\\d\\d")

# add pm back to pm dates and am to am dates
dates[pm] <- paste(dates[pm], "PM")
dates[!pm] <- paste(dates[!pm], "AM")

# now your orignal approach works
ydm_hm(paste(2021,dates))

Output

[1] "2021-12-02 05:47:00 UTC" "2021-11-07 21:47:00 UTC" "2021-07-03 00:28:00 UTC" "2021-09-23 08:53:00 UTC"
[5] "2021-05-07 21:05:00 UTC"


问:
Passing Variable from JS to VB.net
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

```<code>document.getElementById("Label1").innerText = nwLat;
</code>```

then in the vb part

```<code>   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)
</code>```

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

答:
Easiest way without any type of ajax would be to use a hidden field.

Markup:

<asp:HiddenField ID="nwLatHidden" runat="server" Value="" />

JS:

document.getElementById('nwLatHidden').value = '6.00'; // or of course the value from your function.

.NET during your postback routine:

```<code>Dim nwLat As Double
nwLat = nwLatHidden.Value
</code>```

Title: Passing Variable from JS to VB.net

Body:
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

document.getElementById("Label1").innerText = nwLat;

then in the vb part

   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

Body:
Easiest way without any type of ajax would be to use a hidden field.

Markup:

<asp:HiddenField ID="nwLatHidden" runat="server" Value="" />

JS:

document.getElementById('nwLatHidden').value = '6.00'; // or of course the value from your function.

.NET during your postback routine:

Dim nwLat As Double
nwLat = nwLatHidden.Value


问:
Why when I use onClick with radio button make them have to click twice to make radio button to be selected?
now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value

```<code>  <input
     required
     id="singleClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={1}
     OnClick={() => setisRepeat("oneTime")}
     ></input>

     <label>ครั้งเดียว</label>
   <input
     required
     id="repeatClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={2}
     onClick={() => setisRepeat("repeat")}
     ></input>
</code>```

and render component like this

```<code>    {isRepeat === "oneTime" && (
        <>...</>
    )}
    {isRepeat === "repeat" && (
        <div>...</div>
    )}
</code>```

but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked

(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)

ps. I already using document.getElementByName('classType').value === 1 or 2   to render different items, but didn't work

答:
You can use onChange instead of onClick handler and checked property along with it.

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

export default function App() {
const [isRepeat, setisRepeat] = useState("");
const onClickHandler = (type) => {
  if (type === "singleClass") {
     setisRepeat("singleClass");
  } else {
     setisRepeat("repeatClass");
  }
};
return (
<div className="App">
  <input
    required
    name="singleClass"
    type="radio"
    className="inputContainer"
    value={1}
    checked={isRepeat === "singleClass"}
    onChange={() => {
      onClickHandler("singleClass");
    }}
  ></input>

  <label>ครั้งเดียว</label>
  <input
    required
    name="repeatClass"
    type="radio"
    className="inputContainer"
    value={2}
    checked={isRepeat === "repeatClass"}
    onChange={() => {
      onClickHandler("repeatClass");
    }}
  ></input>
  {isRepeat === "singleClass" && (
    <>
      <p>One time component Triggered </p>
    </>
  )}
  {isRepeat === "repeatClass" && <div>Repeat component Triggered </div>}
</div>
);
}
</code>```

Demo

Body:
now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value

  <input
     required
     id="singleClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={1}
     OnClick={() => setisRepeat("oneTime")}
     ></input>

     ครั้งเดียว
   <input
     required
     id="repeatClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={2}
     onClick={() => setisRepeat("repeat")}
     ></input>

and render component like this

    {isRepeat === "oneTime" && (
        <>...</>
    )}
    {isRepeat === "repeat" && (

...

    )}

but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked

(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)

ps. I already using document.getElementByName('classType').value === 1 or 2   to render different items, but didn't work

Body:
You can use onChange instead of onClick handler and checked property along with it.

import { useState } from "react";

export default function App() {
const [isRepeat, setisRepeat] = useState("");
const onClickHandler = (type) => {
  if (type === "singleClass") {
     setisRepeat("singleClass");
  } else {
     setisRepeat("repeatClass");
  }
};
return (
<div className="App">
  <input
    required
    name="singleClass"
    type="radio"
    className="inputContainer"
    value={1}
    checked={isRepeat === "singleClass"}
    onChange={() => {
      onClickHandler("singleClass");
    }}
  ></input>

  <label>ครั้งเดียว</label>
  <input
    required
    name="repeatClass"
    type="radio"
    className="inputContainer"
    value={2}
    checked={isRepeat === "repeatClass"}
    onChange={() => {
      onClickHandler("repeatClass");
    }}
  ></input>
  {isRepeat === "singleClass" && (
    <>
      <p>One time component Triggered </p>
    </>
  )}
  {isRepeat === "repeatClass" && <div>Repeat component Triggered </div>}
</div>
);
}

Demo


问:
Why I cannot send a string in send in express?
I have the following code to get data from an external API:

```<code>const axios = require('axios');
const express =  require('express');

const app = express()

app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat=>{
         console.log(resultat.data.markets)
           res = resultat.data.markets
           myS="";

               res.forEach(element=>{
               console.log(element.exchange_id);
               myS=myS+element.exchange_id;
            });

            res.send(myS);

       })
       .catch(error => console.log(`error is ${error}`));
})

port = 3000

app.listen(port, ()=>{console.log(`The server has started and is listening on port number: ${port}`);});
</code>```

when I execute the code I get the following:

```<code>error is TypeError: res.send is not a function
</code>```

I dont know where is my error.

答:
You've overwritten the value of res that was passed into the function with this line of code:

```<code>res = resultat.data.markets
</code>```

So, after doing that the original res is gone so you can't call res.send() any more.

Define your own separately named variable:

```<code>app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat => {
           console.log(resultat.data.markets);
           let markets = resultat.data.markets;
           let myS = "";

           markets.forEach(element => {
               console.log(element.exchange_id);
               myS = myS + element.exchange_id;
           });

           res.send(myS);

       })
       .catch(error => console.log(`error is ${error}`));
})
</code>```

Also, you must declare all variables you use with let or const.

FYI, you could simplify a bit with:

```<code>let myS = resultat.data.markets.map(element => element.exchange_id).join("");
res.send(myS);
</code>```

Body:
I have the following code to get data from an external API:

const axios = require('axios');
const express =  require('express');

const app = express()

app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat=>{
         console.log(resultat.data.markets)
           res = resultat.data.markets
           myS="";

               res.forEach(element=>{
               console.log(element.exchange_id);
               myS=myS+element.exchange_id;
            });

            res.send(myS);

       })
       .catch(error => console.log(`error is ${error}`));
})

port = 3000

app.listen(port, ()=>{console.log(`The server has started and is listening on port number: ${port}`);});

when I execute the code I get the following:

error is TypeError: res.send is not a function

I dont know where is my error.

Body:
You've overwritten the value of res that was passed into the function with this line of code:

res = resultat.data.markets

So, after doing that the original res is gone so you can't call res.send() any more.

Define your own separately named variable:

app.get("/coins", (req, res) => {
    console.log("/coins test");

    axios.get("https://www.cryptingup.com/api/markets")
       .then(resultat => {
           console.log(resultat.data.markets);
           let markets = resultat.data.markets;
           let myS = "";

           markets.forEach(element => {
               console.log(element.exchange_id);
               myS = myS + element.exchange_id;
           });

           res.send(myS);

       })
       .catch(error => console.log(`error is ${error}`));
})

Also, you must declare all variables you use with let or const.

FYI, you could simplify a bit with:

let myS = resultat.data.markets.map(element => element.exchange_id).join("");
res.send(myS);


问:
How use jQuery inline?
I have this code:

```<code><p id = 'drop1' style='color:#008cba; background-color:#fffF00;'
onmouseover="show()" onmouseout="hide()" title="See more">
Hi, my name is text 1.
</p>
</code>```

that works.

But, I'd like to write it in jQuery. I tried:

```<code><p id = 'drop2' style='color:#008cba; background-color:#fffF00;'
$(this).attr('See more')>
Hi, my name is text 2.
</p>
</code>```

Doesn't work.

Is there a way to write a jQuery only inline form?

答:
You shouldn't be putting code inline with HTML elements in general. It's just as easy to incorporate a script element and a proper event handler. However, I suspect that this is what you're after:

  Hi, my name is text 2

```

The reason your example doesn't work is because jQuery's attr() method, when passed a single argument, attempts to retrieve the value of that attribute. There's no such attribute in your HTML.

Title: How use jQuery inline?

Body:
I have this code:

Hi, my name is text 1.

that works.

But, I'd like to write it in jQuery. I tried:

Hi, my name is text 2.

Doesn't work.

Is there a way to write a jQuery only inline form?

Body:
You shouldn't be putting code inline with HTML elements in general. It's just as easy to incorporate a script element and a proper event handler. However, I suspect that this is what you're after:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="drop2" style="color: #008cba; background-color: #fffF00;"
    onmouseover="$(this).text('See more')"
    onmouseout="$(this).text('Hi, my name is text 2')">
  Hi, my name is text 2
</p>

The reason your example doesn't work is because jQuery's attr() method, when passed a single argument, attempts to retrieve the value of that attribute. There's no such attribute in your HTML.


问:
How to to deploy AWS lambda using CodePipleline?
In this world of CICD,I have a lambda function ( written in typescript) and presently in  Github. My IDE is vscode. I can do my development and push my change's to Github. I want that when I push my changes to github, the Lambda function should be deployed to my AWS account using Codebuild and codePipeline. I can create the codestar connection. Can anyone help me with this ?

It should be simple - I push my changes, and then the Lambda should be deployed - correct ?

My google search did not give me any how to solutions ?

Appreciate your help !

答:
You should use a CloudFormation actions of "Create Or Update Stack".  These articles present a good examples:

https://medium.com/hatchsoftware/setting-up-ci-cd-for-lambda-functions-using-aws-codepipeline-880567769dde

https://blog.clairvoyantsoft.com/continuous-deployment-of-lambda-functions-f5d930d1937d

https://www.linkedin.com/pulse/building-cicd-pipeline-lambda-function-aws-using-aliaksandr-liakh/


问:
How To: Prevent Timeout When Inspecting Unavailable Network Share - C#
We have some basic C# logic that iterates over a directory and returns the folders and files within. When run against a network share (\\server\share\folder) that is inaccessible or invalid, the code seems to 'hang' for about 30 seconds before returning back from the call.

I'd like to end up with a method that will attempt to get folders and files from the given path, but without the timeout period. In other words, to reduce or eliminate the timeout altogether.

I've tried something as simple as validating the existence of the directory ahead of time thinking that an 'unavailable' network drive would quickly return false, but that did not work as expected.

```<code>System.IO.Directory.Exists(path) //hangs

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); //hangs
</code>```

Any suggestions on what may help me achieve an efficient (and hopefully managed) solution?

答:
You can use this code:</p>

```<code>var task = new Task<bool>(() => { var fi = new FileInfo(uri.LocalPath); return fi.Exists; });
task.Start();

return task.Wait(100) && task.Result;
</code>```

OwnerDisplayName: Will Smith - AT

ContentLicense: CC BY-SA 2.5

Body:
We have some basic C# logic that iterates over a directory and returns the folders and files within. When run against a network share (\\server\share\folder) that is inaccessible or invalid, the code seems to 'hang' for about 30 seconds before returning back from the call.

I'd like to end up with a method that will attempt to get folders and files from the given path, but without the timeout period. In other words, to reduce or eliminate the timeout altogether.

I've tried something as simple as validating the existence of the directory ahead of time thinking that an 'unavailable' network drive would quickly return false, but that did not work as expected.

System.IO.Directory.Exists(path) //hangs

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); //hangs

Any suggestions on what may help me achieve an efficient (and hopefully managed) solution?

Body:
You can use this code:

var task = new Task<bool>(() => { var fi = new FileInfo(uri.LocalPath); return fi.Exists; });
task.Start();

return task.Wait(100) && task.Result;


问:
Is it possible to use an array value as a switch case value?
I am trying to create a working Java code. I created an encryption function that takes any symbol in a string and replaces it with a value from an array.

The problem is very simple. Decryption function must take any value written in an array and use it to decrypt. The code describes it better than I do.

```<code>   case "1" -> output += n_encryptions[0];
// Then in decrypt():
   case n_encryptions[0] -> output += "1";
// Sadly, this creates an error
</code>```

My goal is to make an easily changeable encryption and decryption system, since I am planning to change these values in the future.

I need a way to use an array value (n_encryptions[0] in the example) as a case parameter.

Edit: I guess an if statement is the best option. Thanks!

答:
AFAIU you problem, a usual approach to this is to have 2 arrays

```<code>char[] from = {'a','b','c'};
char[] to = {'1','e','@'};
</code>```

Read your input char by char, look up the position of the char in from and replace it with the char from the same position in to.

Reverse, the same (to -> from).

Body:
I am trying to create a working Java code. I created an encryption function that takes any symbol in a string and replaces it with a value from an array.

The problem is very simple. Decryption function must take any value written in an array and use it to decrypt. The code describes it better than I do.

   case "1" -> output += n_encryptions[0];
// Then in decrypt():
   case n_encryptions[0] -> output += "1";
// Sadly, this creates an error

My goal is to make an easily changeable encryption and decryption system, since I am planning to change these values in the future.

I need a way to use an array value (n_encryptions[0] in the example) as a case parameter.

Edit: I guess an if statement is the best option. Thanks!

Body:
AFAIU you problem, a usual approach to this is to have 2 arrays

char[] from = {'a','b','c'};
char[] to = {'1','e','@'};

Read your input char by char, look up the position of the char in from and replace it with the char from the same position in to.

Reverse, the same (to -> from).


问:
different ylabel for each subplot in pandas.DataFrame.plot()
I have a data frame df with two columns: df['A'] and df['B']. I am plotting my dataframe with df.plot(subplots=True). This produces a figure with two subplots, one for A and one for B.
Is there a way to use the ylabel keyword to assign different ylabel values to the two subplots? I tried with df.plot(subplots=True,ylabel=['A','B']) and hoped that the first element of the list was assigned to the first subplot and the second element to the second subplot. However, the labels of both subplots are set to '[A,B]'.

答:
You can use the axes handles returned by df.plot:

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 4, 1]})

axes = df.plot(subplots=True)
axes[0].set_ylabel("label1")
axes[1].set_ylabel("label2")
plt.show()
</code>```

Body:
You can use the axes handles returned by df.plot:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 4, 1]})

axes = df.plot(subplots=True)
axes[0].set_ylabel("label1")
axes[1].set_ylabel("label2")
plt.show()


问:
How to increment a shared counter from multiple processes?
I am having troubles with the multiprocessing module. I am using a Pool of workers with its map method to concurrently analyze lots of files. Each time a file has been processed I would like to have a counter updated so that I can keep track of how many files remains to be processed. Here is sample code:

```<code>import os
import multiprocessing

counter = 0

def analyze(file):
    # Analyze the file.
    global counter
    counter += 1
    print counter

if __name__ == '__main__':
    files = os.listdir('/some/directory')
    pool = multiprocessing.Pool(4)
    pool.map(analyze, files)
</code>```

I cannot find a solution for this.

答:
Here is a solution to your problem based on a different approach from that proposed in the other answers. It uses message passing with multiprocessing.Queue objects (instead of shared memory with multiprocessing.Value objects) and process-safe (atomic) built-in increment and decrement operators += and -= (instead of introducing custom increment and decrement methods) since you asked for it.

First, we define a class Subject for instantiating an object that will be local to the parent process and whose attributes are to be incremented or decremented:

import multiprocessing

class Subject:

    def __init__(self):
        self.x = 0
        self.y = 0
```
<p>Next, we define a class <code>Proxy</code> for instantiating an object that will be the remote proxy through which the child processes will request the parent process to retrieve or update the attributes of the <code>Subject</code> object. The interprocess communication will use two <code>multiprocessing.Queue</code> attributes, one for exchanging requests and one for exchanging responses. Requests are of the form <code>(sender, action, *args)</code> where <code>sender</code> is the sender name, <code>action</code> is the action name (<code>'get'</code>, <code>'set'</code>, <code>'increment'</code>, or <code>'decrement'</code> the value of an attribute), and <code>args</code> is the argument tuple. Responses are of the form <code>value</code> (to <code>'get'</code> requests):</p>
<pre class="lang-py prettyprint-override"><code>class Proxy(Subject):

    def __init__(self, request_queue, response_queue):
        self.__request_queue = request_queue
        self.__response_queue = response_queue

    def _getter(self, target):
        sender = multiprocessing.current_process().name
        self.__request_queue.put((sender, 'get', target))
        return Decorator(self.__response_queue.get())

    def _setter(self, target, value):
        sender = multiprocessing.current_process().name
        action = getattr(value, 'action', 'set')
        self.__request_queue.put((sender, action, target, value))

    @property
    def x(self):
        return self._getter('x')

    @property
    def y(self):
        return self._getter('y')

    @x.setter
    def x(self, value):
        self._setter('x', value)

    @y.setter
    def y(self, value):
        self._setter('y', value)
</code>```

Then, we define the class Decorator to decorate the int objects returned by the getters of a Proxy object in order to inform its setters whether the increment or decrement operators += and -= have been used by adding an action attribute, in which case the setters request an 'increment' or 'decrement' operation instead of a 'set' operation. The increment and decrement operators += and -= call the corresponding augmented assignment special methods __iadd__ and __isub__ if they are defined, and fall back on the assignment special methods __add__ and __sub__ which are always defined for int objects (e.g. proxy.x += value is equivalent to proxy.x = proxy.x.__iadd__(value) which is equivalent to proxy.x = type(proxy).x.__get__(proxy).__iadd__(value) which is equivalent to type(proxy).x.__set__(proxy, type(proxy).x.__get__(proxy).__iadd__(value))):

class Decorator(int):

    def __iadd__(self, other):
        value = Decorator(other)
        value.action = 'increment'
        return value

    def __isub__(self, other):
        value = Decorator(other)
        value.action = 'decrement'
        return value
```
<p>Then, we define the function <code>worker</code> that will be run in the child processes and request the increment and decrement operations:</p>
<pre class="lang-py prettyprint-override"><code>def worker(proxy):
    proxy.x += 1
    proxy.y -= 1
</code>```

Finally, we define a single request queue to send requests to the parent process, and multiple response queues to send responses to the child processes:

if __name__ == '__main__':
    subject = Subject()
    request_queue = multiprocessing.Queue()
    response_queues = {}
    processes = []
    for index in range(4):
        sender = 'child {}'.format(index)
        response_queues[sender] = multiprocessing.Queue()
        proxy = Proxy(request_queue, response_queues[sender])
        process = multiprocessing.Process(
            target=worker, args=(proxy,), name=sender)
        processes.append(process)
    running = len(processes)
    for process in processes:
        process.start()
    while subject.x != 4 or subject.y != -4:
        sender, action, *args = request_queue.get()
        print(sender, 'requested', action, *args)
        if action == 'get':
            response_queues[sender].put(getattr(subject, args[0]))
        elif action == 'set':
            setattr(subject, args[0], args[1])
        elif action == 'increment':
            setattr(subject, args[0], getattr(subject, args[0]) + args[1])
        elif action == 'decrement':
            setattr(subject, args[0], getattr(subject, args[0]) - args[1])
    for process in processes:
        process.join()
```
<p>The program is guaranteed to terminate when <code>+=</code> and <code>-=</code> are process-safe. If you remove process-safety by commenting the corresponding <code>__iadd__</code> or <code>__isub__</code> of <code>Decorator</code> then the program will only terminate by chance (e.g. <code>proxy.x += value</code> is equivalent to <code>proxy.x = proxy.x.__iadd__(value)</code> but falls back to <code>proxy.x = proxy.x.__add__(value)</code> if <code>__iadd__</code> is not defined, which is equivalent to <code>proxy.x = proxy.x + value</code> which is equivalent to <code>proxy.x = type(proxy).x.__get__(proxy) + value</code> which is equivalent to <code>type(proxy).x.__set__(proxy, type(proxy).x.__get__(proxy) + value)</code>, so the <code>action</code> attribute is not added and the setter requests a <code>'set'</code> operation instead of an <code>'increment'</code> operation).</p>
<p>Example process-safe session (atomic <code>+=</code> and <code>-=</code>):</p>
<pre class="lang-none prettyprint-override"><code>child 0 requested get x
child 0 requested increment x 1
child 0 requested get y
child 0 requested decrement y 1
child 3 requested get x
child 3 requested increment x 1
child 3 requested get y
child 2 requested get x
child 3 requested decrement y 1
child 1 requested get x
child 2 requested increment x 1
child 2 requested get y
child 2 requested decrement y 1
child 1 requested increment x 1
child 1 requested get y
child 1 requested decrement y 1
</code>```

Example process-unsafe session (non-atomic += and -=):

child 2 requested get x
child 1 requested get x
child 0 requested get x
child 2 requested set x 1
child 2 requested get y
child 1 requested set x 1
child 1 requested get y
child 2 requested set y -1
child 1 requested set y -1
child 0 requested set x 1
child 0 requested get y
child 0 requested set y -2
child 3 requested get x
child 3 requested set x 2
child 3 requested get y
child 3 requested set y -3  # the program stalls here
```

Body:
I am having troubles with the multiprocessing module. I am using a Pool of workers with its map method to concurrently analyze lots of files. Each time a file has been processed I would like to have a counter updated so that I can keep track of how many files remains to be processed. Here is sample code:

import os
import multiprocessing

counter = 0

def analyze(file):
    # Analyze the file.
    global counter
    counter += 1
    print counter

if __name__ == '__main__':
    files = os.listdir('/some/directory')
    pool = multiprocessing.Pool(4)
    pool.map(analyze, files)

I cannot find a solution for this.

Body:
Here is a solution to your problem based on a different approach from that proposed in the other answers. It uses message passing with multiprocessing.Queue objects (instead of shared memory with multiprocessing.Value objects) and process-safe (atomic) built-in increment and decrement operators += and -= (instead of introducing custom increment and decrement methods) since you asked for it.

First, we define a class Subject for instantiating an object that will be local to the parent process and whose attributes are to be incremented or decremented:

import multiprocessing

class Subject:

    def __init__(self):
        self.x = 0
        self.y = 0

Next, we define a class Proxy for instantiating an object that will be the remote proxy through which the child processes will request the parent process to retrieve or update the attributes of the Subject object. The interprocess communication will use two multiprocessing.Queue attributes, one for exchanging requests and one for exchanging responses. Requests are of the form (sender, action, *args) where sender is the sender name, action is the action name ('get', 'set', 'increment', or 'decrement' the value of an attribute), and args is the argument tuple. Responses are of the form value (to 'get' requests):

class Proxy(Subject):

    def __init__(self, request_queue, response_queue):
        self.__request_queue = request_queue
        self.__response_queue = response_queue

    def _getter(self, target):
        sender = multiprocessing.current_process().name
        self.__request_queue.put((sender, 'get', target))
        return Decorator(self.__response_queue.get())

    def _setter(self, target, value):
        sender = multiprocessing.current_process().name
        action = getattr(value, 'action', 'set')
        self.__request_queue.put((sender, action, target, value))

    @property
    def x(self):
        return self._getter('x')

    @property
    def y(self):
        return self._getter('y')

    @x.setter
    def x(self, value):
        self._setter('x', value)

    @y.setter
    def y(self, value):
        self._setter('y', value)

Then, we define the class Decorator to decorate the int objects returned by the getters of a Proxy object in order to inform its setters whether the increment or decrement operators += and -= have been used by adding an action attribute, in which case the setters request an 'increment' or 'decrement' operation instead of a 'set' operation. The increment and decrement operators += and -= call the corresponding augmented assignment special methods __iadd__ and __isub__ if they are defined, and fall back on the assignment special methods __add__ and __sub__ which are always defined for int objects (e.g. proxy.x += value is equivalent to proxy.x = proxy.x.__iadd__(value) which is equivalent to proxy.x = type(proxy).x.__get__(proxy).__iadd__(value) which is equivalent to type(proxy).x.__set__(proxy, type(proxy).x.__get__(proxy).__iadd__(value))):

class Decorator(int):

    def __iadd__(self, other):
        value = Decorator(other)
        value.action = 'increment'
        return value

    def __isub__(self, other):
        value = Decorator(other)
        value.action = 'decrement'
        return value

Then, we define the function worker that will be run in the child processes and request the increment and decrement operations:

def worker(proxy):
    proxy.x += 1
    proxy.y -= 1

Finally, we define a single request queue to send requests to the parent process, and multiple response queues to send responses to the child processes:

if __name__ == '__main__':
    subject = Subject()
    request_queue = multiprocessing.Queue()
    response_queues = {}
    processes = []
    for index in range(4):
        sender = 'child {}'.format(index)
        response_queues[sender] = multiprocessing.Queue()
        proxy = Proxy(request_queue, response_queues[sender])
        process = multiprocessing.Process(
            target=worker, args=(proxy,), name=sender)
        processes.append(process)
    running = len(processes)
    for process in processes:
        process.start()
    while subject.x != 4 or subject.y != -4:
        sender, action, *args = request_queue.get()
        print(sender, 'requested', action, *args)
        if action == 'get':
            response_queues[sender].put(getattr(subject, args[0]))
        elif action == 'set':
            setattr(subject, args[0], args[1])
        elif action == 'increment':
            setattr(subject, args[0], getattr(subject, args[0]) + args[1])
        elif action == 'decrement':
            setattr(subject, args[0], getattr(subject, args[0]) - args[1])
    for process in processes:
        process.join()

The program is guaranteed to terminate when += and -= are process-safe. If you remove process-safety by commenting the corresponding __iadd__ or __isub__ of Decorator then the program will only terminate by chance (e.g. proxy.x += value is equivalent to proxy.x = proxy.x.__iadd__(value) but falls back to proxy.x = proxy.x.__add__(value) if __iadd__ is not defined, which is equivalent to proxy.x = proxy.x + value which is equivalent to proxy.x = type(proxy).x.__get__(proxy) + value which is equivalent to type(proxy).x.__set__(proxy, type(proxy).x.__get__(proxy) + value), so the action attribute is not added and the setter requests a 'set' operation instead of an 'increment' operation).

Example process-safe session (atomic += and -=):

child 0 requested get x
child 0 requested increment x 1
child 0 requested get y
child 0 requested decrement y 1
child 3 requested get x
child 3 requested increment x 1
child 3 requested get y
child 2 requested get x
child 3 requested decrement y 1
child 1 requested get x
child 2 requested increment x 1
child 2 requested get y
child 2 requested decrement y 1
child 1 requested increment x 1
child 1 requested get y
child 1 requested decrement y 1

Example process-unsafe session (non-atomic += and -=):

child 2 requested get x
child 1 requested get x
child 0 requested get x
child 2 requested set x 1
child 2 requested get y
child 1 requested set x 1
child 1 requested get y
child 2 requested set y -1
child 1 requested set y -1
child 0 requested set x 1
child 0 requested get y
child 0 requested set y -2
child 3 requested get x
child 3 requested set x 2
child 3 requested get y
child 3 requested set y -3  # the program stalls here


答: Your problem is that you are grabbing the "res" object which is passed into the express callback function, but then for whatever reason you reassign it to equal some results from your axios call, essentially removing all of the Express methods on "res".</p>

Title: Why I cannot send a string in send in express?


问:
React Native: Unhandled promise rejection [TypeError: undefined is not an object (evaluating 'checkFav[0].name')]
I keep getting every time I enter this page/first-time app load data unless I try to ctrl+s file while android on debugging, the app works fine.
How do I fix this? Thx:)

error on filter multidimensional array then I call the already filter array name

```<code>const userProfile = async () => {
    let recipeId = props.route.params?.id ?? null;
    // let recipeId = 3;
    setGiveId(recipeId)
    const list = await authAction.RecipeShow(recipeId);
    setrefresh(list)
    let dataShow = list.data;
    setRecipeName(dataShow.name)
    setImage(dataShow.imageUrl)
    setDescription(dataShow.description)
    let dataFav = await authAction.FavRecipe()
    setData(dataFav.data)
    setIsLoading(false)
    let checkFav = ''
    let check = []
    if (data) {
        checkFav = data.filter((item) => item.name === recipeName);
        // try {
        check[0] = checkFav[0].name;
        // } catch (err) {
        // userProfile()
        // console.warn(err)
        // }
    } else if (data === 'empty') {
    } else {
        setData('empty')
    }
    console.log(check);
    let listFav = [];
    if (check === recipeName) {
        listFav[0] = {
            name: check,
            favorite: true
        }
    } else if (check != recipeName) {
        listFav[0] = {
            name: check,
            favorite: false
        }
    }
    setIsFavorite(listFav[0].favorite)
}
</code>```

答:
checkFav does not seem to get resolved or checkFav is not what you expect it to be at least

```<code>checkFav = data.filter((item) => item.name === recipeName);
</code>```

it looks like this is not resolving to anything at least not at the point where you want it to. To change it you could use async wait or .then() chain.
Something like:

```<code>checkFav = data.filter((item) => item.name === recipeName)
.then(resp =>{ DO SOMETHING WHERE CHECKFAV IS NEEDED}).catch [...]
</code>```

Body:
I keep getting every time I enter this page/first-time app load data unless I try to ctrl+s file while android on debugging, the app works fine.
How do I fix this? Thx:)

error on filter multidimensional array then I call the already filter array name

const userProfile = async () => {
    let recipeId = props.route.params?.id ?? null;
    // let recipeId = 3;
    setGiveId(recipeId)
    const list = await authAction.RecipeShow(recipeId);
    setrefresh(list)
    let dataShow = list.data;
    setRecipeName(dataShow.name)
    setImage(dataShow.imageUrl)
    setDescription(dataShow.description)
    let dataFav = await authAction.FavRecipe()
    setData(dataFav.data)
    setIsLoading(false)
    let checkFav = ''
    let check = []
    if (data) {
        checkFav = data.filter((item) => item.name === recipeName);
        // try {
        check[0] = checkFav[0].name;
        // } catch (err) {
        // userProfile()
        // console.warn(err)
        // }
    } else if (data === 'empty') {
    } else {
        setData('empty')
    }
    console.log(check);
    let listFav = [];
    if (check === recipeName) {
        listFav[0] = {
            name: check,
            favorite: true
        }
    } else if (check != recipeName) {
        listFav[0] = {
            name: check,
            favorite: false
        }
    }
    setIsFavorite(listFav[0].favorite)
}

Body:
checkFav does not seem to get resolved or checkFav is not what you expect it to be at least

checkFav = data.filter((item) => item.name === recipeName);

it looks like this is not resolving to anything at least not at the point where you want it to. To change it you could use async wait or .then() chain.
Something like:

checkFav = data.filter((item) => item.name === recipeName)
.then(resp =>{ DO SOMETHING WHERE CHECKFAV IS NEEDED}).catch [...]