问:
Retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list
I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere.

This is the code, the dropdown has a list of years from 2020 to the current year.

I store the year in local storage on change and in Chrome Dev Tools you can see how the stored variable changes when other years are chosen from the dropdown.

So far so good. But when I try to retrieve the year in the userSelectedYearStorage variable the last console.log line won't show. What am I doing wrong? Thanks!

```<code>    <body>
      <div id="app">
        <select id="yearSelection">
          <option value="0" selected>Select a year</option>
        </select>
      </div>

          <script>

            var yearSelection = document.getElementById("yearSelection");
            var currentYear = new Date().getFullYear();
            for (let y = 2020; y <= currentYear; y++) {
              var element = document.createElement("option");
              element.textContent = y;
              element.value = y;
              yearSelection.appendChild(element);
            }

            var userSelectedYear = 0;
            $("#yearSelection").on("change", function () {
              userSelectedYear = this.value;
              console.log("userSelectedYear inside on change: " + userSelectedYear);
              localStorage.setItem("userSelectedYear", userSelectedYear);
            });

            var userSelectedYearStorage = localStorage.getItem('userSelectedYear')
//this line below won't be printed:
            console.log("userSelectedYear outside on change: " + userSelectedYearStorage);

          </script>
        </body>
</code>```

答: The last console.log is reading only when the page load the onload event of your body then if you trigged the event from the dropdown this console.log is never read.</p>

Body:
I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere.

This is the code, the dropdown has a list of years from 2020 to the current year.

I store the year in local storage on change and in Chrome Dev Tools you can see how the stored variable changes when other years are chosen from the dropdown.

So far so good. But when I try to retrieve the year in the userSelectedYearStorage variable the last console.log line won't show. What am I doing wrong? Thanks!

        <select id="yearSelection">
          <option value="0" selected>Select a year</option>
        </select>


来源: stackexchange

问:
What is the best way to import SVG using React.JS

My team and I are building a react application and we want to import SVGs not as a string so we'll have the ability to use it as a component.

Since we've installed the project using CRA, SVGR is already installed and is in webpack configuration.

We wanted to know if there's any other way to import the SVG file and not to use the import {ReactComponent as Logo} from '../path' but use something like import Logo from '../path'.

Also is there any benefits from using it that way?
Actually we're able to import it the way we want but we can't use it outside of an image tag.

Thanks.

答:
You can create Your custom Component like

```<code>const ArrowIcon = (props)=>{
  return (
   <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props}>
  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
)
}
</code>```

Warning:
Careful with Props of SVG. because In React, SVG Attributes may vary from SVG in HTML!

You can use it by

```<code>
import ArrowIcon from "path/to/svgComponent"

const SimpleReact = ()=>{
  return (
    <div>
      Arrow Icon
      <ArrowIcon className="class" />
    </div>
  )
}
</code>```

I hope It would work fine ;-)

You can also try SVGR which an awesome library to work with React and SVG.
You can download it with

```<code>yarn add -D @svgr/cli
</code>```

Transforms a single file by specifying file as the single argument.

```<code>npx @svgr/cli -- icons/clock-icon.svg
</code>```

You can find more in their Official Docs Link here

ContentLicense: CC BY-SA 4.0

Body:
You can create Your custom Component like

const ArrowIcon = (props)=>{
  return (
   <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" {...props}>
  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
)
}

Warning:
Careful with Props of SVG. because In React, SVG Attributes may vary from SVG in HTML!

You can use it by

import ArrowIcon from "path/to/svgComponent"

const SimpleReact = ()=>{
  return (
    <div>
      Arrow Icon
      <ArrowIcon className="class" />
    </div>
  )
}

I hope It would work fine ;-)

You can also try SVGR which an awesome library to work with React and SVG.
You can download it with

yarn add -D @svgr/cli

Transforms a single file by specifying file as the single argument.

npx @svgr/cli -- icons/clock-icon.svg

You can find more in their Official Docs Link here


问:
How can I embed Youtube homepage to my website iframe or embed or object element?
In HTML ,
if I do this ->

or,
 <embed src="https://www.youtube.com/"></embed>
or,
 <object data="https://www.youtube.com/"></embed>

it shows me an error { Refused to display 'https://www.youtube.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. }
and says youtube.com refused to connect.
can I get rid off?
Is there any way to show youtube homepage to my website  iframe  or  embed  or  object  element?

答:
You should always read the docs first:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

You cannot embed youtube.com directly in an iframe, because the setting X-Frame-Options: sameorigin only allows embeddings on websites which run on the same domain (in this case youtube.com).

What you can do instead is embedding the YouTube player: https://developers.google.com/youtube/player_parameters


问:
Running Python codes with cuda support in Google Colab
I don't have GPU support in my Macbook pro. I uploaded a directory of codes in Google colab to make use of the Cuda support. However, I see the code is unable to access other files in folders in the current directory. Please advise.

enter image description here

enter image description here

答:
First, you need to mount your drive by using the following script.

from google.colab import drive

drive.mount('address of your directory')


问:
How create a correct file path with a Python API program that is running inside a Docker Container?
My python progam is creating wrong file path.
The file path formed is wrong : '/autocameratest2\data\TestImages/7_vw_test.png'
The correct file path should be: '/autocameratest2/data/TestImages/7_vw_test.png'

```<code>  The file path is fp = builtins.open(filename, "rb")
    FileNotFoundError: [Errno 2] No such file or directory: '/autocameratest2\\data\\TestImages/7_vw_test.png'
    172.17.0.1 - - [05/Feb/2022 17:34:22] "POST /places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png HTTP/1.1" 500 -
</code>```

In the python api program, the below URL
http://127.0.0.1:5000/places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png
returns a json file. The code works fine in VisualStudio code or outside docker. It python code give a path problem inside docker.

```<code>image1test_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image1test)
image2perfect_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image2perfect)
test_results = generate_report(camid, image1test_path, image2perfect_path)
test_names = ['CamId','Blur','check_scale','noise','scrolled','allign','mirror','blackspots','ssim_score','staticlines','rotation_deg']
</code>```

答:
The following approach helped my create a file path that I wanted. like this "/autocameratest2/data/TestImages"

```<code>image1test_path = os.path.join('data','TestImages',image1test)
image2perfect_path = os.path.join('data','TestImages',image2perfect)
</code>```

Other techniques which I tried for building the path is below. These are good though it did not solve my problme.

```<code>import pathlib
#image1test_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image2perfect)

#image1test_path = pathlib.Path('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path('data', 'TestImages', args.image2perfect)
</code>```

Body:
My python progam is creating wrong file path.
The file path formed is wrong : '/autocameratest2\data\TestImages/7_vw_test.png'
The correct file path should be: '/autocameratest2/data/TestImages/7_vw_test.png'

  The file path is fp = builtins.open(filename, "rb")
    FileNotFoundError: [Errno 2] No such file or directory: '/autocameratest2\\data\\TestImages/7_vw_test.png'
    172.17.0.1 - - [05/Feb/2022 17:34:22] "POST /places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png HTTP/1.1" 500 -

In the python api program, the below URL
http://127.0.0.1:5000/places?camid=1&image1test=7_vw_test.png&image2perfect=5_vw_master.png
returns a json file. The code works fine in VisualStudio code or outside docker. It python code give a path problem inside docker.

image1test_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image1test)
image2perfect_path = os.path.join(IMAGE_FOLD_PATH,'autocameratest2\data\TestImages',image2perfect)
test_results = generate_report(camid, image1test_path, image2perfect_path)
test_names = ['CamId','Blur','check_scale','noise','scrolled','allign','mirror','blackspots','ssim_score','staticlines','rotation_deg']

Body:
The following approach helped my create a file path that I wanted. like this "/autocameratest2/data/TestImages"

image1test_path = os.path.join('data','TestImages',image1test)
image2perfect_path = os.path.join('data','TestImages',image2perfect)

Other techniques which I tried for building the path is below. These are good though it did not solve my problme.

import pathlib
#image1test_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path.cwd().joinpath('data', 'TestImages', args.image2perfect)

#image1test_path = pathlib.Path('data', 'TestImages', args.image1test)
#image2perfect_path = pathlib.Path('data', 'TestImages', args.image2perfect)


问:
Angular - How to disable Menu Item dynamically?
I struggle to get a menu component running. I want to be able to disable a menu item, but i also don't want to have to much menu logic in the caller/user of the menu (here app-component).

So a refresh or something would not be so nice i think?

I am using onPush in the menu component but i don't think thats a problem. Even Using immutable menu items in the app component wouldn't help i think. The creation of the items in the constructor is the problem i think, but i don't know how to do it better.

A complicated way in the app componeent wouldn't be nice because the menu is used from menu components in this way.

Maybe a automatic refresh of the item(s) after a on() call could be the solution? But how?

Or should i create an observable/subject isDisabled$ and whenever the defined valued in that subject (app properties) i need to trigger the ChangeDetection?

Or do i need to make an Observable out of the menuItems and give them via async pipe to the menuItem?

Anybody some tipps? (In best case a good Best Practice :D )

Or is there a special CDK way to do it? I know there is a disabled directive but i think i would have the same problem as with the menu-item.disabled property

https://stackblitz.com/edit/angular-mat-disable-fn6bj5?file=app/app.component.ts

答:
looking at how you designed your menu component using href  you'll have to use styles to disable items. just add an ngClass attribute to each item with the disabled predicate in order to do this.

the template should contain something like:

```<code><a *ngIf="node.on" (click)="node.on()" [ngClass]="{'disabled-item':node.disabled()}"> {{node.name}} </a>
</code>```

and the style should contain:

```<code>.disabled-item {
  pointer-events: none;
  cursor: default;
}
</code>```

by disabling the pointer-events you will get the result you wanted.

Body:
looking at how you designed your menu component using href <a> you'll have to use styles to disable items. just add an ngClass attribute to each item with the disabled predicate in order to do this.

the template should contain something like:

<a *ngIf="node.on" (click)="node.on()" [ngClass]="{'disabled-item':node.disabled()}"> {{node.name}} </a>

and the style should contain:

.disabled-item {
  pointer-events: none;
  cursor: default;
}

by disabling the pointer-events you will get the result you wanted.


问:
How to set nat_gateway_id in aws_route_table
main.tf

```<code>module "vpc" {
  source = "../modules/aws/vpc"

  env_prefix  = "prod"
  environment = "production"
  env_name    = "test"
  vpc_cidr    = "10.1.0.0/16"

  public_subnet_cidrs = {
    test-prod-nat = {
      subnet = "10.1.15.0/24"
      name   = "test-prod-nat"
      az     = "ap-northeast-1a"
    }
  }
}
</code>```

nat.tf

```<code>resource "aws_nat_gateway" "private" {
  for_each = var.public_subnet_cidrs

  allocation_id = aws_eip.nat_gateway.id
  subnet_id     = aws_subnet.public[each.key].id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s_%s", var.env_prefix, var.env_name, "nat-gateway")
    }
  )

  lifecycle {
    prevent_destroy = false
  }
}
</code>```

route_table.tf

```<code>/**
 * for private subnet
 */
resource "aws_route_table" "private" {
  vpc_id = aws_vpc.dandori.id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s", var.env_prefix, var.env_name)
    }
  )

  route {
    cidr_block = "0.0.0.0/0"
    nat_gateway_id = [
      for v in aws_nat_gateway.private : v.id
    ]
  }

  lifecycle {
    prevent_destroy = false
  }
}
</code>```

When I run the terraform plan after creating the above tf file, I get the following Error

【Error】

```<code>╷
│ Error: Incorrect attribute value type
│
│   on ../modules/aws/vpc/route_table.tf line 55, in resource "aws_route_table" "private":
│   55:     nat_gateway_id = [
│   56:       for v in aws_nat_gateway.private : v.id
│   57:     ]
│     ├────────────────
│     │ aws_nat_gateway.private is object with 1 attribute "test-prod-nat"
│
│ Inappropriate value for attribute "nat_gateway_id": string required.
</code>```

route_table.tf and nat.tf will be files in the module
I'm trying to set the nat_gateway_id in route_table.tf using the for loop method, but I can't set it correctly as shown in the Error message.

What should I do to solve this problem?
Please give me some advice.

答:
If you want to create a route table for each aws_nat_gateway.private, then it should be:

```<code>resource "aws_route_table" "private" {

  for_each = aws_nat_gateway.private

  vpc_id = aws_vpc.dandori.id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s", var.env_prefix, var.env_name)
    }
  )

  route {
    cidr_block = "0.0.0.0/0"
    nat_gateway_id = each.value["id"]
  }

  lifecycle {
    prevent_destroy = false
  }
}
</code>```

Body:
main.tf

module "vpc" {
  source = "../modules/aws/vpc"

  env_prefix  = "prod"
  environment = "production"
  env_name    = "test"
  vpc_cidr    = "10.1.0.0/16"

  public_subnet_cidrs = {
    test-prod-nat = {
      subnet = "10.1.15.0/24"
      name   = "test-prod-nat"
      az     = "ap-northeast-1a"
    }
  }
}

nat.tf

resource "aws_nat_gateway" "private" {
  for_each = var.public_subnet_cidrs

  allocation_id = aws_eip.nat_gateway.id
  subnet_id     = aws_subnet.public[each.key].id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s_%s", var.env_prefix, var.env_name, "nat-gateway")
    }
  )

  lifecycle {
    prevent_destroy = false
  }
}

route_table.tf

/**
 * for private subnet
 */
resource "aws_route_table" "private" {
  vpc_id = aws_vpc.dandori.id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s", var.env_prefix, var.env_name)
    }
  )

  route {
    cidr_block = "0.0.0.0/0"
    nat_gateway_id = [
      for v in aws_nat_gateway.private : v.id
    ]
  }

  lifecycle {
    prevent_destroy = false
  }
}

When I run the terraform plan after creating the above tf file, I get the following Error

【Error】

╷
│ Error: Incorrect attribute value type
│
│   on ../modules/aws/vpc/route_table.tf line 55, in resource "aws_route_table" "private":
│   55:     nat_gateway_id = [
│   56:       for v in aws_nat_gateway.private : v.id
│   57:     ]
│     ├────────────────
│     │ aws_nat_gateway.private is object with 1 attribute "test-prod-nat"
│
│ Inappropriate value for attribute "nat_gateway_id": string required.

route_table.tf and nat.tf will be files in the module
I'm trying to set the nat_gateway_id in route_table.tf using the for loop method, but I can't set it correctly as shown in the Error message.

What should I do to solve this problem?
Please give me some advice.

Body:
If you want to create a route table for each aws_nat_gateway.private, then it should be:

resource "aws_route_table" "private" {

  for_each = aws_nat_gateway.private

  vpc_id = aws_vpc.dandori.id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s", var.env_prefix, var.env_name)
    }
  )

  route {
    cidr_block = "0.0.0.0/0"
    nat_gateway_id = each.value["id"]
  }

  lifecycle {
    prevent_destroy = false
  }
}


问:
Javascript split function for getting name from a whole link?
I have several link like this:

```<code>https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html
</code>```

Or, it can be:

```<code>https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html
</code>```

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

答:
Javascript solution

```<code>const domain = new URL(url).hostname.replace('www.', '');
</code>```

const urls = [
  'https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.htmll',
  'https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html',
  'https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html',
];

urls.map((url) => {
  const domain = new URL(url).hostname.replace('www.', '');
  console.log(domain)
});```

Body:
I have several link like this:

https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html

Or, it can be:

https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html

https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.html

Anything. But I need the domain name. How can I get that.

Here from this two links, I need:

Finace Yahoo

Globe News Wire

Daily Fx

How can I find that using JavaScript.

Body:
Javascript solution

const domain = new URL(url).hostname.replace('www.', '');

const urls = [
  'https://www.dailyfx.com/forex/fundamental/forecast/weekly/title/2022/02/06/Mexican-Peso-Outlook-US-Inflation-Data-Banxico-Decision-will-Be-Key-for-USDMXN.htmll',
  'https://finance.yahoo.com/m/597b7dc4-eecf-3b45-83ac-fa87ba542bbf/bitcoin-is-back-over-%2441%2C000.html',
  'https://www.globenewswire.com/news-release/2022/02/05/2379566/673/en/ROSEN-GLOBAL-INVESTOR-COUNSEL-Encourages-Reata-Pharmaceuticals-Inc-Investors-With-Losses-Over-100K-to-Secure-Counsel-Before-Important-February-18-Deadline-in-Securities-Class-Actio.html',
];

urls.map((url) => {
  const domain = new URL(url).hostname.replace('www.', '');
  console.log(domain)
});


问:
Need to output javascript date object from a php json_encode call
```<code>$array = array('start'=>"new Date(".date("Y",strtotime($start_date)).")");
$myJson = json_encode($array);
</code>```

The returned json is a string, how can i convert the dates to objects? I'm using the jquery calendar plugin and it wants a date object. Thanks!

答:
Instead of trying to send javascript to the browser send just a unix timestamp and make a date with that on the server

PHP

```<code>echo json_encode(array('start' => mktime(date("Y",strtotime($start_date)))));
</code>```

JS

```<code>var val = JSON.parse(json);
var date = new Date(val['start']);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
$array = array('start'=>"new Date(".date("Y",strtotime($start_date)).")");
$myJson = json_encode($array);

The returned json is a string, how can i convert the dates to objects? I'm using the jquery calendar plugin and it wants a date object. Thanks!

Body:
Instead of trying to send javascript to the browser send just a unix timestamp and make a date with that on the server

PHP

echo json_encode(array('start' => mktime(date("Y",strtotime($start_date)))));

JS

var val = JSON.parse(json);
var date = new Date(val['start']);


问:
UnhandledPromiseRejectionWarning: Error: You must `await server.start()` before calling `server.applyMiddleware()` at ApolloServer
I am trying to start my nestJs server and It keeps giving me this error:

UnhandledPromiseRejectionWarning: Error: You must await server.start() before calling server.applyMiddleware()
at ApolloServer

I'm not even sure where to debug from as I am still very new at NestJs and GraphQL.

答:
We must wait for the server to get ready before adding middleware to it.</p>
```<code>    const app = express();
    const apolloServer = new ApolloServer({
        schema: await buildSchema({
            resolvers: [HelloResolver],
            validate: false,
        }),
    });

    await apolloServer.start(); // First start the server then apply middleware on it

    apolloServer.applyMiddleware({ app });

</code>```

Body:
We must wait for the server to get ready before adding middleware to it.

    const app = express();
    const apolloServer = new ApolloServer({
        schema: await buildSchema({
            resolvers: [HelloResolver],
            validate: false,
        }),
    });

    await apolloServer.start(); // First start the server then apply middleware on it

    apolloServer.applyMiddleware({ app });


问:
Error in runserver with Django on windows 10
I am using python 3.5 and windows 10, but had the same issue using windows 8, and that is the traceback i get while trying to runserver:

Traceback (most recent call last):
    File "C:\Users\noabendor87\documents\otree\manage.py", line 10, in
      execute_from_command_line(sys.argv, script_file=file)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\otree\management\cli.py", line
  177, in execute_from_command_line
      utility.execute()
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management__init__
  .py", line 346, in execute
      self.fetch_command(subcommand).run_from_argv(self.argv)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management\base.py"
  , line 394, in run_from_argv
      self.execute(*args, **cmd_options)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management\commands
  \runserver.py", line 49, in execute
      super(Command, self).execute(*args, **options)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management\base.py"
  , line 445, in execute
      output = self.handle(*args, **options)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management\commands
  \runserver.py", line 88, in handle
      self.run(**options)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\core\management\commands
  \runserver.py", line 97, in run
      autoreload.main(self.inner_run, None, options)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\utils\autoreload.py", li
  ne 336, in main
      reloader(wrapped_main_func, args, kwargs)
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\utils\autoreload.py", li
  ne 307, in python_reloader
      exit_code = restart_with_reloader()
    File "c:\users\noabendor87\appdata\local\programs\python\python35-32\lib\site-packages\django\utils\autoreload.py", li
  ne 293, in restart_with_reloader
      exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
  UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

I have already tried following the instructions in the following link:
http://stackoverflow.com/questions/25714826/error-in-manage-py-runserver-with-django-on-windows-8-1

but it did not help.

This is how the lines of code look like:

enter image description here

(Since Im a new user I cannot paste the image to the original post)

Anyone have encountered something similar and have a solution?

答: first I will like you check the django version you are working with my "type python -m django --version" or "pip freeze". check weather its compatible with the python version on your pc. if it's not install compatible python version. then check weather  "init.py" is within your project directory, if not add it to your project directory. then run "Set-ExecutionPolicy -Scope CurrentUser Unrestricted" on your terminal. then run activate your virtualenv, then run "python manage.py runserver"


问:
Why is "end if" missing at the end of an if-else sequence?
The error is

teclat.vhdl:57:12: 'if' is expected instead of 'process'

The end if is where it is supposed to be. I don't understand why it doesn't compile like it's missing an end if always.

```<code>architecture v1 of teclat is
begin
    process(Buttons, COL, ROW) begin

    if (Buttons(1) = '1') then
        COL <= "100";
        ROW <= "100";
    else if (Buttons(2) = '1') then
        COL <= "010";
        ROW <= "100";
    else if (Buttons(3) = '1') then
        COL <= "001";
        ROW <= "100";
    else
        ROW <= "111";
    end if;

    end process;
end v1;
</code>```

答:
There is one end if where it is supposed to be, but you are missing the ones for the remaining if statements you opened.

Your code is currently processed as

```<code>if (Buttons(1) = '1') then
    COL <= "100";
    ROW <= "100";
else
    if (Buttons(2) = '1') then
        COL <= "010";
        ROW <= "100";
    else
        if (Buttons(3) = '1') then
            COL <= "001";
            ROW <= "100";
        else
            ROW <= "111";
        end if;
    end if; -- missing
end if; -- missing
</code>```

Alternatively, use elsif to avoid opening so many if statements. Now you have only a single if statement and need only one end if.

```<code>if (Buttons(1) = '1') then
    COL <= "100";
    ROW <= "100";
elsif (Buttons(2) = '1') then
    COL <= "010";
    ROW <= "100";
elsif (Buttons(3) = '1') then
    COL <= "001";
    ROW <= "100";
else
    ROW <= "111";
end if;
</code>```

Body:
The error is

teclat.vhdl:57:12: 'if' is expected instead of 'process'

The end if is where it is supposed to be. I don't understand why it doesn't compile like it's missing an end if always.

architecture v1 of teclat is
begin
    process(Buttons, COL, ROW) begin

    if (Buttons(1) = '1') then
        COL <= "100";
        ROW <= "100";
    else if (Buttons(2) = '1') then
        COL <= "010";
        ROW <= "100";
    else if (Buttons(3) = '1') then
        COL <= "001";
        ROW <= "100";
    else
        ROW <= "111";
    end if;

    end process;
end v1;

Body:
There is one end if where it is supposed to be, but you are missing the ones for the remaining if statements you opened.

Your code is currently processed as

if (Buttons(1) = '1') then
    COL <= "100";
    ROW <= "100";
else
    if (Buttons(2) = '1') then
        COL <= "010";
        ROW <= "100";
    else
        if (Buttons(3) = '1') then
            COL <= "001";
            ROW <= "100";
        else
            ROW <= "111";
        end if;
    end if; -- missing
end if; -- missing

Alternatively, use elsif to avoid opening so many if statements. Now you have only a single if statement and need only one end if.

if (Buttons(1) = '1') then
    COL <= "100";
    ROW <= "100";
elsif (Buttons(2) = '1') then
    COL <= "010";
    ROW <= "100";
elsif (Buttons(3) = '1') then
    COL <= "001";
    ROW <= "100";
else
    ROW <= "111";
end if;


问:
Powershell assignment in expression?
Does Powershell have an operator like Python's :=, which can assign a variable within an expression? (e.g., if (match := pattern.search(data)) is not None)

Suppose I want to store a value in Powershell as a variable, but also pass it down the pipeline. Is there a more elegant way than ...| ForEach-Object { $foo = $_.split(': ')[1]; $foo } |...?

答:
I'm trying to pipe an expression, but also store it as a variable for
2 steps down the pipe

In this case you might consider using the common parameter -PipelineVariable (-pv). It has the advantage that the variable doesn't pollute the parent scope of the pipeline as explicitly assigning to a variable would do. It will just live as long as the pipeline runs.

```<code>...| ForEach-Object -PipelineVariable foo { $_.split(': ')[1] }
</code>```

A reproducible example will make the difference clearer:

```<code>1..3 | ForEach-Object { ($a = $_) } | ForEach-Object { $_ * 2 } | ForEach-Object { "$a * 2 = $_" }
$a  # Print the value of $a
</code>```

Output:

1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
3
```
<p>Note that it ouputs the value of <code>$a</code> in the last line, because the variable has "leaked" from the pipeline into the parent scope. This may be an undesired side effect when you actually wanted to use <code>$a</code> only within the pipeline scope.</p>
<p>Now see what happens when we change to <code>-PipelineVariable</code>:</p>
```1..3 | ForEach-Object -PipelineVariable a { $_ } | ForEach-Object { $_ * 2 } | ForEach-Object { "$a * 2 = $_" }
$a  # Print the value of $a
```
<p><strong>Output:</strong></p>
<pre class="lang-text prettyprint-override"><code>1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
</code>```

Now $a after the pipeline doesn't output anything, because the variable is defined only within the pipeline scope.

Title: Powershell assignment in expression?

Body:
I'm trying to pipe an expression, but also store it as a variable for
2 steps down the pipe

In this case you might consider using the common parameter -PipelineVariable (-pv). It has the advantage that the variable doesn't pollute the parent scope of the pipeline as explicitly assigning to a variable would do. It will just live as long as the pipeline runs.

...| ForEach-Object -PipelineVariable foo { $_.split(': ')[1] }

A reproducible example will make the difference clearer:

1..3 | ForEach-Object { ($a = $_) } | ForEach-Object { $_ * 2 } | ForEach-Object { "$a * 2 = $_" }
$a  # Print the value of $a

Output:

1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
3

Note that it ouputs the value of $a in the last line, because the variable has "leaked" from the pipeline into the parent scope. This may be an undesired side effect when you actually wanted to use $a only within the pipeline scope.

Now see what happens when we change to -PipelineVariable:

1..3 | ForEach-Object -PipelineVariable a { $_ } | ForEach-Object { $_ * 2 } | ForEach-Object { "$a * 2 = $_" }
$a  # Print the value of $a

Output:

1 * 2 = 2
2 * 2 = 4
3 * 2 = 6

Now $a after the pipeline doesn't output anything, because the variable is defined only within the pipeline scope.


问:
Cannot find python kernels corresponding to Virtual environment on remote
I am visual studio code Version: 1.63.2 (Universal).
I am connected to a linux server where my code is located (jupyter notebook). When i open the notebook and select the python kernel, i can only find the default python kernels (from the server). I cannot find the kernels that i created which is necessary to run the notebooks.

Note: The required kernel is linked to a virtual environment on the kernel.

Please help me in linking the remote kernel to my notebook on vscode so that i can work locally on the notebooks located in remote server.

答:
You can find the answer in the second method here.
https://stackoverflow.com/a/62871909

I did a little differently:

Ctrl+Shift+P, Preferences: Open Remote Setting (SSH:your_address)

Set Python: Default Interpreter Path to your virtual environment Python path

Done


问:
Is it possible to change the variance of a base class/trait in Scala?
I would like to derive from Scala's immutable Map. It is defined as such:

```<code>trait Map[A, +B]
</code>```

Unfortunately, my implementation needs to be invariant in B. I tried the following, but without success:

```<code>def +(kv : (A, B)) : MyMap[A, B] = { ... }

override def +[B1 >: B](kv : (A, B1)) : MyMap[A, B1] =
    throw new IllegalArgumentException()
</code>```

Maybe there is a trick with @uncheckedVariance?

答:
Getting rid of covariance altogether would of course be unsound, and is not allowed.
Given m: Map[A, String], and v : Any, you can do val mm : Map[A, Any] = m + v. This is what Map definition says, and all implementors must follow. Your class may be invariant, but it must implement the full covariant interface of Map.

Now redefining + to throw an error is a different story (not very sound yet). The problem with your new + method is that after generics erasure, it has the same signature than the other + method. There is a trick: add in implicit parameter, so that you have two parameters in the signature, which makes it different from the first one.

```<code>def +(kv : (A,B))(implicit useless: A <:< A) : MyMap[A,B]
</code>```

(it doesn't really matter what implicit parameter you're looking for, as long as one is found. implicit useless: Ordering[String] works just as well)

Doing that, you have the usual problem with overloading. If you add a B without the compiler knowing it to be so, the failing method will be called. It might be better to perform a type check there so that B instances are accepted whatever. That would require getting a Manifest[B] in your map.

Body:
I would like to derive from Scala's immutable Map. It is defined as such:

trait Map[A, +B]

Unfortunately, my implementation needs to be invariant in B. I tried the following, but without success:

def +(kv : (A, B)) : MyMap[A, B] = { ... }

override def +[B1 >: B](kv : (A, B1)) : MyMap[A, B1] =
    throw new IllegalArgumentException()

Maybe there is a trick with @uncheckedVariance?

Body:
Getting rid of covariance altogether would of course be unsound, and is not allowed.
Given m: Map[A, String], and v : Any, you can do val mm : Map[A, Any] = m + v. This is what Map definition says, and all implementors must follow. Your class may be invariant, but it must implement the full covariant interface of Map.

Now redefining + to throw an error is a different story (not very sound yet). The problem with your new + method is that after generics erasure, it has the same signature than the other + method. There is a trick: add in implicit parameter, so that you have two parameters in the signature, which makes it different from the first one.

def +(kv : (A,B))(implicit useless: A <:< A) : MyMap[A,B]

(it doesn't really matter what implicit parameter you're looking for, as long as one is found. implicit useless: Ordering[String] works just as well)

Doing that, you have the usual problem with overloading. If you add a B without the compiler knowing it to be so, the failing method will be called. It might be better to perform a type check there so that B instances are accepted whatever. That would require getting a Manifest[B] in your map.


问:
How can I fetch WhatsApp username of a person using python?
I want to know the WhatsApp username of a person he is using on whatsapp using python. Is it possible using the pyWhatKit Module?</p>

答:
Read this article.

pywhatkit is a Python library for sending WhatsApp messages at a certain time

So this is its principal feature, and a few others:

Send WhatsApp messages.

Play a YouTube video.

Perform a Google Search.

So I guess the WhatsApp API doesn't return user's data, or at least pyWhatKit still can't handle this data.

I would suggest to use pure selenium instead, like described here.


问:
How to use Apollo useMutation in custom React hook
I'm still having issues with wrapping my head around Hooks. I constantly run into issues where it complains I'm doing an Invalid hook call.

This time, it's when trying to use the useMutation hook from Apollo inside a custom hook.

I'd appreciate if someone can tell me what I'm doing wrong.

Component (where I'm calling my custom hook)

```<code>export default function MyComponent() {

    const { loading, error, data } = useQuery( GET_ORDERS );

    const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
        metafieldResp = useSetMetafields( { customerId, value: orders, field: 'duplicateOrders' } );
    }

    @useEffect( () => {
        setOrdersInMetafields( orders );
    }, [ orders ] );
}
</code>```

Custom hook

```<code>export const useSetMetafields( { customerId, value, field }, { customerId: string, value: any, field: string } ) => {
    [ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );

    useEffect( () => {
        onUpdateMetafield();
    }, [] );

    const onUpdateMetafield = () => {
        updateMetafield( {
            variables: {
                input: {
                    id: customerId,
                    metafields: [
                        {
                            namespace: 'app-name',
                            key: field,
                            value: JSON.stringify( value ),
                            type: 'string'
                        }
                    ]
                }
            }
        } );
    }
}
</code>```

Resulting error:

```<code>Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
</code>```

答:
Always use Hooks at the top level of your React function. You should call useSetMetafields right up next to useQuery. To make your code work, you'll need to change the aspect of your custom hook. My proposal, with  the amount of code you've provided:

export default function MyComponent() {
    const { loading, error, data } = useQuery( GET_ORDERS );
    { doUpdateMetaField } = useSetMetafields();

  const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
// Make doUpdateMetaField function return something if you need and collect it here
       doUpdateMetaField( { customerId, value: orders, field: 'duplicateOrders' } );
    }
    useEffect( () => {
        setOrdersInMetafields( orders );
    }, [ orders ] );
}

```
```export const useSetMetafields = () => {
    [ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );

    const doUpdateMetaField = ({ customerId, value, field }, { customerId: string, value: any, field: string } ) => {
        updateMetafield( {
            variables: {
                input: {
                    id: customerId,
                    metafields: [
                        {
                            namespace: 'app-name',
                            key: field,
                            value: JSON.stringify( value ),
                            type: 'string'
                        }
                    ]
                }
            }
        } );
    }

return {
   doUpdateMetaField
}
}

```

Body:
I'm still having issues with wrapping my head around Hooks. I constantly run into issues where it complains I'm doing an Invalid hook call.

This time, it's when trying to use the useMutation hook from Apollo inside a custom hook.

I'd appreciate if someone can tell me what I'm doing wrong.

Component (where I'm calling my custom hook)

export default function MyComponent() {

    const { loading, error, data } = useQuery( GET_ORDERS );

    const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
        metafieldResp = useSetMetafields( { customerId, value: orders, field: 'duplicateOrders' } );
    }

    @useEffect( () => {
        setOrdersInMetafields( orders );
    }, [ orders ] );
}

Custom hook

export const useSetMetafields( { customerId, value, field }, { customerId: string, value: any, field: string } ) => {
    [ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );

    useEffect( () => {
        onUpdateMetafield();
    }, [] );

    const onUpdateMetafield = () => {
        updateMetafield( {
            variables: {
                input: {
                    id: customerId,
                    metafields: [
                        {
                            namespace: 'app-name',
                            key: field,
                            value: JSON.stringify( value ),
                            type: 'string'
                        }
                    ]
                }
            }
        } );
    }
}

Resulting error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Body:
Always use Hooks at the top level of your React function. You should call useSetMetafields right up next to useQuery. To make your code work, you'll need to change the aspect of your custom hook. My proposal, with  the amount of code you've provided:

export default function MyComponent() {
    const { loading, error, data } = useQuery( GET_ORDERS );
    { doUpdateMetaField } = useSetMetafields();

  const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
// Make doUpdateMetaField function return something if you need and collect it here
       doUpdateMetaField( { customerId, value: orders, field: 'duplicateOrders' } );
    }
    useEffect( () => {
        setOrdersInMetafields( orders );
    }, [ orders ] );
}

export const useSetMetafields = () => {
    [ updateMetafield, { loading, error, data } ] = useMutation( SET_METAFIELD_ON_CUSTOMER );

    const doUpdateMetaField = ({ customerId, value, field }, { customerId: string, value: any, field: string } ) => {
        updateMetafield( {
            variables: {
                input: {
                    id: customerId,
                    metafields: [
                        {
                            namespace: 'app-name',
                            key: field,
                            value: JSON.stringify( value ),
                            type: 'string'
                        }
                    ]
                }
            }
        } );
    }

return {
   doUpdateMetaField
}
}


问:
ModuleNotFoundError: No module named 'djoser' while running Django + Docker project
To add registration to django-project, I decided to use 'djoser' library. But while making migrations with
docker-compose run server python manage.py makemigrations
, the same error raises:

```<code>Creating school-co_server_run ... done
Traceback (most recent call last):
  File "/home/web/server/manage.py", line 22, in <module>
    main()
  File "/home/web/server/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/home/web/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/web/venv/lib/python3.9/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'djoser'
ERROR: 1
</code>```

The thing is that I already pip installed djoser (using the newest update of pip), I froze djoser too with the help of requirements.txt:

```<code>asgiref==3.2.10
attrs==21.2.0
Django==3.1
django-environ==0.8.1
django-extensions==3.1.5
django-filter==21.1
djangorestframework==3.12.4
djangorestframework-camel-case==1.2.0
drf-spectacular==0.21.0
inflection==0.5.1
jsonschema==4.2.1
Markdown==3.3.6
mysqlclient==2.1.0
Pillow==8.4.0
pyrsistent==0.18.0
pytz==2021.3
PyYAML==6.0
sqlparse==0.4.2
uritemplate==4.1.1
djoser==2.0.1
pandas=1.1.3
</code>```

But it still doesn't work. Section of 'settings.py' INSTALLED_APPS also is correct:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base',
    'school_co',
    'django_extensions',
    'rest_framework',
    'rest_framework.authtoken',
    'drf_spectacular',
    'djoser',
    'rest_framework_simplejwt',
]
</code>```

I use docker-compose, and here is the web/Dockerfile in which the operation happens:

```<code>FROM python:3.9-slim-bullseye

ENV PYTHONUNBUFFERED=1

RUN set -ex \
    && apt-get update \
    && apt-get install curl default-libmysqlclient-dev gcc -y \
    && rm -rf /var/lib/apt/lists/*

RUN useradd --create-home --shell /bin/bash --home /home/web web
USER web
WORKDIR /home/web

COPY etc/requirements.txt ./etc/requirements.txt

RUN set -ex \
    && python -m venv /home/web/venv \
    && ./venv/bin/pip install --upgrade pip \
    && ./venv/bin/pip install --no-cache-dir -r ./etc/requirements.txt

COPY etc/env ./etc/env

ENV VIRTUAL_ENV /home/web/venv
ENV PATH /home/web/venv/bin:$PATH
WORKDIR /home/web/server
</code>```

答:
Seems that 'djoser' doesn't work without 'pandas'.

That is why it is needed to add this library too. My mistake was that I accidentally typed '=' instead of '==' in requirments.txt.

Body:
To add registration to django-project, I decided to use 'djoser' library. But while making migrations with
docker-compose run server python manage.py makemigrations
, the same error raises:

Creating school-co_server_run ... done
Traceback (most recent call last):
  File "/home/web/server/manage.py", line 22, in <module>
    main()
  File "/home/web/server/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/web/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute
    django.setup()
  File "/home/web/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/web/venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/web/venv/lib/python3.9/site-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'djoser'
ERROR: 1

The thing is that I already pip installed djoser (using the newest update of pip), I froze djoser too with the help of requirements.txt:

asgiref==3.2.10
attrs==21.2.0
Django==3.1
django-environ==0.8.1
django-extensions==3.1.5
django-filter==21.1
djangorestframework==3.12.4
djangorestframework-camel-case==1.2.0
drf-spectacular==0.21.0
inflection==0.5.1
jsonschema==4.2.1
Markdown==3.3.6
mysqlclient==2.1.0
Pillow==8.4.0
pyrsistent==0.18.0
pytz==2021.3
PyYAML==6.0
sqlparse==0.4.2
uritemplate==4.1.1
djoser==2.0.1
pandas=1.1.3

But it still doesn't work. Section of 'settings.py' INSTALLED_APPS also is correct:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'base',
    'school_co',
    'django_extensions',
    'rest_framework',
    'rest_framework.authtoken',
    'drf_spectacular',
    'djoser',
    'rest_framework_simplejwt',
]

I use docker-compose, and here is the web/Dockerfile in which the operation happens:

FROM python:3.9-slim-bullseye

ENV PYTHONUNBUFFERED=1

RUN set -ex \
    && apt-get update \
    && apt-get install curl default-libmysqlclient-dev gcc -y \
    && rm -rf /var/lib/apt/lists/*

RUN useradd --create-home --shell /bin/bash --home /home/web web
USER web
WORKDIR /home/web

COPY etc/requirements.txt ./etc/requirements.txt

RUN set -ex \
    && python -m venv /home/web/venv \
    && ./venv/bin/pip install --upgrade pip \
    && ./venv/bin/pip install --no-cache-dir -r ./etc/requirements.txt

COPY etc/env ./etc/env

ENV VIRTUAL_ENV /home/web/venv
ENV PATH /home/web/venv/bin:$PATH
WORKDIR /home/web/server


问:
I'm getting a problem with apache commons compress
I'm getting this error while extracting a .7z protected file

org.tukaani.xz.CorruptedInputException: Compressed data is corrupt

and I'm using this code

```<code>public static void unSevenZipFile(String from,String to,String pass) throws Exception
{
    // Get 7zip file.
    SevenZFile sevenZFile = new SevenZFile(new File(from),pass.getBytes("UTF16LE"));

    SevenZArchiveEntry entry;
    while ((entry = sevenZFile.getNextEntry()) != null)
    {

        File file = new File(to + entry.getName());
        Log.d("unzip","Un seven zipping - " + file);
        // Create directory before streaming files.
        String dir = file.toPath().toString().substring(0, file.toPath().toString().lastIndexOf("/"));
        Files.createDirectories(new File(dir).toPath());
        // Stream file content
        byte[] content = new byte[(int) entry.getSize()];
        sevenZFile.read(content);
        Files.write(file.toPath(), content);

    }

}
</code>```

if You know what's the problem please tell me.
Thanks in advance

答:
The problem was I didn't place the dash in the right place.
I did both this "UTF16LE" and "UTF-16LE"
but the solution was this "UTF16-LE"</p>

Body:
I'm getting this error while extracting a .7z protected file

org.tukaani.xz.CorruptedInputException: Compressed data is corrupt

and I'm using this code

public static void unSevenZipFile(String from,String to,String pass) throws Exception
{
    // Get 7zip file.
    SevenZFile sevenZFile = new SevenZFile(new File(from),pass.getBytes("UTF16LE"));

    SevenZArchiveEntry entry;
    while ((entry = sevenZFile.getNextEntry()) != null)
    {

        File file = new File(to + entry.getName());
        Log.d("unzip","Un seven zipping - " + file);
        // Create directory before streaming files.
        String dir = file.toPath().toString().substring(0, file.toPath().toString().lastIndexOf("/"));
        Files.createDirectories(new File(dir).toPath());
        // Stream file content
        byte[] content = new byte[(int) entry.getSize()];
        sevenZFile.read(content);
        Files.write(file.toPath(), content);

    }

}

if You know what's the problem please tell me.
Thanks in advance


问:
C++ wprintf format specifier for char16_t for printing unicode string
I have the following code successfully compiled:

```<code>#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <cstddef>
#include <cstdio>
int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b";
    wprintf(L"String written with unicode codes: %ls \n", chinese);

    wchar_t arabic[] = L"أَبْجَدِيَّة عَرَبِيَّة";
    wprintf(L"String written with L-String: %ls \n", arabic);
    std::wcout << std::endl;  std::system("PAUSE");
}
</code>```

It prints:

String written with unicode codes: 书中自有黄金屋

String written with L-String: أَبْجَدِيَّة عَرَبِيَّة

However, the compiler issues a warning for chinese case (not for arabic case):

```<code>warning C4477: 'wprintf' : format string '%ls' requires an argument of type 'wchar_t *', but variadic argument 1 has type 'char16_t *'
</code>```

What would be then the correct wprintf format string?

答:
What would be then the correct wprintf format string?

There is no printf format specifier for char16_t. It does not exist.

You have to convert your char16_t string to multibyte string or wide string and print it then.

c16rtomb would be the standard C function to do it. Convert between string, u16string & u32string shows how to do it in C++.

Body:
I have the following code successfully compiled:

#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <cstddef>
#include <cstdio>
int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);

    char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b";
    wprintf(L"String written with unicode codes: %ls \n", chinese);

    wchar_t arabic[] = L"أَبْجَدِيَّة عَرَبِيَّة";
    wprintf(L"String written with L-String: %ls \n", arabic);
    std::wcout << std::endl;  std::system("PAUSE");
}

It prints:

String written with unicode codes: 书中自有黄金屋

String written with L-String: أَبْجَدِيَّة عَرَبِيَّة

However, the compiler issues a warning for chinese case (not for arabic case):

warning C4477: 'wprintf' : format string '%ls' requires an argument of type 'wchar_t *', but variadic argument 1 has type 'char16_t *'

What would be then the correct wprintf format string?


问:
Biztalk Message Promotions
I'm relatively new to Biztalk and I'm having a bit of hassle with this:

I have built a simple orchestration, hooked it up correctly to a receive port, I'm using the correct schema and map and the orchestration seems to be subscribing ok.
However, when the file I want to process gets picked up at the port I'm getting the 'could not be routed because no subscribers were found' error.
I ran a HAT query and can see the orch has an active subsription to the correct thing, is there anything else I can check on this?

答:
Is your port hooked directly to the orchestration or is the orchestration picking the message up from the message box? Has the orchestration receive been set to Activate?

What does your subscription filter look like for the orchestration?

Title: Biztalk Message Promotions


问:
Minimum element in next step in Python
This code finds the minimum of each row and scans the adjoining elements to find the next minimum. But I don't want it to return to the previous row. For example, for row 2, the min is 0.021. I want it to scan the elements 0.28 (row 2), 0.78 (row 3), 0.85 (row 3) and not 0.34 (row 1), 0.002 (row 1).

```<code>import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

#Pe = np.random.rand(3,3)
Pe = np.array([[0.32, 0.34 , 0.002],
       [0.74, 0.28, 0.021],
       [0.69, 0.78, 0.85]])
b = np.zeros((Pe.shape[0], 2))

Pw=0.5

for row_n, row in enumerate(Pe):
    # Get row min
    b[row_n][0] = np.min(row)

    # Get surroundings min
    i = np.argmin(row)
    near = []
    if row_n > 0:
      near.append(Pe[row_n-1][i])
    if row_n+1 < b.shape[0]:
      near.append(Pe[row_n+1][i])
    if i > 0:
      near.append(Pe[row_n][i-1])
    if i+1 < b.shape[1]:
      near.append(Pe[row_n][i+1])
    b[row_n][1] = min(near)

print(b)
</code>```

Current output:

```<code>[[0.002 0.021]
[0.021 0.002]
[0.69 0.74]]
</code>```

Output I want:

```<code>[[0.002 0.021]
[0.021 0.28]
[0.69 0.78]]
</code>```

答:
If you use numpy arrays, you should try to avoid explicit iterations using for loops. scipy's ndimage module can efficiently address tasks like that described in your question as it provides convenient sliding windows functions. Here, we use the minimum filter:

```<code>import numpy as np
from scipy.ndimage import minimum_filter as mf

#Pe = np.random.rand(3,3)
Pe = np.array([[0.32, 0.34 , 0.002],
       [0.74, 0.28, 0.021],
       [0.69, 0.78, 0.85]])
b = np.zeros((Pe.shape[0], 2))

#the footprint of the window, i.e., we do not consider the value itself
#(the center of the footprint array) or any value in the row above
ft = np.asarray([[0, 0, 0],
                 [1, 0, 1],
                 [1, 1, 1]])
#applying scipy's minimum filter
#mode defines what should be considered as values at the edges
#setting the edges to INF
Pe_min = mf(Pe, footprint=ft, mode="constant", cval=np.inf)

#finding rowwise index of the minimum value using np.argmin()
idx = Pe.argmin(axis=1)

#retrieving minimum values and filtered values
b[:, 0] = np.take_along_axis(Pe, idx[None].T, 1).T[0]
b[:, 1] = np.take_along_axis(Pe_min, idx[None].T, 1).T[0]

print(b)
</code>```

Sample output:

```<code>[[0.002 0.021]
 [0.021 0.28 ]
 [0.69  0.78 ]]
</code>```

It should be noted that np.argmin returns the first minimum value per row if the same minimum occurs more than once. However, this situation was not considered in your question.

Title: Minimum element in next step in Python

Body:
This code finds the minimum of each row and scans the adjoining elements to find the next minimum. But I don't want it to return to the previous row. For example, for row 2, the min is 0.021. I want it to scan the elements 0.28 (row 2), 0.78 (row 3), 0.85 (row 3) and not 0.34 (row 1), 0.002 (row 1).

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

#Pe = np.random.rand(3,3)
Pe = np.array([[0.32, 0.34 , 0.002],
       [0.74, 0.28, 0.021],
       [0.69, 0.78, 0.85]])
b = np.zeros((Pe.shape[0], 2))

Pw=0.5

for row_n, row in enumerate(Pe):
    # Get row min
    b[row_n][0] = np.min(row)

    # Get surroundings min
    i = np.argmin(row)
    near = []
    if row_n > 0:
      near.append(Pe[row_n-1][i])
    if row_n+1  0:
      near.append(Pe[row_n][i-1])
    if i+1 < b.shape[1]:
      near.append(Pe[row_n][i+1])
    b[row_n][1] = min(near)

print(b)

Current output:

[[0.002 0.021]
[0.021 0.002]
[0.69 0.74]]

Output I want:

[[0.002 0.021]
[0.021 0.28]
[0.69 0.78]]

Body:
If you use numpy arrays, you should try to avoid explicit iterations using for loops. scipy's ndimage module can efficiently address tasks like that described in your question as it provides convenient sliding windows functions. Here, we use the minimum filter:

import numpy as np
from scipy.ndimage import minimum_filter as mf

#Pe = np.random.rand(3,3)
Pe = np.array([[0.32, 0.34 , 0.002],
       [0.74, 0.28, 0.021],
       [0.69, 0.78, 0.85]])
b = np.zeros((Pe.shape[0], 2))

#the footprint of the window, i.e., we do not consider the value itself
#(the center of the footprint array) or any value in the row above
ft = np.asarray([[0, 0, 0],
                 [1, 0, 1],
                 [1, 1, 1]])
#applying scipy's minimum filter
#mode defines what should be considered as values at the edges
#setting the edges to INF
Pe_min = mf(Pe, footprint=ft, mode="constant", cval=np.inf)

#finding rowwise index of the minimum value using np.argmin()
idx = Pe.argmin(axis=1)

#retrieving minimum values and filtered values
b[:, 0] = np.take_along_axis(Pe, idx[None].T, 1).T[0]
b[:, 1] = np.take_along_axis(Pe_min, idx[None].T, 1).T[0]

print(b)

Sample output:

[[0.002 0.021]
 [0.021 0.28 ]
 [0.69  0.78 ]]

It should be noted that np.argmin returns the first minimum value per row if the same minimum occurs more than once. However, this situation was not considered in your question.


问:
golang goroutine synchronization expected behaviour
The following piece of code try to send to the channel on the main goroutine and receive from another goroutine but a few times it returns as expected but a few times it exits without printing any on the console screen

```<code>package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}
</code>```

At the same time, the following piece of code works as expected everytime, one difference is that an additional check has been added to check if the channel is closed or not which always throws the same expected output.
Does this ensure that a check on the channel is a must than optional ? or anything wrong with the code

```<code>package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data, ok := <-ch
        if !ok {
            fmt.Println("Channel closed")
            return
        }
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}
</code>```

答:
You should wait for goroutine to complete before main routine exit.</p>
```<code>package main

import (
    "fmt"
    "sync"
)

func main() {
    ch := make(chan bool)
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
    wg.Wait()
}
</code>```

Body:
The following piece of code try to send to the channel on the main goroutine and receive from another goroutine but a few times it returns as expected but a few times it exits without printing any on the console screen

package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}

At the same time, the following piece of code works as expected everytime, one difference is that an additional check has been added to check if the channel is closed or not which always throws the same expected output.
Does this ensure that a check on the channel is a must than optional ? or anything wrong with the code

package main

import "fmt"

func main() {
    ch := make(chan bool)

    go func() {
        data, ok := <-ch
        if !ok {
            fmt.Println("Channel closed")
            return
        }
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
}

Body:
You should wait for goroutine to complete before main routine exit.

package main

import (
    "fmt"
    "sync"
)

func main() {
    ch := make(chan bool)
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        data := <-ch
        fmt.Printf("Received: %t", data)
    }()
    ch <- true
    wg.Wait()
}


问:
SendKeys does not work when computer is locked using Selenium
I use python 3.9.5 and selenium 4.1.0 with Microsoft Edge 98.0.1108.43 on Windows 10 to fill a date in a text box with the code below:

#element is the web element I want to fill
element = "element_name"
date = driver.find_element(By.ID, element)

date.click()
date.clear()

#Positionate cursor at text box beginning
for i in range(1,10):
    date.send_keys(Keys.ARROW_LEFT)

#Fill the date
date.send_keys("11022022")
```
<p>I use a Windows task scheduler to run a python script when the computer is locked.</p>
<p>This code uses to work when I am logged in and using the computer, but when it's locked the send keys fail, it used to work with edge version 95, but in recent versions stopped.</p>
<p>Unfortunately, I can't simply replace the value of the element, apparently, the site has some different mechanism to fill it and I must fill it with the keyboard.</p>
```<input name="element_name" type="text" value="04/02/2022" id="ctl00_ContentPlaceHolder1_dtInicial_txtData" class="edt" style="width:90px;">
```

I also have tried to force windows to always focus on browser windows, so the webpage always has the keyboard focus, but it also does not work.

Any hint of how to solve this question? Is it a Bug?

答:
In Selenium there is a state that called headless, it allows you to work with the web page without actually "seeing" it. There is no window opening and everything works virtually. You set this state in the browser options.

```<code>EdgeOptions edgeOptions = new EdgeOptions();
            edgeOptions.UseChromium = true;
            edgeOptions.BinaryLocation =
@"C:\Program Files
(x86)\Microsoft\Edge\Application\msedge.exe";
            edgeOptions.AddArgument("headless");
            edgeOptions.AddArgument("disable-gpu");
            var msedgedriverDir = @"E:\webdriver";
            var driver =
new EdgeDriver(msedgedriverDir, edgeOptions);
</code>```

In Java, there is a class called Robot which mimic keyboard pressing, so try to find the matching library in Python.

Body:
I use python 3.9.5 and selenium 4.1.0 with Microsoft Edge 98.0.1108.43 on Windows 10 to fill a date in a text box with the code below:

#element is the web element I want to fill
element = "element_name"
date = driver.find_element(By.ID, element)

date.click()
date.clear()

#Positionate cursor at text box beginning
for i in range(1,10):
    date.send_keys(Keys.ARROW_LEFT)

#Fill the date
date.send_keys("11022022")

I use a Windows task scheduler to run a python script when the computer is locked.

This code uses to work when I am logged in and using the computer, but when it's locked the send keys fail, it used to work with edge version 95, but in recent versions stopped.

Unfortunately, I can't simply replace the value of the element, apparently, the site has some different mechanism to fill it and I must fill it with the keyboard.

<input name="element_name" type="text" value="04/02/2022" id="ctl00_ContentPlaceHolder1_dtInicial_txtData" class="edt" style="width:90px;">

I also have tried to force windows to always focus on browser windows, so the webpage always has the keyboard focus, but it also does not work.

Any hint of how to solve this question? Is it a Bug?

Body:
In Selenium there is a state that called headless, it allows you to work with the web page without actually "seeing" it. There is no window opening and everything works virtually. You set this state in the browser options.

EdgeOptions edgeOptions = new EdgeOptions();
            edgeOptions.UseChromium = true;
            edgeOptions.BinaryLocation =
@"C:\Program Files
(x86)\Microsoft\Edge\Application\msedge.exe";
            edgeOptions.AddArgument("headless");
            edgeOptions.AddArgument("disable-gpu");
            var msedgedriverDir = @"E:\webdriver";
            var driver =
new EdgeDriver(msedgedriverDir, edgeOptions);

In Java, there is a class called Robot which mimic keyboard pressing, so try to find the matching library in Python.


问:
How to get Visual Studio to recognize multiple project resource files
I have a Windows project in Visual Studio 2010 in which I store all images in the project's resource file that Visual Studio created for me. However, it's getting cluttered and I'd like to separate images into multiple resource files if possible. I created a new resource file, but Visual Studio doesn't recognize it when I go to the form designer and try to change an image. The only file that comes up under the Project resource files available are MyProject\Resources.resx. The one that I just created isn't there.

Any idea why it doesn't show up? I tried putting the resource under the My.Resources namespace as well as change the namespace and I also made it public. It still doesn't show up.

答:
A project only has a single default resource file.  You can add additional non-default resource files to the project at any time.  Additional resources files will NOT be placed in the "My Project" folder.  They will simply be added to the project like other files are.

You can refer to these new resources the same way you refer to others.  Instead of accessing the resources through "My.Resources.", you will find the other resource files under "My.Resources.[Resource File Name]".

EDIT:  A resource file needs to be in the root of your project if you want to reference it from a PictureBox control.

I hope this helps you.


问:
AWS - Storing .env files
A bit of background, a while back created a cfm template which allows us to deploy a new stack of our app on aws, which has a redis, db,2 security groups,cluster, target grous, ,alb, iam role, inline policies, couple of services, each service has service discovery entry, etc and more importantly right now it creates multiple parameter stores which are named "${cluster}/${env}/${nameOfTheParam}"

All of the parameters are env variables which are inputted when a new stack is being created.
Right now our env have grown to the point of having them over a few dozen, a bit overdue but im looking into simplifying  the process.

What i ultimately want to achieve is instead of adding each env variable one by one as a param into an input field at the cloudformation interface, to simple copy and paste them in a bulk (in a sense copy the content from the .env file) into a single input field as a cfm parameter.
What would be my option to achieve it?

答:
Apparently my current use use is considered an IoC anti-pattern, the reason being

a deploy a service with lets say 1 comma separated set of env variables stored at the param store,

there would be no way to detect drift between my currently used .env variables from my service.

having each env variable as a separate entry into param store and separate key=value pair at my service would allow me to detect drift between the current state of my service and my cloudformation template

Title: AWS - Storing .env files


问:
How to Add Title To SEM Plot in R
This is what I have for the plot:

```<code>semPaths(twofac7items_b,"std","est", rotation = 2,
         style = "lisrel",nCharNodes = 0,nodeNames=nodeNames,layout = "tree2",
         filetype = "pdf", width = 8, height = 6, filename = "Two Factor",
         residScale = 20)
</code>```

Looks like this:

What I want is this:

This is the dput(head). Everything I have is relabeled as Anxiety and Depression, so not sure how useful this will be:

```<code>structure(list(q01 = c(2, 1, 2, 3, 2, 2), q02 = c(1, 1, 3, 1,
1, 1), q03 = c(4, 4, 2, 1, 3, 3), q04 = c(2, 3, 2, 4, 2, 2),
    q05 = c(2, 2, 4, 3, 2, 4), q06 = c(2, 2, 1, 3, 3, 4), q07 = c(3,
    2, 2, 4, 3, 4), q08 = c(1, 2, 2, 2, 2, 2), q09 = c(1, 5,
    2, 2, 4, 4), q10 = c(2, 2, 2, 4, 2, 3), q11 = c(1, 2, 3,
    2, 2, 2), q12 = c(2, 3, 3, 2, 3, 4), q13 = c(2, 1, 2, 2,
    3, 3), q14 = c(2, 3, 4, 3, 2, 3), q15 = c(2, 4, 2, 3, 2,
    5), q16 = c(3, 3, 3, 3, 2, 2), q17 = c(1, 2, 2, 2, 2, 3),
    q18 = c(2, 2, 3, 4, 3, 5), q19 = c(3, 3, 1, 2, 3, 1), q20 = c(2,
    4, 4, 4, 4, 5), q21 = c(2, 4, 3, 4, 2, 3), q22 = c(2, 4,
    2, 4, 4, 1), q23 = c(5, 2, 2, 3, 4, 4)), variable.labels = c(q01 = "Statistics makes me cry",
q02 = "My friends will think I'm stupid for not being able to cope with SPSS",
q03 = "Standard deviations excite me", q04 = "I dream that Pearson is attacking me with correlation coefficients",
q05 = "I don't understand statistics", q06 = "I have little experience of computers",
q07 = "All computers hate me", q08 = "I have never been good at mathematics",
q09 = "My friends are better at statistics than me", q10 = "Computers are useful only for playing games ",
q11 = "I did badly at mathematics at school", q12 = "People try to tell you that SPSS makes statistics easier to understand but it doesn't",
q13 = "I worry that I will cause irreparable damage because of my incompetenece with computers",
q14 = "Computers have minds of their own and deliberately go wrong whenever I use them",
q15 = "Computers are out to get me", q16 = "I weep openly at the mention of central tendency",
q17 = "I slip into a coma whenever I see an equation", q18 = "SPSS always crashes when I try to use it",
q19 = "Everybody looks at me when I use SPSS", q20 = "I can't sleep for thoughts of eigen vectors",
q21 = "I wake up under my duvet thinking that I am trapped under a normal distribtion",
q22 = "My friends are better at SPSS than I am", q23 = "If I'm good at statistics my friends will think I'm a nerd"
), codepage = 65001L, row.names = c(NA, 6L), class = "data.frame")
</code>```

This is the SEM Model if its necessary:

```<code>m4b <- 'Depression =~ q01+ q03 + q04 + q05 + q08
        Anxiety =~ q06 + q07'
twofac7items_b <- cfa(m4b, data=dat,std.lv=TRUE)
summary(twofac7items_b,fit.measures=TRUE,standardized=TRUE)
</code>```

答:
Background

Finally, I put this to the side for some time when I got more R savvy. Instead of trying to overcomplicate things, I decided to make a really simple SEM path plot, then apply what was said in the comments here earlier to solve the issue.

Solution

So the major issue I kept having was getting the title to map on. For some reason I couldn't understand what was causing the issue...until I figured out the order of operations for printing out the plot. So here is basically what I did. First I used a well-oiled data frame and wrote a model based off the old lavaan manual:

```<code># Write model:
model <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8

dem60 ~ ind60
dem65 ~ ind60 + dem60

y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
# Fit model:
fit <- sem(model,
           data = PoliticalDemocracy)
# Summarize model:
summary(fit,
        standardized = T)

semPaths(fit,
         "std",
         "est",
         style = "lisrel",
         theme = "colorblind",
         rotation = 2,
         legend.cex = .5,
         layout = "tree2")
</code>```

Now this is the main part...first, I just printed out the plot as it was from there:

It was then that I put the title command directly after running the plot in the R plot viewer:

```<code># Manually add title to generated plot
title("Democracy")
</code>```

From there, I just printed the plot with this dropdown:

I was so new to R that I kept screwing this up by trying to output the file first. And by changing the order in my script, I got my pdf of my plot! I'm so happy that I was finally able to get this accomplished. Thank you to Rawr and User20650 for attempting to work with me on this.

Title: How to Add Title To SEM Plot in R

Body:
This is what I have for the plot:

semPaths(twofac7items_b,"std","est", rotation = 2,
         style = "lisrel",nCharNodes = 0,nodeNames=nodeNames,layout = "tree2",
         filetype = "pdf", width = 8, height = 6, filename = "Two Factor",
         residScale = 20)

Looks like this:

What I want is this:

This is the dput(head). Everything I have is relabeled as Anxiety and Depression, so not sure how useful this will be:

structure(list(q01 = c(2, 1, 2, 3, 2, 2), q02 = c(1, 1, 3, 1,
1, 1), q03 = c(4, 4, 2, 1, 3, 3), q04 = c(2, 3, 2, 4, 2, 2),
    q05 = c(2, 2, 4, 3, 2, 4), q06 = c(2, 2, 1, 3, 3, 4), q07 = c(3,
    2, 2, 4, 3, 4), q08 = c(1, 2, 2, 2, 2, 2), q09 = c(1, 5,
    2, 2, 4, 4), q10 = c(2, 2, 2, 4, 2, 3), q11 = c(1, 2, 3,
    2, 2, 2), q12 = c(2, 3, 3, 2, 3, 4), q13 = c(2, 1, 2, 2,
    3, 3), q14 = c(2, 3, 4, 3, 2, 3), q15 = c(2, 4, 2, 3, 2,
    5), q16 = c(3, 3, 3, 3, 2, 2), q17 = c(1, 2, 2, 2, 2, 3),
    q18 = c(2, 2, 3, 4, 3, 5), q19 = c(3, 3, 1, 2, 3, 1), q20 = c(2,
    4, 4, 4, 4, 5), q21 = c(2, 4, 3, 4, 2, 3), q22 = c(2, 4,
    2, 4, 4, 1), q23 = c(5, 2, 2, 3, 4, 4)), variable.labels = c(q01 = "Statistics makes me cry",
q02 = "My friends will think I'm stupid for not being able to cope with SPSS",
q03 = "Standard deviations excite me", q04 = "I dream that Pearson is attacking me with correlation coefficients",
q05 = "I don't understand statistics", q06 = "I have little experience of computers",
q07 = "All computers hate me", q08 = "I have never been good at mathematics",
q09 = "My friends are better at statistics than me", q10 = "Computers are useful only for playing games ",
q11 = "I did badly at mathematics at school", q12 = "People try to tell you that SPSS makes statistics easier to understand but it doesn't",
q13 = "I worry that I will cause irreparable damage because of my incompetenece with computers",
q14 = "Computers have minds of their own and deliberately go wrong whenever I use them",
q15 = "Computers are out to get me", q16 = "I weep openly at the mention of central tendency",
q17 = "I slip into a coma whenever I see an equation", q18 = "SPSS always crashes when I try to use it",
q19 = "Everybody looks at me when I use SPSS", q20 = "I can't sleep for thoughts of eigen vectors",
q21 = "I wake up under my duvet thinking that I am trapped under a normal distribtion",
q22 = "My friends are better at SPSS than I am", q23 = "If I'm good at statistics my friends will think I'm a nerd"
), codepage = 65001L, row.names = c(NA, 6L), class = "data.frame")

This is the SEM Model if its necessary:

m4b <- 'Depression =~ q01+ q03 + q04 + q05 + q08
        Anxiety =~ q06 + q07'
twofac7items_b <- cfa(m4b, data=dat,std.lv=TRUE)
summary(twofac7items_b,fit.measures=TRUE,standardized=TRUE)

Body:
Background

Finally, I put this to the side for some time when I got more R savvy. Instead of trying to overcomplicate things, I decided to make a really simple SEM path plot, then apply what was said in the comments here earlier to solve the issue.

Solution

So the major issue I kept having was getting the title to map on. For some reason I couldn't understand what was causing the issue...until I figured out the order of operations for printing out the plot. So here is basically what I did. First I used a well-oiled data frame and wrote a model based off the old lavaan manual:

# Write model:
model <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8

dem60 ~ ind60
dem65 ~ ind60 + dem60

y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
# Fit model:
fit <- sem(model,
           data = PoliticalDemocracy)
# Summarize model:
summary(fit,
        standardized = T)

semPaths(fit,
         "std",
         "est",
         style = "lisrel",
         theme = "colorblind",
         rotation = 2,
         legend.cex = .5,
         layout = "tree2")

Now this is the main part...first, I just printed out the plot as it was from there:

It was then that I put the title command directly after running the plot in the R plot viewer:

# Manually add title to generated plot
title("Democracy")

From there, I just printed the plot with this dropdown:

I was so new to R that I kept screwing this up by trying to output the file first. And by changing the order in my script, I got my pdf of my plot! I'm so happy that I was finally able to get this accomplished. Thank you to Rawr and User20650 for attempting to work with me on this.


问:
How to decode struct pointer with function?
I know how struct pointers work in general. But for struct spi_controller * spi_busnum_to_master(u16 bus_num),

What is holding the address of the struct spi_controller it is pointing towards ?

Can someone decode the logic of this declaration?. ( this style creating struct pointers)

From my understanding, a struct pointer is to enable a variable hold the address of some structure that it points to.

答:
struct spi_controller * spi_busnum_to_master(u16 bus_num) declares spi_busnum_to_master to be a function taking a parameter of type u16 and returning a pointer to struct spi_controller.

The return value is passed by whatever method is defined by the Application Binary Interface for the target platform. Often it is in a processor register.


问:
Subsetting data frames in a list in R
I am new to R and I am working with ecological data.  I have a list with 10 data frames (ten different Taxa), each of which have 36 columns (id, species, taxa, weight, etc.).

I need to apply a filter to all of the data frames within my list, to separate by a certain character(herbicide, insecticide, etc.) in one of the columns.

I tried to do it with this code:

```<code>data0 <-subset(data1, TAXA != "Annelida" & TAXA != "Arachnida" & TAXA != "Fungi" & TAXA != "Mammalia" & TAXA != "Platyhelminthes")

data2 <- split(data0, f = data0$TAXA)

herb <- data2[data2[, "USEPATTERN"] =="Herbicide",]
</code>```

But I keep getting this error:

Error in data2[, "USEPATTERN"] : incorrect number of dimensions

From there I need to count the number of times data has been entered for each df for the last 5 columns(NA, NA, NA, 35, NA, 45), which I am uncertain how to do.

答:
Here are two ways to do this -

First subset then split -

```<code>data2 <- subset(data0, USEPATTERN == "Herbicide")
herb <- split(data2, data2$TAXA)
</code>```

First split then subset. (Similar to yours)

```<code>data2 <- split(data0, f = data0$TAXA)
herb <- lapply(data2, function(x) subset(x, USEPATTERN == "Herbicide"))
</code>```

Title: Subsetting data frames in a list in R

Body:
I am new to R and I am working with ecological data.  I have a list with 10 data frames (ten different Taxa), each of which have 36 columns (id, species, taxa, weight, etc.).

I need to apply a filter to all of the data frames within my list, to separate by a certain character(herbicide, insecticide, etc.) in one of the columns.

I tried to do it with this code:

data0 <-subset(data1, TAXA != "Annelida" & TAXA != "Arachnida" & TAXA != "Fungi" & TAXA != "Mammalia" & TAXA != "Platyhelminthes")

data2 <- split(data0, f = data0$TAXA)

herb <- data2[data2[, "USEPATTERN"] =="Herbicide",]

But I keep getting this error:

Error in data2[, "USEPATTERN"] : incorrect number of dimensions

From there I need to count the number of times data has been entered for each df for the last 5 columns(NA, NA, NA, 35, NA, 45), which I am uncertain how to do.

Body:
Here are two ways to do this -

First subset then split -

data2 <- subset(data0, USEPATTERN == "Herbicide")
herb <- split(data2, data2$TAXA)

First split then subset. (Similar to yours)

data2 <- split(data0, f = data0$TAXA)
herb <- lapply(data2, function(x) subset(x, USEPATTERN == "Herbicide"))


问:
How to check if a property placeholder exists in Apache Camel?
How to check if a property placeholder exists in Apache Camel?

I tried:

```<code>.choice()
    .when(simple("{{app.custom.property}}").isNotNull())
       ...
</code>```

java.lang.IllegalArgumentException: Property with key [app.custom.property] not found in properties from text: {{app.custom.property}}

I also tried (note the ? (question mark) at the beginning of the key name):

```<code>.choice()
    .when(simple("{{?app.custom.property}}").isNotNull())
        ...
</code>```

java.lang.NullPointerException: null

Also (with default value):

```<code>.choice()
    .when(simple("{{app.custom.property:null}}").isNotNull())
        ...
</code>```

It is never null because (if not exists) it initializes the variable with the string "null". I could compare against this string, but then I have no way of knowing if the property didn't really exist or if it had set that value.

答:
I think , its is easiest and clean solution .  if you want use other properties  in other routes  u can write basic method for controlling property exist</p>
```<code>public class Greeting  extends RouteBuilder{

    @Override
    public void configure() throws Exception {

        boolean isExist = getCamelContext().getPropertiesComponent().resolveProperty("app.custom.property").isPresent();

     from("timer:hello")
        .choice()
        .when(constant(isExist)).log("exist")
        .otherwise().log("not exist");

    }

}
</code>```

Body:
How to check if a property placeholder exists in Apache Camel?

I tried:

.choice()
    .when(simple("{{app.custom.property}}").isNotNull())
       ...

java.lang.IllegalArgumentException: Property with key [app.custom.property] not found in properties from text: {{app.custom.property}}

I also tried (note the ? (question mark) at the beginning of the key name):

.choice()
    .when(simple("{{?app.custom.property}}").isNotNull())
        ...

java.lang.NullPointerException: null

Also (with default value):

.choice()
    .when(simple("{{app.custom.property:null}}").isNotNull())
        ...

It is never null because (if not exists) it initializes the variable with the string "null". I could compare against this string, but then I have no way of knowing if the property didn't really exist or if it had set that value.

Body:
I think , its is easiest and clean solution .  if you want use other properties  in other routes  u can write basic method for controlling property exist

public class Greeting  extends RouteBuilder{

    @Override
    public void configure() throws Exception {

        boolean isExist = getCamelContext().getPropertiesComponent().resolveProperty("app.custom.property").isPresent();

     from("timer:hello")
        .choice()
        .when(constant(isExist)).log("exist")
        .otherwise().log("not exist");

    }

}


问:
How to use Moq to return a List of data or values?
Can anyone tell me how to return List of data using mock object using Moq framework and assigning the so returned list of data to another List<> variable.??</p>

答:
```<code>public class SomeClass
{
    public virtual List<int> GimmeSomeData()
    {
        throw new NotImplementedException();
    }
}

[TestClass]
public class TestSomeClass
{
    [TestMethod]
    public void HowToMockAList()
    {
        var mock = new Mock<SomeClass>();
        mock.Setup(m => m.GimmeSomeData()).Returns(() => new List<int> {1, 2, 3});
        var resultList = mock.Object.GimmeSomeData();
        CollectionAssert.AreEquivalent(new List<int>{1,2,3},resultList);
    }
}
</code>```


问:
I Cant install puppeteer
I ran this script -> npm i --save-dev puppeteer to install puppeteer for e2e testing purposes.

But there is an error while installing:

```<code>C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer

> puppeteer@13.1.3 install C:\Users\Mora\Desktop\JS\Testing\node_modules\puppete
er
> node install.js

ERROR: Failed to set up Chromium r950341! Set "PUPPETEER_SKIP_DOWNLOAD" env vari
able to skip download.
Error: Download failed: server returned code 403. URL: https://storage.googleapi
s.com/chromium-browser-snapshots/Win/950341/chrome-win.zip
    at C:\Users\Mora\Desktop\JS\Testing\node_modules\puppeteer\lib\cjs\puppeteer
\node\BrowserFetcher.js:367:27
    at ClientRequest.requestCallback (C:\Users\Mora\Desktop\JS\Testing\node_modu
les\puppeteer\lib\cjs\puppeteer\node\BrowserFetcher.js:493:13)
    at Object.onceWrapper (events.js:483:26)
    at ClientRequest.emit (events.js:376:20)
    at HTTPParser.parserOnIncomingClient (_http_client.js:647:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
    at TLSSocket.socketOnData (_http_client.js:515:22)
    at TLSSocket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
npm WARN js-testing-introduction@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"
})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\wa
tchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32
"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! puppeteer@13.1.3 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@13.1.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mora\AppData\Roaming\npm-cache\_logs\2022-02-06T10_19_25_3
69Z-debug.log
</code>```

How can i fix this?

答:
It looks like it is not able to download chromium from https://storage.googleapis.com/chromium-browser-snapshots/Win/950341/chrome-win.zip.

Check whether your network is e.g behind a proxy or storage.googleapis.com was blocked by the firewall.

Title: I Cant install puppeteer

Body:
I ran this script -> npm i --save-dev puppeteer to install puppeteer for e2e testing purposes.

But there is an error while installing:

C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer

> puppeteer@13.1.3 install C:\Users\Mora\Desktop\JS\Testing\node_modules\puppete
er
> node install.js

ERROR: Failed to set up Chromium r950341! Set "PUPPETEER_SKIP_DOWNLOAD" env vari
able to skip download.
Error: Download failed: server returned code 403. URL: https://storage.googleapi
s.com/chromium-browser-snapshots/Win/950341/chrome-win.zip
    at C:\Users\Mora\Desktop\JS\Testing\node_modules\puppeteer\lib\cjs\puppeteer
\node\BrowserFetcher.js:367:27
    at ClientRequest.requestCallback (C:\Users\Mora\Desktop\JS\Testing\node_modu
les\puppeteer\lib\cjs\puppeteer\node\BrowserFetcher.js:493:13)
    at Object.onceWrapper (events.js:483:26)
    at ClientRequest.emit (events.js:376:20)
    at HTTPParser.parserOnIncomingClient (_http_client.js:647:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
    at TLSSocket.socketOnData (_http_client.js:515:22)
    at TLSSocket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
npm WARN js-testing-introduction@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32"
})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\wa
tchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"ia32
"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! puppeteer@13.1.3 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@13.1.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mora\AppData\Roaming\npm-cache\_logs\2022-02-06T10_19_25_3
69Z-debug.log

How can i fix this?


问:
Two setState functions in one onclick
I'm trying to call two functions in a single onclick, however only the first one sets the state. Following solutions from other answers, I tried calling a single function which would then call the Add() and Del() functions, but that didn't work.

This is my code:

```<code>

    const [obj, setObj] = useState(['door1','mc','start'])

    const Add = (a) => {
        var newObj = [...obj]
        a.map((i) => newObj.push(i))
        console.log(newObj)
        setObj(newObj)
        console.log(obj)
    }

    const Del = (d) => {
        const newObj = obj.filter((o) => o!=d)
        console.log(newObj)
        setObj(newObj)
    }

    return (
        <div class="main">
            {obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}
            {obj.includes('text1') && <div className="text text1" onClick={() => {Del('text1');Add(['text2'])}}>I've been trapped here for hours</div>}
        </div>
    )
</code>```

In specific, this part:

```<code>{obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}
</code>```

How can I set state twice in one onclick?

答:
You can create a handleClick function before the return statement, and add this function to your button's onClick, like this:

```<code>const handleClick = () => {
    Add(["text1"])
    Del("start")
}

<button className="btn1" onClick={handleClick}>
    Start
</button>
</code>```

Title: Two setState functions in one onclick

Body:
I'm trying to call two functions in a single onclick, however only the first one sets the state. Following solutions from other answers, I tried calling a single function which would then call the Add() and Del() functions, but that didn't work.

This is my code:

    const [obj, setObj] = useState(['door1','mc','start'])

    const Add = (a) => {
        var newObj = [...obj]
        a.map((i) => newObj.push(i))
        console.log(newObj)
        setObj(newObj)
        console.log(obj)
    }

    const Del = (d) => {
        const newObj = obj.filter((o) => o!=d)
        console.log(newObj)
        setObj(newObj)
    }

    return (

            {obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}
            {obj.includes('text1') &&
 {Del('text1');Add(['text2'])}}>I've been trapped here for hours
}

    )

In specific, this part:

{obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}

How can I set state twice in one onclick?

Body:
You can create a handleClick function before the return statement, and add this function to your button's onClick, like this:

const handleClick = () => {
    Add(["text1"])
    Del("start")
}

<button className="btn1" onClick={handleClick}>
    Start
</button>


问:
Saving complex form data in zend framework using doctrine 2
Doctrine 2 integration into ZF seems to make simple things very hard and time consuming(At least for me).

I cant just give a submitted form array to doctrine to automatically map key/value pairs to doctrine entities and it gets very complicated if i have a many-to-many entity and submitted form has nested array.

In symfony, submitted form keys/values are easily and AUTOMATICALLY mapped and saved to doctrine tables. I don't know how to do that in ZF especially if I have "Many to Many" and/or "Many to One" doctrine entities and I have **nested form elements which need multi-level iteration.

I don't want to Set every entity explicitly and create every entity object manually**.

Pain would be alot less if i used ZF`s native database architecture.

I have done some coding and now its done half-automatically but is not very useful.

答:
You should program this sort of logic into your models.

I usually add this sort of logic into my form, for example

```<code>class Application_Form_SomeModel extends Zend_Form
{
    // the usual stuff

    public function populateModel(\Entity\Model $model)
    {
        $model->setSomething($this->getValue('something'));

        $subForm = $this->getSubForm('name');

        $relatedModel = new \Entity\RelatedModel;
        $relatedModel->setSomething($subForm->getValue('something'));

        $model->getRelatedModels()->add($relatedModel);

        // assuming the related model collection has cascade persist
        // otherwise you'll need to pass in the entity manager to persist
        // the new model
    }
}
</code>```

I do it this way due to the fact the form's elements are really only known to the form. This allows you to encapsulate everything to do with the form and its element names within the form without having to assume anything else knows this information.

Body:
You should program this sort of logic into your models.

I usually add this sort of logic into my form, for example

class Application_Form_SomeModel extends Zend_Form
{
    // the usual stuff

    public function populateModel(\Entity\Model $model)
    {
        $model->setSomething($this->getValue('something'));

        $subForm = $this->getSubForm('name');

        $relatedModel = new \Entity\RelatedModel;
        $relatedModel->setSomething($subForm->getValue('something'));

        $model->getRelatedModels()->add($relatedModel);

        // assuming the related model collection has cascade persist
        // otherwise you'll need to pass in the entity manager to persist
        // the new model
    }
}

I do it this way due to the fact the form's elements are really only known to the form. This allows you to encapsulate everything to do with the form and its element names within the form without having to assume anything else knows this information.