问:
How do I add an integer to a string using Console.WriteLine?
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

```<code>Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();
</code>```

Outcome:

```<code>Checking 'Pi' value...
Pi value found. Pi =
</code>```

If you know anything I can try, please let me know.

答:
```<code>Console.WriteLine("Pi Value found. Pi =" + Pi);
</code>```

Body:
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();

Outcome:

Checking 'Pi' value...
Pi value found. Pi =

If you know anything I can try, please let me know.


来源: stackexchange

问:
Identifying duplicates in a list of character vectors in R
I have a list of character vectors like this:

```<code>my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")
</code>```

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

答:
You could do:

```<code>subset(stack(my_list), duplicated(values))$values
[1] "e"
</code>```

If you need to tell whether all the values in a group are unique to that group, you could do:

```<code>result <- setNames(logical(length(my_list)), names(my_list))

result[unique(unlist(Filter(\(x)length(x)>1,
                            unstack(rev(stack(my_list))))))] <- TRUE
result
group1 group2 group3
  TRUE   TRUE  FALSE
</code>```

or even:

```<code>stack(my_list) %>%
  mutate(dups = duplicated(values) | duplicated(values, f = T)) %>%
  group_by(ind) %>%
  summarise(logic = any(dups))

# A tibble: 3 x 2
  ind    logic
  <fct>  <lgl>
1 group1 TRUE
2 group2 TRUE
3 group3 FALSE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of character vectors like this:

my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

Body:
You could do:

subset(stack(my_list), duplicated(values))$values
[1] "e"

If you need to tell whether all the values in a group are unique to that group, you could do:

result <- setNames(logical(length(my_list)), names(my_list))

result[unique(unlist(Filter(\(x)length(x)>1,
                            unstack(rev(stack(my_list))))))] <- TRUE
result
group1 group2 group3
  TRUE   TRUE  FALSE

or even:

stack(my_list) %>%
  mutate(dups = duplicated(values) | duplicated(values, f = T)) %>%
  group_by(ind) %>%
  summarise(logic = any(dups))

# A tibble: 3 x 2
  ind    logic
  <fct>  <lgl>
1 group1 TRUE
2 group2 TRUE
3 group3 FALSE


问:
Generate images from a grayscale trained GAN pkl file
I have trained a stylegan using a set of grayscale images, now I am stuck in the generate.py because it is all set for generating RGB images.
I get this error:

```<code>ValueError: not enough image data
</code>```

when I changed the generate.py archive from stylegan pytorch from RGB to L :

```<code>ValueError: Too many dimensions: 3 > 2.
</code>```

This is the whole generate.py code:
https://github.com/mit-han-lab/data-efficient-gans/blob/master/DiffAugment-stylegan2-pytorch/generate.py

I have searched the internet for hours and tried a lot of stuff but I am pretty new to python so I have run out of ideas of what I need to change in the generate.py to be able to have the images, can somebody please help me?

答:
I ran into this problem a lot, too...

Finally found that it had something to do with indexing the img var.

Check lines 137-140 here: https://github.com/pgtinsley/stylegan3/blob/main/gen_images_gray.py

That's for StyleGAN3, but the code/logic should transfer over to SG2 pretty easily.

Best of luck!

Body:
I have trained a stylegan using a set of grayscale images, now I am stuck in the generate.py because it is all set for generating RGB images.
I get this error:

ValueError: not enough image data

when I changed the generate.py archive from stylegan pytorch from RGB to L :

ValueError: Too many dimensions: 3 > 2.

This is the whole generate.py code:
https://github.com/mit-han-lab/data-efficient-gans/blob/master/DiffAugment-stylegan2-pytorch/generate.py

I have searched the internet for hours and tried a lot of stuff but I am pretty new to python so I have run out of ideas of what I need to change in the generate.py to be able to have the images, can somebody please help me?


问:
Tensorflow insatllation is failing on AWS python3.8 image when building the docker file
```<code>Collecting Flask==1.1.2
  Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
Collecting tensorflow==2.4.0
  Downloading tensorflow-2.4.0-cp38-cp38-manylinux2010_x86_64.whl (394.8 MB)
ERROR: Exception:
Traceback (most recent call last):
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion
    crit = self.state.criteria[name]
KeyError: 'tensorflow'

During handling of the above exception, another exception occurred:
</code>```
```<code>File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 52, in _close
    self.__callback(self.__buf.getvalue())
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/controller.py", line 309, in cache_response
    cache_url, self.serializer.dumps(request, response, body=body)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/serialize.py", line 72, in dumps
    return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/__init__.py", line 35, in packb
    return Packer(**kwargs).pack(o)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 960, in pack
    self._pack(obj)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 943, in _pack
    return self._pack_map_pairs(
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 943, in _pack
    return self._pack_map_pairs(
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 889, in _pack
    return self._buffer.write(obj)
MemoryError
The command '/bin/sh -c python3.8 -m pip install   -r requirements.txt' returned a non-zero code: 2
</code>```

Following this blog to create the container image for lambda
URL : https://aws.amazon.com/blogs/machine-learning/using-container-images-to-run-tensorflow-models-in-aws-lambda/

答:
This is a memory error. When creating the environment, use a larger capacity EC2 instance.
The default instance type is t2.small. I used c5.xlarge and TensorFlow was installed properly.</p>

Body:
Collecting Flask==1.1.2
  Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB)
Collecting tensorflow==2.4.0
  Downloading tensorflow-2.4.0-cp38-cp38-manylinux2010_x86_64.whl (394.8 MB)
ERROR: Exception:
Traceback (most recent call last):
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion
    crit = self.state.criteria[name]
KeyError: 'tensorflow'

During handling of the above exception, another exception occurred:

File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 52, in _close
    self.__callback(self.__buf.getvalue())
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/controller.py", line 309, in cache_response
    cache_url, self.serializer.dumps(request, response, body=body)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/cachecontrol/serialize.py", line 72, in dumps
    return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/__init__.py", line 35, in packb
    return Packer(**kwargs).pack(o)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 960, in pack
    self._pack(obj)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 943, in _pack
    return self._pack_map_pairs(
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 943, in _pack
    return self._pack_map_pairs(
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/lang/lib/python3.8/site-packages/pip/_vendor/msgpack/fallback.py", line 889, in _pack
    return self._buffer.write(obj)
MemoryError
The command '/bin/sh -c python3.8 -m pip install   -r requirements.txt' returned a non-zero code: 2

Following this blog to create the container image for lambda
URL : https://aws.amazon.com/blogs/machine-learning/using-container-images-to-run-tensorflow-models-in-aws-lambda/


问:
mongo refusing connection on Ubuntu 16.04
Ubuntu 16.04

console output for running mongo on the terminal:

```<code>MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-03-27T18:23:41.006+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2018-03-27T18:23:41.006+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:251:13
@(connect):1:6
exception: connect failed
</code>```

答:
User This Command

```<code>sudo systemctl start mongod
</code>```

Then

```<code>mongo
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ubuntu 16.04

console output for running mongo on the terminal:

MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
2018-03-27T18:23:41.006+0530 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2018-03-27T18:23:41.006+0530 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:251:13
@(connect):1:6
exception: connect failed

Body:
User This Command

sudo systemctl start mongod

Then

mongo


问:
React Hooks Form : undefined values on submit
I took the example from the documentation :

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      <input type="submit" />
    </form>
  );
}
```

But on every change or on submit, I got undefined for each field

I tried to install the library again but nothing change and I got undefined everywhere...seems to be a problem with the register function. Does anybody got the same issue ?

答:
In my case, I was using a Controller, so to fix the Undefined value I just had to pass defaultValues to useForm.
See the rules section here: https://react-hook-form.com/api/useform/watch</p>
```<code> const { register, handleSubmit, control, setValue} = useForm<MyFormValues>({
    defaultValues : {
      receiveUpdates: false
    }
  });

<Controller
  control={control}
  name="receiveUpdates"
  render={({ field }) => (
    <FormControlLabel
      control={
        <Checkbox
          ref={field.ref}
          checked={field.value}
          onChange={field.onChange}
        />
      }
      label="Receive Email Updates?"
      labelPlacement="start"
    />
  )}
/>
</code>```

Body:
I took the example from the documentation :

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      <input type="submit" />
    </form>
  );
}

But on every change or on submit, I got undefined for each field

I tried to install the library again but nothing change and I got undefined everywhere...seems to be a problem with the register function. Does anybody got the same issue ?

Body:
In my case, I was using a Controller, so to fix the Undefined value I just had to pass defaultValues to useForm.
See the rules section here: https://react-hook-form.com/api/useform/watch

 const { register, handleSubmit, control, setValue} = useForm<MyFormValues>({
    defaultValues : {
      receiveUpdates: false
    }
  });

<Controller
  control={control}
  name="receiveUpdates"
  render={({ field }) => (
    <FormControlLabel
      control={
        <Checkbox
          ref={field.ref}
          checked={field.value}
          onChange={field.onChange}
        />
      }
      label="Receive Email Updates?"
      labelPlacement="start"
    />
  )}
/>


问:
HLS stream is not working with react-native-video
I am trying to embed live stream using react-native-video packages, but HLS link is not working, please help

答: I suggest testing the same playback URL with other players such as shaka, bitmovin, safari, VLC or ffplay.  If the source URL works in most or all of those players, then the issue is most likely related to the implementation of the react player.</p>


问:
Webdriverio v7 remote selenium grid
How can be webdriver-io v7 Tests run with an intranet Selenium Grid? According to Company policies is the intranet Selenium Grid only option? I can find in Webdriverio services for stand-alone-selenium, chrome driver, and some cloud services but not for an internal Company Selenium Grid Instances</p>

答:
change this in config file.
when run in Grid

```<code>services: [],
hostname: your.domain.without.http.and.without.port,
port: 4444,
path: '/wd/hub/',
protocol: 'http',
</code>```

when run in local

```<code>services:  ['chromedriver'],
</code>```

in local run, hostname, port, path and protocol are can be any value or removed, since framework does not pick up this value.
Dependency "wdio-chromedriver-service" needs to be installed since it is essential for local run.

Title: Webdriverio v7 remote selenium grid

Body:
change this in config file.
when run in Grid

services: [],
hostname: your.domain.without.http.and.without.port,
port: 4444,
path: '/wd/hub/',
protocol: 'http',

when run in local

services:  ['chromedriver'],

in local run, hostname, port, path and protocol are can be any value or removed, since framework does not pick up this value.
Dependency "wdio-chromedriver-service" needs to be installed since it is essential for local run.


问:
Add the email address for multiple security groups from a csv file using powershell
I have a csv file with a list of groups with their email addresses. I need add these email addresses to the mail attribut security group in AD (no exchange). In the csv the first column is labeled group (###.testgroup) second column is labeled mail (###.testgroup@domain.com).

When I run this script

```<code>Import-CSV -path 'C:\Temp\test.csv' | ForEach-Object {Set-ADGroup -Identity $_.group -Replace @{mail="$_.mail"}}
</code>```

It returns the following instead of the actual email address the mail field.

@{group=###.testgroup; mail=domain.com}.mail

答:
Your problem is because of the double quotes around "$.mail" which cast your object "$" to a string and then add litterally ".mail" at the end of the string.
To bypass this behaviour, (for example when you want to use write-host) you can use this :

```<code>"$($_.mail)"
</code>```

Or in your case, you can simply remove the quotes which gives:

```<code>Import-CSV -path 'C:\Temp\test.csv' | ForEach-Object {Set-ADGroup -Identity $_.group -Replace @{mail=$_.mail}}
</code>```

Body:
I have a csv file with a list of groups with their email addresses. I need add these email addresses to the mail attribut security group in AD (no exchange). In the csv the first column is labeled group (###.testgroup) second column is labeled mail (###.testgroup@domain.com).

When I run this script

Import-CSV -path 'C:\Temp\test.csv' | ForEach-Object {Set-ADGroup -Identity $_.group -Replace @{mail="$_.mail"}}

It returns the following instead of the actual email address the mail field.

@{group=###.testgroup; mail=domain.com}.mail

Body:
Your problem is because of the double quotes around "$.mail" which cast your object "$" to a string and then add litterally ".mail" at the end of the string.
To bypass this behaviour, (for example when you want to use write-host) you can use this :

"$($_.mail)"

Or in your case, you can simply remove the quotes which gives:

Import-CSV -path 'C:\Temp\test.csv' | ForEach-Object {Set-ADGroup -Identity $_.group -Replace @{mail=$_.mail}}


问:
For which reason this Angular Service is not working?
I created an Angular app with controller. I can successfully use the controller (with Postman, see screenshot below).

At the fronted I implemented a new component including service to show the data from controller (see code below). The service is not working. No data are shown at the application.

I made a breakpoint in feedback.service.ts/getFeedbacks() and in feedback.component.ts/ngOnInit(). Both are reached.

I mad a breakpoint at my controller and this one is never reached (except using postman).

Why doesn't the data from the controller reach the GUI?

feedback.component.html:

Feedback List:

       {{feedback.comment}}

Count: {{feedbacks.length}}

```
<p>feedback.component.ts:</p>
```import { Component, OnInit } from '@angular/core';
import { Feedback } from './feedback';
import { FeedbackService } from './feedback.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  feedbacks: Feedback[] = [];
    objects: any;

  constructor(private feedbackService: FeedbackService) { }

  ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);
  }
}
```
<p>feedback.service.ts:</p>
```import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback } from './feedback';

@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>('/feedback');
    return result;
  }
}
```
<p>feedback.ts:</p>
```export interface Feedback {
    id:      number;
    comment: string;
    userId:  number;
}
```
<p>app.modules.ts:</p>
```// other imports ...
import { FeedbackComponent } from './feedback/feedback.component';
import { FeedbackService } from './feedback/feedback.service';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    FeedbackComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: FeedbackComponent, pathMatch: 'full' }
    ]),
    BrowserAnimationsModule,
    MatToolbarModule
  ],
  providers: [FeedbackService],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

Screenshot from browser:

答:
In your component.ts change this.

```<code>ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => {
          this.feedbacks.push(...feedbacks);
    })
}
</code>```

Change this in your service.ts

```<code>getFeedbacks(): Observable<Feedback[]> {
    return this.http.get<Feedback[]>('http://localhost:444477/feedback');
}
</code>```

let me know if it worked

Body:
I created an Angular app with controller. I can successfully use the controller (with Postman, see screenshot below).

At the fronted I implemented a new component including service to show the data from controller (see code below). The service is not working. No data are shown at the application.

I made a breakpoint in feedback.service.ts/getFeedbacks() and in feedback.component.ts/ngOnInit(). Both are reached.

I mad a breakpoint at my controller and this one is never reached (except using postman).

Why doesn't the data from the controller reach the GUI?

feedback.component.html:

Feedback List:

       {{feedback.comment}}

Count: {{feedbacks.length}}

feedback.component.ts:

import { Component, OnInit } from '@angular/core';
import { Feedback } from './feedback';
import { FeedbackService } from './feedback.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})
export class FeedbackComponent implements OnInit {
  feedbacks: Feedback[] = [];
    objects: any;

  constructor(private feedbackService: FeedbackService) { }

  ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => this.feedbacks = feedbacks);
  }
}

feedback.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Feedback } from './feedback';

@Injectable({
  providedIn: 'root'
})
export class FeedbackService {

  constructor(private http: HttpClient) { }

  getFeedbacks(): Observable<Feedback[]> {
    let result: Observable<Feedback[]>;
    result = this.http.get<Feedback[]>('/feedback');
    return result;
  }
}

feedback.ts:

export interface Feedback {
    id:      number;
    comment: string;
    userId:  number;
}

app.modules.ts:

// other imports ...
import { FeedbackComponent } from './feedback/feedback.component';
import { FeedbackService } from './feedback/feedback.service';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    FeedbackComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: FeedbackComponent, pathMatch: 'full' }
    ]),
    BrowserAnimationsModule,
    MatToolbarModule
  ],
  providers: [FeedbackService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Screenshot from browser:

Body:
In your component.ts change this.

ngOnInit(): void {
    this.feedbackService
      .getFeedbacks()
      .subscribe(feedbacks => {
          this.feedbacks.push(...feedbacks);
    })
}

Change this in your service.ts

getFeedbacks(): Observable<Feedback[]> {
    return this.http.get<Feedback[]>('http://localhost:444477/feedback');
}

let me know if it worked


问:
Discord.js Button Links
Hello I am trying to use a discord.js button to link to a website

This is what I attempted to do

```<code>const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setCustomId('whatever')
    .setLabel('CLICK THIS')
    .setLink("google.com")
    .setStyle('LINK'),
);
</code>```

However this does not work due to set link not being a function

And the documentation doesnt help me out with this

答: MessageButton.setLink() is not a function. Although I can see why this may be confusing because of the setStyle('LINK') being required. The correct function is .setURL(url). The MessageButton documentation is available here https://discord.js.org/#/docs/main/stable/class/MessageButton

Title: Discord.js Button Links

Body:
Hello I am trying to use a discord.js button to link to a website

This is what I attempted to do

const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setCustomId('whatever')
    .setLabel('CLICK THIS')
    .setLink("google.com")
    .setStyle('LINK'),
);

However this does not work due to set link not being a function

And the documentation doesnt help me out with this


问:
What are the advantages of installing Eclipse Temurin OpenJDK in place of OpenJDK Deb Package on Debian?
I have on my Debian 11 Bullseye these JDK installed :

```<code>sudo update-java-alternatives -l
java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64       1081       /usr/lib/jvm/java-1.8.0-openjdk-amd64
</code>```

I want to switch to OpenJDK 17 and would to know if the Eclipse Temurin OpenJDK 17 is preferable to install instead of deb OpenJDK 17 package?
NB: Temurin advantages according to Adoptium are :

supports high-quality, TCK certified runtimes and associated
technology for use across the Java™ ecosystem

答:
As a rule of thumb, just stick with what the official Debian repositories provide to be sure to receive regular updates and more important: Security updates released by the Debian project.

Before you resort to unpack tarballs into whatever location you should watch out for a maintained repository.

In case of Adoptium you might want to add their official repository that has been published on 2021-12-30.

https://blog.adoptium.net/2021/12/eclipse-temurin-linux-installers-available/

```<code>wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public \
    | apt-key add -

echo "deb https://packages.adoptium.net/artifactory/deb bullseye main" \
    > /etc/apt/sources.list.d/adoptium.list

apt update && apt install temurin-17-jdk
</code>```

TCK certification might be worth only if you intend to ship commercial software to industry customers which insist on it.

Body:
I have on my Debian 11 Bullseye these JDK installed :

sudo update-java-alternatives -l
java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64       1081       /usr/lib/jvm/java-1.8.0-openjdk-amd64

I want to switch to OpenJDK 17 and would to know if the Eclipse Temurin OpenJDK 17 is preferable to install instead of deb OpenJDK 17 package?
NB: Temurin advantages according to Adoptium are :

supports high-quality, TCK certified runtimes and associated
technology for use across the Java™ ecosystem

Body:
As a rule of thumb, just stick with what the official Debian repositories provide to be sure to receive regular updates and more important: Security updates released by the Debian project.

Before you resort to unpack tarballs into whatever location you should watch out for a maintained repository.

In case of Adoptium you might want to add their official repository that has been published on 2021-12-30.

https://blog.adoptium.net/2021/12/eclipse-temurin-linux-installers-available/

wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public \
    | apt-key add -

echo "deb https://packages.adoptium.net/artifactory/deb bullseye main" \
    > /etc/apt/sources.list.d/adoptium.list

apt update && apt install temurin-17-jdk

TCK certification might be worth only if you intend to ship commercial software to industry customers which insist on it.


问:
How do i get parallel jobs working on failure
If I have a set of parallel jobs and 1 fails and the other succeeds.
I try the resume execution/retry failed nodes, it triggers both the jobs again.
Is there any setting in rundeck which can trigger only the failed job and not rerun the entire group again ? Is this a bug ?</p>

答:
The reason is that job reference steps is running on a single job, by design, rundeck consider that as a parent job exection and not individual executions (child jobs, the parallel jobs). If you want to avoid this, you will run these jobs individually (in a job calling each job using rd cli or Rundeck api) in a inline-script step.

In that way you can retry only the failed execution.

Now, to resume since a failed step, you can use the Job Resume Plugin (only for Rundeck Enterprise). The plugin allows to resume in the job failed step.


问:
Empty ssh invitation (no "user@host:~$") when run command after connect (sh script, sshpass)
Client OS: MacOS 12.1, Server OS: Linux Debian 9 (any server)

case 1:

```<code>#!/bin/bash
sshpass -p mypass ssh user@host.ru -o StrictHostKeyChecking=no
</code>```

works fine:

case 2:

```<code>#!/bin/bash
sshpass -p mypass ssh user@host.ru -o StrictHostKeyChecking=no "cd /var/www ; git status ; /bin/bash"
</code>```

Output of "git status" works fine, but
no "user@host:~$" message in output (input is active).

I tried:
/bin/bash
bash -l
(in server "echo $SHELL" shows /bin/bash)

How to fix it?

答:
Use ssh -t and && inside commands list

```<code>#!/bin/bash
sshpass -p mypass ssh -t user@host.ru -o StrictHostKeyChecking=no "cd /var/www && git status && /bin/bash"
</code>```

Body:
Client OS: MacOS 12.1, Server OS: Linux Debian 9 (any server)

case 1:

#!/bin/bash
sshpass -p mypass ssh user@host.ru -o StrictHostKeyChecking=no

works fine:

case 2:

#!/bin/bash
sshpass -p mypass ssh user@host.ru -o StrictHostKeyChecking=no "cd /var/www ; git status ; /bin/bash"

Output of "git status" works fine, but
no "user@host:~$" message in output (input is active).

I tried:
/bin/bash
bash -l
(in server "echo $SHELL" shows /bin/bash)

How to fix it?

Body:
Use ssh -t and && inside commands list

#!/bin/bash
sshpass -p mypass ssh -t user@host.ru -o StrictHostKeyChecking=no "cd /var/www && git status && /bin/bash"


问:
Realistic lighting (sunlight) with Three.js?
I'm attempting to create a small 1st-person game using Three.js, but I'm having trouble with the lighting. Basically I want to simulate the sun and have it rotate around casting light on everything. I'm using THREE.DirectionalLight at the moment and it only lights up the one direction so sides of cubes remain black/dark.

Do I have to use multiple lights so everything is lit up? Or could I somehow reflect light off the ground/objects?

答:
You can use scene.environment to do this job, there is already a good example here:

https://gltf-viewer.donmccurdy.com/

check gltf-viewer's code here, which did a great job in sunlight.

https://github.com/donmccurdy/three-gltf-viewer/blob/main/src/viewer.js

notice the environments vairable, which use venice_sunset_1k.hdr as their default background.

To be more detailed, they use a background as their environment, but they didn't 'show' them, you can use the code below

```<code>    this.pmremGenerator = new PMREMGenerator( this.renderer );
    this.pmremGenerator.compileEquirectangularShader();
    var rgbe_loader = new RGBELoader();
    var that = this;
    rgbe_loader.setDataType(UnsignedByteType).load("/environment/venice_sunset_2k.hdr", function(texture) {

        var envMap = that.pmremGenerator.fromEquirectangular(texture).texture;

        that.scene.environment = envMap;

        texture.dispose();
        that.pmremGenerator.dispose();

    });
</code>```

where the hdr file can be found in https://polyhaven.com/a/venice_sunset

Body:
You can use scene.environment to do this job, there is already a good example here:

https://gltf-viewer.donmccurdy.com/

check gltf-viewer's code here, which did a great job in sunlight.

https://github.com/donmccurdy/three-gltf-viewer/blob/main/src/viewer.js

notice the environments vairable, which use venice_sunset_1k.hdr as their default background.

To be more detailed, they use a background as their environment, but they didn't 'show' them, you can use the code below

    this.pmremGenerator = new PMREMGenerator( this.renderer );
    this.pmremGenerator.compileEquirectangularShader();
    var rgbe_loader = new RGBELoader();
    var that = this;
    rgbe_loader.setDataType(UnsignedByteType).load("/environment/venice_sunset_2k.hdr", function(texture) {

        var envMap = that.pmremGenerator.fromEquirectangular(texture).texture;

        that.scene.environment = envMap;

        texture.dispose();
        that.pmremGenerator.dispose();

    });

where the hdr file can be found in https://polyhaven.com/a/venice_sunset


问:
Python linear algebra in a finite field
Is there a way to do linear algebra and matrix manipulation in a finite field in Python? I need to be able to find the null space of a non-square matrix in the finite field F2. I currently can't find a way to do this. I have tried the galois package, but it does not support the scipy null space function. It is easy to compute the null space in sympy, however I do not know how to work in a finite field in sympy.</p>

答:
That's how I would approach as well.

Null space for floating point numbers is usually implemented using SVD or some other robust algorithm, for your GF(2) field it you can simply use a gaussian elimination, since there is no rounding.

Here goes an example

import numpy as np
import galois
# Initialize GF(2) and a random matrix to serve as an example
M,N = 7, 4
GF2 = galois.GF(2)
A = GF2.Random((M, N))

# B is an augmented matrix [A | I]
B = GF2.Zeros((M, M+N));
B[:, :N] = A
for i in range(M):
  B[i, N+i] = 1;
for i in range(M):
  B[i, N+i] = 1;
# Run gaussian elimination
k = 0;
for j in range(N):
  i = j;
  for i in range(k, M):
    if B[i,j] != 0:
      if i != j:
        B[[i,k],:] = B[[k,i],:]
        break;
  if B[k,j] == 0:
    continue;
  for i in range(j+1, M):
    if B[i,j]:
      B[i,j:] += B[k,j:];
  k += 1;
C = B[k:, N:]

# C should be the left null space of A
C @ A # should be zero
```

Title: Python linear algebra in a finite field


问:
Javascript function default parameter incorrect
Why does the code at this JS fiddle not work?  I want it to log a blank string, but it's logging a Pointer Event.
https://jsfiddle.net/wvom7k2f/</p>
```<code>let c = document.getElementById('c');
c.onclick = test;

function test(a='', b=''){
console.log(a);
}
</code>```

答:
You're doing c.onclick = test.  The onclick event calls its function with the event as the 1st parameter.

Try to do:

```<code>function test(e, a='', b='') {
    console.log(a);
}

c.onclick = test;
</code>```

Or, if you don't want to change test(), then you can do:

```<code>function test(a='', b='') {
    console.log(a);
}

c.onclick = function(e) {
    test();
};
</code>```

Body:
Why does the code at this JS fiddle not work?  I want it to log a blank string, but it's logging a Pointer Event.
https://jsfiddle.net/wvom7k2f/

let c = document.getElementById('c');
c.onclick = test;

function test(a='', b=''){
console.log(a);
}

Body:
You're doing c.onclick = test.  The onclick event calls its function with the event as the 1st parameter.

Try to do:

function test(e, a='', b='') {
    console.log(a);
}

c.onclick = test;

Or, if you don't want to change test(), then you can do:

function test(a='', b='') {
    console.log(a);
}

c.onclick = function(e) {
    test();
};


问:
FFmpeg error - unspecified pixel format for pipe input
I'm trying to convert stream into mp4 file using ffmpeg

```<code>ffmpeg -i pipe:0 -c:v libx264 -crf 20 -an -s 800x600 -q:v 31 output.mp4
</code>```

Output:

```<code>[mov,mp4,m4a,3gp,3g2,mj2 @ 0x55e63529aec0] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 1280x720, 3001 kb/s): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'pipe:0':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100   Duration: 00:03:03.15, start: 0.000000, bitrate: N/A
    Stream #0:0(und): Video: h264 (avc1 / 0x31637661), none, 1280x720, 3001 kb/s, SAR 1:1 DAR 16:9, 23.98 fps, 23.98 tbr, 24k tbn, 48k tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : Stereo
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
[mov,mp4,m4a,3gp,3g2,mj2 @0x55e63529aec0] stream 0, offset 0x30: partial file pipe:0: Invalid data found when processing input
Cannot determine format of input stream 0:0 after EOF Error marking filters as finished
Conversion failed!
</code>```

What I've tried:

to increase analyzeduration and probesize values in the command

```<code>ffmpeg -analyzeduration 100M -probesize 100M -i pipe:0 -c:v libx264 -crf 20 -an -s 800x600 -q:v 31 output.mp4
</code>```

but I still have the same error.

Update:

```<code>ffmpeg -f mp4 -i pipe:0 -c:v libx264 -f mp4 output.mp4
</code>```

this command with formmating stream as mp4 actually works with smaller files. I still have issues with bigger files. I'm suspecting on dockerfile with specfic ffmpeg package

答:
You have to tell FFmpeg what codec format (and/or settings) that your pipe data is using.

You didn't say what format your "stream" is using so here's some general tips:

Apply format setting (including widths/heights, where needed like for raw RGB data).

Use -f to specify a format.

Use -pix_fmt to specify a YUV picture format (like 4:2:0)

For example if your stream to convert is in H.264 format (you won't need pix_fmt here):

```<code>ffmpeg -f h264 -i - -c:v copy -f mp4 output.mp4
</code>```

or can try as (where you don't need -f for MP4 output :

```<code>ffmpeg -f h264 -i pipe:0 -c:v copy output.mp4
</code>```

If your stream is raw RGB pixel data:

(maybe you're generating a video by code / bitmap data at 30 FPS with -r 30).

```<code>ffmpeg -f rawvideo -pix_fmt argb -s 800x600 -r 30 -i pipe:0 -c:v libx264 -crf 20 -an  -q:v 31 output.mp4
</code>```

Hope it helps. Ask anything if you get a specific error.

Body:
I'm trying to convert stream into mp4 file using ffmpeg

ffmpeg -i pipe:0 -c:v libx264 -crf 20 -an -s 800x600 -q:v 31 output.mp4

Output:

[mov,mp4,m4a,3gp,3g2,mj2 @ 0x55e63529aec0] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 1280x720, 3001 kb/s): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'pipe:0':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100   Duration: 00:03:03.15, start: 0.000000, bitrate: N/A
    Stream #0:0(und): Video: h264 (avc1 / 0x31637661), none, 1280x720, 3001 kb/s, SAR 1:1 DAR 16:9, 23.98 fps, 23.98 tbr, 24k tbn, 48k tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : Stereo
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
[mov,mp4,m4a,3gp,3g2,mj2 @0x55e63529aec0] stream 0, offset 0x30: partial file pipe:0: Invalid data found when processing input
Cannot determine format of input stream 0:0 after EOF Error marking filters as finished
Conversion failed!

What I've tried:

to increase analyzeduration and probesize values in the command

ffmpeg -analyzeduration 100M -probesize 100M -i pipe:0 -c:v libx264 -crf 20 -an -s 800x600 -q:v 31 output.mp4

but I still have the same error.

Update:

ffmpeg -f mp4 -i pipe:0 -c:v libx264 -f mp4 output.mp4

this command with formmating stream as mp4 actually works with smaller files. I still have issues with bigger files. I'm suspecting on dockerfile with specfic ffmpeg package

Body:
You have to tell FFmpeg what codec format (and/or settings) that your pipe data is using.

You didn't say what format your "stream" is using so here's some general tips:

Apply format setting (including widths/heights, where needed like for raw RGB data).

Use -f to specify a format.

Use -pix_fmt to specify a YUV picture format (like 4:2:0)

For example if your stream to convert is in H.264 format (you won't need pix_fmt here):

ffmpeg -f h264 -i - -c:v copy -f mp4 output.mp4

or can try as (where you don't need -f for MP4 output :

ffmpeg -f h264 -i pipe:0 -c:v copy output.mp4

If your stream is raw RGB pixel data:

(maybe you're generating a video by code / bitmap data at 30 FPS with -r 30).

ffmpeg -f rawvideo -pix_fmt argb -s 800x600 -r 30 -i pipe:0 -c:v libx264 -crf 20 -an  -q:v 31 output.mp4

Hope it helps. Ask anything if you get a specific error.


问:
Redirecting to subpage with id
I've had two routes:

```<code><Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />
</code>```

why when I'm trigger:

```<code>window.location.href = `/client/${id}/members/${mid}`;
</code>```

then my url is changed to correct form like in the route path but not redirect me to MemberProfile component?

Thanks for any help!

答:
as

```<code><Route path="/client/:id/members" component={Members} />
</code>```

declared before

```<code><Route path="/client/:id/members/:mid" component={MemberProfile} />
</code>```

and

```<code>/client/${id}/members/${mid}
</code>```

fit

```<code>"/client/:id/members"
</code>```

Members component will still be rendered.

Consider one of the following:

decleare MemberProfile before Members

change MembersProfile route to /client/:id/member/:mid for example

use exact Route property

Title: Redirecting to subpage with id

Body:
I've had two routes:

<Route path="/client/:id/members" component={Members} />
<Route path="/client/:id/members/:mid" component={MemberProfile} />

why when I'm trigger:

window.location.href = `/client/${id}/members/${mid}`;

then my url is changed to correct form like in the route path but not redirect me to MemberProfile component?

Thanks for any help!

Body:
as

<Route path="/client/:id/members" component={Members} />

declared before

<Route path="/client/:id/members/:mid" component={MemberProfile} />

and

/client/${id}/members/${mid}

fit

"/client/:id/members"

Members component will still be rendered.

Consider one of the following:

decleare MemberProfile before Members

change MembersProfile route to /client/:id/member/:mid for example

use exact Route property


问:
Load 600+ million records in Synapse Dedicated Pool with Oracle as Source
I am trying to do a full load a very huge table (600+ million records) which resides in an Oracle On-Prem database. My destination is Azure Synapse Dedicated Pool.

I have already tried following:

Using ADF Copy activity with Source Partitioning, as source table is having 22 partitions

I increased the Copy Parallelism and DIU to a very high level

Still, I am able to fetch only 150 million records in 3 hrs whereas the ask is to complete the full load in around 2 hrs as the source would be freezed to users during that time frame so that Synapse can copy the data

How a full copy of data can be done from Oracle to Synapse in that time frame?

For a change, I tried loading data from Oracle to ADLS Gen 2, but its slow as well

答:
wBob provided a good summary of things you good look at to increase your transfer speed. In addition to that, you could try to bulk export your data into chunks of data files, and in-parallel transfer the files to azure datalake or azure blob storage, this way you can maximize your network throughput.

Once the data is on the datalake, you can scale up your Synapse instance and take advantage of fast loads using the COPY command.

I faced the same problem in our organization, and the fastest way to get the data out of SQL Server was using bcp into a fast storage layer.


答:
Conor Reid is right

```<code>const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setLabel('CLICK THIS')
    .setURL("urlhere")
    .setStyle('LINK'),
);
</code>```

The correct function is setUrl()

Title: Discord.js Button Links

Body:
Conor Reid is right

const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setLabel('CLICK THIS')
    .setURL("urlhere")
    .setStyle('LINK'),
);

The correct function is setUrl()


问:
JavaScript syntax check with JavaScript?
How could a Commando like me check if inputed code is a valid JavaScript source using some JavaScript built-in methods (if any!) or in any other possible way!? (Something like a preparser found in various IDE's like NetBeans, Eclipse, etc)?

I have to check if code is OKAY and then window.eval()-it to the current document instance.

答:
You could use a lint library like:

http://www.javascriptlint.com/download.htm

EDIT:

Sorry, that's a compiled linter and you're wanting something for on-the-fly. Try jslint: http://jslint.com


问:
The named parameter 'Images' isn't defined
I'm new to flutter and try to build up image carousel using flutter. but now I'm getting below errors in my code. its occurring at  ImageCarousel class. you can find it on end of the code. how to fix them appreciate your help on this.

The named parameter 'Images' isn't defined.

The named parameter 'Images' isn't defined.

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

class GetStartedThree extends StatelessWidget {
  const GetStartedThree({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            ImageCarousel(),

            Padding(
              padding: const EdgeInsets.only(left: 40, bottom: 230),
              child: Align(
                  alignment: Alignment.bottomLeft,
                  child: Text('Meet \nYour Doctor\nHere', style: TextStyle(
                    height: 1.2,
                    fontFamily: 'Dubai',
                    fontSize: 35,
                    color: Color(0xffFAFAFA),
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(left: 30, top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style: TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {},
                        child: Text('Get Started', style: TextStyle(
                            color: Colors.white,
                            fontSize: 25,
                            fontWeight: FontWeight.normal),
                        ),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5.0),
                        color: Colors.white,
                      ),
                      height: 5,
                      width: 120,
                    )
                )
            ),
          ],
        ),
      ),
    );
  }
}

class ImageCarousel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ImageCarousel(
        fit: BoxFit.cover,
      Images: [
        AssetImage('assets/images/person1.png'),
        AssetImage('assets/images/person2.png'),
        AssetImage('assets/images/person3.png'),

      ],
    );
  }
}
</code>```

答:
Looking at the documentation for the carousel_slider package, you do not need an extra class for the carousel. All you need to do is use the CarouselSlider() widget and give it a map of image links :

```<code>final List<String> imgList = ['assets/images/person1.png',
                              'assets/images/person2.png',
                              'assets/images/person2.png',];

CarouselSlider(
  options: CarouselOptions(),
  items: imgList.map((item) => Container(
    child: Center(
        child:
        Image.asset(item, fit: BoxFit.cover, width: 1000)),
  )).toList(),
),
</code>```

Your full code would look like something like this :

```<code>import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:carousel_slider/carousel_slider.dart';

class GetStartedThree extends StatelessWidget {
  GetStartedThree({Key? key}) : super(key: key);

  final List<String> imgList = ['assets/images/person1.png',
                                'assets/images/person2.png',
                                'assets/images/person2.png',
                                ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            CarouselSlider(
            options: CarouselOptions(),
            items: imgList.map((item) => Container(
              child: Center(
                  child:
                  Image.asset(item, fit: BoxFit.cover, width: 1000)),
            )).toList(),
          ),

            Padding(
              padding: const EdgeInsets.only(left: 40, bottom: 230),
              child: Align(
                  alignment: Alignment.bottomLeft,
                  child: Text('Meet \nYour Doctor\nHere', style: TextStyle(
                    height: 1.2,
                    fontFamily: 'Dubai',
                    fontSize: 35,
                    color: Color(0xffFAFAFA),
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(left: 30, top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style: TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {},
                        child: Text('Get Started', style: TextStyle(
                            color: Colors.white,
                            fontSize: 25,
                            fontWeight: FontWeight.normal),
                        ),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5.0),
                        color: Colors.white,
                      ),
                      height: 5,
                      width: 120,
                    )
                )
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I'm new to flutter and try to build up image carousel using flutter. but now I'm getting below errors in my code. its occurring at  ImageCarousel class. you can find it on end of the code. how to fix them appreciate your help on this.

The named parameter 'Images' isn't defined.

The named parameter 'Images' isn't defined.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

class GetStartedThree extends StatelessWidget {
  const GetStartedThree({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            ImageCarousel(),

            Padding(
              padding: const EdgeInsets.only(left: 40, bottom: 230),
              child: Align(
                  alignment: Alignment.bottomLeft,
                  child: Text('Meet \nYour Doctor\nHere', style: TextStyle(
                    height: 1.2,
                    fontFamily: 'Dubai',
                    fontSize: 35,
                    color: Color(0xffFAFAFA),
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(left: 30, top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style: TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {},
                        child: Text('Get Started', style: TextStyle(
                            color: Colors.white,
                            fontSize: 25,
                            fontWeight: FontWeight.normal),
                        ),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5.0),
                        color: Colors.white,
                      ),
                      height: 5,
                      width: 120,
                    )
                )
            ),
          ],
        ),
      ),
    );
  }
}

class ImageCarousel extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ImageCarousel(
        fit: BoxFit.cover,
      Images: [
        AssetImage('assets/images/person1.png'),
        AssetImage('assets/images/person2.png'),
        AssetImage('assets/images/person3.png'),

      ],
    );
  }
}

Body:
Looking at the documentation for the carousel_slider package, you do not need an extra class for the carousel. All you need to do is use the CarouselSlider() widget and give it a map of image links :

final List<String> imgList = ['assets/images/person1.png',
                              'assets/images/person2.png',
                              'assets/images/person2.png',];

CarouselSlider(
  options: CarouselOptions(),
  items: imgList.map((item) => Container(
    child: Center(
        child:
        Image.asset(item, fit: BoxFit.cover, width: 1000)),
  )).toList(),
),

Your full code would look like something like this :

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:carousel_slider/carousel_slider.dart';

class GetStartedThree extends StatelessWidget {
  GetStartedThree({Key? key}) : super(key: key);

  final List<String> imgList = ['assets/images/person1.png',
                                'assets/images/person2.png',
                                'assets/images/person2.png',
                                ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        child: Stack(
          children: [
            CarouselSlider(
            options: CarouselOptions(),
            items: imgList.map((item) => Container(
              child: Center(
                  child:
                  Image.asset(item, fit: BoxFit.cover, width: 1000)),
            )).toList(),
          ),

            Padding(
              padding: const EdgeInsets.only(left: 40, bottom: 230),
              child: Align(
                  alignment: Alignment.bottomLeft,
                  child: Text('Meet \nYour Doctor\nHere', style: TextStyle(
                    height: 1.2,
                    fontFamily: 'Dubai',
                    fontSize: 35,
                    color: Color(0xffFAFAFA),
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(left: 30, top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style: TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {},
                        child: Text('Get Started', style: TextStyle(
                            color: Colors.white,
                            fontSize: 25,
                            fontWeight: FontWeight.normal),
                        ),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5.0),
                        color: Colors.white,
                      ),
                      height: 5,
                      width: 120,
                    )
                )
            ),
          ],
        ),
      ),
    );
  }
}


问:
Change dynamically CF7 Stripe module amount depending on user selected price
With the Contact Form 7’s Stripe integration module  I would like to customize the form tag amount depending on the user selected checkbox value.

```<code><input type="checkbox" name="checkboxPrice" value="10€">
<input type="checkbox" name="checkboxPrice" value="30€">
</code>```

[stripe currency:eur amount:checkboxPriceValue "Proceed to checkout" "Pay"]

As mentionned here it's possible to dynamically replace the tripe tag amount depending on the user selected choice but i'm not able to do it.

```<code>add_filter(
    'wpcf7_stripe_payment_intent_parameters',

    function ( $params ) {

        // Get the WPCF7_Submission object
        $submission = WPCF7_Submission::get_instance();

        // Retrieve the currency from the 'your-currency' field value
        $currency = (array) $submission->get_posted_data( 'your-currency' );
        $currency = (string) array_shift( $currency );
        $params['currency'] = strtolower( $currency );

        // Calculate the amount
        $amount = checkboxPriceValue;
        $params['amount'] = $amount;

        $receipt_email = $submission->get_posted_data( 'your-email' );

        if ( is_email( $receipt_email ) ) {
            $params['receipt_email'] = $receipt_email;
        }

        // See https://stripe.com/docs/api/payment_intents/create
        // for the full list of available parameters

        return $params;
    },

    10, 1
);
</code>```

Any help would be appreciated !

答:
Now i get the correct amount depending on the user selected checkbox on submit and it's succesfully passed to Stripe !

Here is the Stripe shortcode I use :

```<code>**[stripe currency:eur amount:1000 "Go to checkout" "Pay !"]**
</code>```

Now checkbox is used to define dynamically Stripe price, only two choice for me with this shortcode :

```<code>**[checkbox* checkbox-price class:checkbox-price-unit use_label_element exclusive default:1 "10€" "18€"]**

$('input:checkbox[name=checkbox-price]').on('change', function(){

            let $checkboxPriceItem = $('input:checkbox[name=checkbox-price]'),
                $stripeAmount      = $('#stripeAmount');

            if ( $checkboxPriceItem[0].checked ) {
                $stripeAmount.val('1000');
            } else if ( $checkboxPriceItem[1].checked ) {
                $stripeAmount.val('1800');
            }
});

// The stripe field with the price value
<input type="hidden" name="stripeAmount" value="1000" id="stripeAmount">

// Customize stripe price
add_filter('wpcf7_stripe_payment_intent_parameters',

    function ( $params ) {

        // Get the WPCF7_Submission object
        $submission = WPCF7_Submission::get_instance();

        // Retrieve the currency from the 'your-currency' field value
        //$currency = (array) $submission->get_posted_data( 'your-currency' );
        //$currency = (string) array_shift( $currency );

        // Put your currency here in uppercase
        $currency = 'EUR';
        $params['currency'] = strtolower( $currency );

        // get value from input name=stripeAmount
        $amount = (array) $submission->get_posted_data( 'stripeAmount' );
        $amount = (string) array_shift( $amount );

        // Optional, add security so that user can't change this value with JS
        if ( $amount == 1000 || $amount == 1800) {
          $params['amount'] = $amount;
        } else {
          return false;
        }

        // Retrieve the buyer's email from the 'your-email' field value
        $receipt_email = $submission->get_posted_data( 'your-email' );

        if ( is_email( $receipt_email ) ) {
            $params['receipt_email'] = $receipt_email;
        }

        // See https://stripe.com/docs/api/payment_intents/create
        // for the full list of available parameters

        return $params;
    },

    10, 1
);
</code>```

Body:
With the Contact Form 7’s Stripe integration module  I would like to customize the form tag amount depending on the user selected checkbox value.

<input type="checkbox" name="checkboxPrice" value="10€">
<input type="checkbox" name="checkboxPrice" value="30€">

[stripe currency:eur amount:checkboxPriceValue "Proceed to checkout" "Pay"]

As mentionned here it's possible to dynamically replace the tripe tag amount depending on the user selected choice but i'm not able to do it.

add_filter(
    'wpcf7_stripe_payment_intent_parameters',

    function ( $params ) {

        // Get the WPCF7_Submission object
        $submission = WPCF7_Submission::get_instance();

        // Retrieve the currency from the 'your-currency' field value
        $currency = (array) $submission->get_posted_data( 'your-currency' );
        $currency = (string) array_shift( $currency );
        $params['currency'] = strtolower( $currency );

        // Calculate the amount
        $amount = checkboxPriceValue;
        $params['amount'] = $amount;

        $receipt_email = $submission->get_posted_data( 'your-email' );

        if ( is_email( $receipt_email ) ) {
            $params['receipt_email'] = $receipt_email;
        }

        // See https://stripe.com/docs/api/payment_intents/create
        // for the full list of available parameters

        return $params;
    },

    10, 1
);

Any help would be appreciated !

Body:
Now i get the correct amount depending on the user selected checkbox on submit and it's succesfully passed to Stripe !

Here is the Stripe shortcode I use :

**[stripe currency:eur amount:1000 "Go to checkout" "Pay !"]**

Now checkbox is used to define dynamically Stripe price, only two choice for me with this shortcode :

**[checkbox* checkbox-price class:checkbox-price-unit use_label_element exclusive default:1 "10€" "18€"]**

$('input:checkbox[name=checkbox-price]').on('change', function(){

            let $checkboxPriceItem = $('input:checkbox[name=checkbox-price]'),
                $stripeAmount      = $('#stripeAmount');

            if ( $checkboxPriceItem[0].checked ) {
                $stripeAmount.val('1000');
            } else if ( $checkboxPriceItem[1].checked ) {
                $stripeAmount.val('1800');
            }
});

// The stripe field with the price value
<input type="hidden" name="stripeAmount" value="1000" id="stripeAmount">

// Customize stripe price
add_filter('wpcf7_stripe_payment_intent_parameters',

    function ( $params ) {

        // Get the WPCF7_Submission object
        $submission = WPCF7_Submission::get_instance();

        // Retrieve the currency from the 'your-currency' field value
        //$currency = (array) $submission->get_posted_data( 'your-currency' );
        //$currency = (string) array_shift( $currency );

        // Put your currency here in uppercase
        $currency = 'EUR';
        $params['currency'] = strtolower( $currency );

        // get value from input name=stripeAmount
        $amount = (array) $submission->get_posted_data( 'stripeAmount' );
        $amount = (string) array_shift( $amount );

        // Optional, add security so that user can't change this value with JS
        if ( $amount == 1000 || $amount == 1800) {
          $params['amount'] = $amount;
        } else {
          return false;
        }

        // Retrieve the buyer's email from the 'your-email' field value
        $receipt_email = $submission->get_posted_data( 'your-email' );

        if ( is_email( $receipt_email ) ) {
            $params['receipt_email'] = $receipt_email;
        }

        // See https://stripe.com/docs/api/payment_intents/create
        // for the full list of available parameters

        return $params;
    },

    10, 1
);


问:
Escape chars in Terraform local exec provisioner
I want to chain Terraform and Ansible using the local-exec provisioner;

However since this requires input to Ansible from Terraform I am stuck with the following complex command:

```<code>provisioner "local-exec" {
        command = 'sleep 60; ansible-playbook -i ../ansible/inventory/ ../ansible/playbooks/site.yml --extra-vars "rancher_server_rds_endpoint="${aws_db_instance.my-server-rds.endpoint}" rancher_server_elastic_ip="${aws_eip.my-server-eip.public_ip}""'
    }
</code>```

which keeps returning

illegal char

error;

any suggestion about escaping correctly?

If the ansible-playbook command was to run directly in the shell it would be:

```<code>ansible-playbook -i inventory playbooks/site.yml --extra-vars "my_server_rds_endpoint=my-server-db.d30ikkj222.us-west-1.rds.amazonaws.com rancher_server_elastic_ip=88.148.17.236"
</code>```

(paths differ)

答:
The only way I know, that will work for any special characters in variables, is to use environment, for example:</p>
```<code>provisioner "local-exec" {
  command = join(
    " ", [
      "sleep 60;",
      "ansible-playbook -i ../ansible/inventory/",
      "../ansible/playbooks/site.yml",
      "--extra-vars",
      "rancher_server_rds_endpoint=\"$RANCHER_SERVER_RDS_ENDPOINT\"",
      "rancher_server_elastic_ip=\"$RANCHER_SERVER_ELASTIC_IP\""
    ]
  )
  environment = {
    RANCHER_SERVER_RDS_ENDPOINT = aws_db_instance.my-server-rds.endpoint
    RANCHER_SERVER_ELASTIC_IP   = aws_eip.my-server-eip.public_ip
  }
}
</code>```

Body:
I want to chain Terraform and Ansible using the local-exec provisioner;

However since this requires input to Ansible from Terraform I am stuck with the following complex command:

provisioner "local-exec" {
        command = 'sleep 60; ansible-playbook -i ../ansible/inventory/ ../ansible/playbooks/site.yml --extra-vars "rancher_server_rds_endpoint="${aws_db_instance.my-server-rds.endpoint}" rancher_server_elastic_ip="${aws_eip.my-server-eip.public_ip}""'
    }

which keeps returning

illegal char

error;

any suggestion about escaping correctly?

If the ansible-playbook command was to run directly in the shell it would be:

ansible-playbook -i inventory playbooks/site.yml --extra-vars "my_server_rds_endpoint=my-server-db.d30ikkj222.us-west-1.rds.amazonaws.com rancher_server_elastic_ip=88.148.17.236"

(paths differ)

Body:
The only way I know, that will work for any special characters in variables, is to use environment, for example:

provisioner "local-exec" {
  command = join(
    " ", [
      "sleep 60;",
      "ansible-playbook -i ../ansible/inventory/",
      "../ansible/playbooks/site.yml",
      "--extra-vars",
      "rancher_server_rds_endpoint=\"$RANCHER_SERVER_RDS_ENDPOINT\"",
      "rancher_server_elastic_ip=\"$RANCHER_SERVER_ELASTIC_IP\""
    ]
  )
  environment = {
    RANCHER_SERVER_RDS_ENDPOINT = aws_db_instance.my-server-rds.endpoint
    RANCHER_SERVER_ELASTIC_IP   = aws_eip.my-server-eip.public_ip
  }
}


问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答: Our experience, 20+ years of writing computationally intensive C++, is that inlining is no silver bullet. You really do need to profile your code to see whether inlining will increase performance. For us except for low level 2D and 3D point and vector manipulations inlining is a waste of time. You are far better off working out a better algorithm than trying to micromanage clock ticks.</p>


问:
A global struct pointer is used, but it does not take input. In C
The input lines are marked beside.
Here,
*ptr is a global struct pointer.
In the main function, the get_data() function is called but it does not take any input rather the program terminates.

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

    struct detail
    {
        int present, absent, credit, left_weeks;
    };

    struct detail *ptr;             // global

    void get_data()
    {
        printf("\nYou have opted for Entering the data \n");
        printf("\nEnter the number of presents - ");
        scanf("%d",&ptr->present);                                       // First input

        printf("\nEnter the number of absents - ");
        scanf("%d",&ptr->absent);                                        // Second input

        printf("\nEnter the subject credit - ");
        scanf("%d",&ptr->credit);                                        // Third input

        printf("\nEnter the number of weeks left - ");
        scanf("%d",&ptr->left_weeks);                                    // Fourth input
    }

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

I have checked in visual studio code and also an online compiler.
Could anyone help.

答:
ptr points nowhere. And there is no variable of type struct detail in this code.

You probably want this:

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

struct detail
{
    int present, absent, credit, left_weeks;
};

struct detail foo;         // << the actual variable you forgot
struct detail *ptr = &foo;             // globalptr points to foo
...
</code>```

and all your scanfs are wrong, the %d specifier wants a pointer to int but you provide an int.

You want this:

```<code>scanf("%d", &ptr->present);
            ^you forgot this
</code>```

That being said, your approach is overly complicated, you probably just want this:

```<code>scanf("%d", &foo.present);
</code>```

and remove the global ptr pointer alltogether.

Body:
The input lines are marked beside.
Here,
*ptr is a global struct pointer.
In the main function, the get_data() function is called but it does not take any input rather the program terminates.

    #include<stdio.h>
    #include<stdlib.h>

    struct detail
    {
        int present, absent, credit, left_weeks;
    };

    struct detail *ptr;             // global

    void get_data()
    {
        printf("\nYou have opted for Entering the data \n");
        printf("\nEnter the number of presents - ");
        scanf("%d",&ptr->present);                                       // First input

        printf("\nEnter the number of absents - ");
        scanf("%d",&ptr->absent);                                        // Second input

        printf("\nEnter the subject credit - ");
        scanf("%d",&ptr->credit);                                        // Third input

        printf("\nEnter the number of weeks left - ");
        scanf("%d",&ptr->left_weeks);                                    // Fourth input
    }

    int main()
    {
        get_data();
    }

I have checked in visual studio code and also an online compiler.
Could anyone help.

Body:
ptr points nowhere. And there is no variable of type struct detail in this code.

You probably want this:

#include<stdio.h>
#include<stdlib.h>

struct detail
{
    int present, absent, credit, left_weeks;
};

struct detail foo;         // << the actual variable you forgot
struct detail *ptr = &foo;             // globalptr points to foo
...

and all your scanfs are wrong, the %d specifier wants a pointer to int but you provide an int.

You want this:

scanf("%d", &ptr->present);
            ^you forgot this

That being said, your approach is overly complicated, you probably just want this:

scanf("%d", &foo.present);

and remove the global ptr pointer alltogether.


问:
Why sigsuspend does not work in while loop?
i am trying to understand how signals works. When i put sigsuspend outside of the while loop the code works otherwise it doesn't. Why?</p>
```<code>static void signal_handler(int sig) {
    printf("SIGUSR1 has been received!");
}

int main() {
    struct sigaction sigact;
    sigset_t sigset;
    sigemptyset(&sigset);

    sigact.sa_handler = signal_handler;
    sigact.sa_mask = sigset;
    sigact.sa_flags = 0;

    sigaction(SIGUSR1, &sigact, NULL);

    while(1) {
        sigsuspend(&sigset);
        printf("The signal has been received!");
    }
}
</code>```

答:
When i put sigsuspend outside of the while loop the code works otherwise it doesn't.

I take you to mean that you don't see any output when you send a SIGUSR1 to a program built from the code presented.  That has nothing directly to do with the looping or signaling.  The problem is that the standard output is buffered by default -- line buffered when it is connected to a terminal, and otherwise fully buffered.  If you send enough SIGUSR1s to the process, it will eventually print enough output to fill the buffer, and then you will see all the messages.

To see the messages immediately, either

(if stdout is connected to a terminal) add a newline to the end of each message:

```<code>printf("The signal has been received!\n");
</code>```

OR

flush stdout after each printf:

```<code> printf("The signal has been received!");
 fflush(stdout);
</code>```

OR

direct the output to stderr instead, which is unbuffered by default:

```<code> fprintf(stderr, "The signal has been received!");
</code>```

OR even

change stdout's buffering mode:

```<code> setvbuf(stdout, NULL, _IONBF, 0);
</code>```

(once is sufficient).

As for why you think you see different behavior when you call sigsuspend() only once instead of in an infinite loop, that is because the program's open streams are automatically flushed and closed when the program terminates normally.

Additionally, printf() is not async-signal-safe, therefore you elicit undefined behavior by calling it from a signal handler.  Don't do that, even if it seems to work for you under some circumstances.

Body:
i am trying to understand how signals works. When i put sigsuspend outside of the while loop the code works otherwise it doesn't. Why?

static void signal_handler(int sig) {
    printf("SIGUSR1 has been received!");
}

int main() {
    struct sigaction sigact;
    sigset_t sigset;
    sigemptyset(&sigset);

    sigact.sa_handler = signal_handler;
    sigact.sa_mask = sigset;
    sigact.sa_flags = 0;

    sigaction(SIGUSR1, &sigact, NULL);

    while(1) {
        sigsuspend(&sigset);
        printf("The signal has been received!");
    }
}

Body:
When i put sigsuspend outside of the while loop the code works otherwise it doesn't.

I take you to mean that you don't see any output when you send a SIGUSR1 to a program built from the code presented.  That has nothing directly to do with the looping or signaling.  The problem is that the standard output is buffered by default -- line buffered when it is connected to a terminal, and otherwise fully buffered.  If you send enough SIGUSR1s to the process, it will eventually print enough output to fill the buffer, and then you will see all the messages.

To see the messages immediately, either

(if stdout is connected to a terminal) add a newline to the end of each message:

printf("The signal has been received!\n");

OR

flush stdout after each printf:

 printf("The signal has been received!");
 fflush(stdout);

OR

direct the output to stderr instead, which is unbuffered by default:

 fprintf(stderr, "The signal has been received!");

OR even

change stdout's buffering mode:

 setvbuf(stdout, NULL, _IONBF, 0);

(once is sufficient).

As for why you think you see different behavior when you call sigsuspend() only once instead of in an infinite loop, that is because the program's open streams are automatically flushed and closed when the program terminates normally.

Additionally, printf() is not async-signal-safe, therefore you elicit undefined behavior by calling it from a signal handler.  Don't do that, even if it seems to work for you under some circumstances.


答:
An onclick event handler will put the event as the first parameter.  If you want to call test with no parameters you should change c.onclick = test; to the following:</p>
```<code>c.onclick = () => test();
</code>```

Title: Javascript function default parameter incorrect

Body:
Why does the code at this JS fiddle not work?  I want it to log a blank string, but it's logging a Pointer Event.
https://jsfiddle.net/wvom7k2f/

let c = document.getElementById('c');
c.onclick = test;

function test(a='', b=''){
console.log(a);
}

Body:
An onclick event handler will put the event as the first parameter.  If you want to call test with no parameters you should change c.onclick = test; to the following:

c.onclick = () => test();


问:
AKS - Terraform's network_profile block
When creating an aks cluster using terraform and azurerm provider you can specify this block :

  network_profile {
    network_plugin     = var.network_plugin
    network_policy     = var.network_policy
    load_balancer_sku  = "Standard"
    docker_bridge_cidr = var.docker_bridge_cidr
    service_cidr       = var.service_cidr
    dns_service_ip     = var.dns_service_ip
  }
```

I've read this page (and many more!) a few times but I still don't quite understand what it means.

network_pluggin : Kubenet vs Azure CNI; why to use one over another ? I understood that kubenet allowed having less chance of ip exhaustion than Azure CNI, byt Azure CNI is recommanded when enable AAD pod identity - am I right?

network_policy: this one I think is the way one can manage the internal k8s's network policies

load_balancer_sku : this one is clear to me; no problem

docker_bridge_cidr: I think this isn't really used by azure and is more like some legacy stuff, docker requiring to be configured on the worker nodes.

service_cidr : I have no idea what the doc means by "The Network Range used by the Kubernetes service. Changing this forces a new resource to be created."

dns_service_ip : as above I'm not really sure

Also, when I provide my default_node_pool a vnet_subnet_id to live in, it populates the given subnet with 31 Scale set instance tho I've only given my cluster a min_count of 1 and max_count of 2 and the vnet_subnet_id is a /24 (251 free IP). Where that 31 instances come from ?

答:
network_plugin = AAD Pod Identity will work with Kubenet but is not a recommended setup as of here. Kubenet also uses a so called Overlay Network and is doing therefore NAT, this means AKS nodes gets IPs inside your Subnet and the Pods receive an IP address from a logically different address space. Azure CNI assign IP addresses from your Subnet to Nodes and also to Pods. You need to think before how many Nodes & Pods you will have in your subnet to not run into the issue that no IPs are left for new Pods or Nodes. Here you can find an article that is doing a performance comparison.

network_policy = yes, it is to enable Kubernetes Network Policies. If you are using Azure as Network Plugin, you can use Azure or Calico as network policy. Calico hast the benefit of GlobalNetworkPolicies.

docker_bridge_cidr= it is legacy but def. needed as of today

service_cidr = It is the CIDR for Kubernetes Services inside you Cluster.

dns_service_ip = Needs to be inside the service_cidr. By default Kubernetes will assign x.x.x.10 as DNS IP. You can change this here. That is why Azure CNI requires little more planning,

To answer your final question, Azure CNI reserves all IP addresses upfront, so given your Setup with 1 Node & the default setting of max_pods=30 it will reserve 31 IPs inside your subnet.

Title: AKS - Terraform's network_profile block

Body:
When creating an aks cluster using terraform and azurerm provider you can specify this block :

  network_profile {
    network_plugin     = var.network_plugin
    network_policy     = var.network_policy
    load_balancer_sku  = "Standard"
    docker_bridge_cidr = var.docker_bridge_cidr
    service_cidr       = var.service_cidr
    dns_service_ip     = var.dns_service_ip
  }

I've read this page (and many more!) a few times but I still don't quite understand what it means.

network_pluggin : Kubenet vs Azure CNI; why to use one over another ? I understood that kubenet allowed having less chance of ip exhaustion than Azure CNI, byt Azure CNI is recommanded when enable AAD pod identity - am I right?

network_policy: this one I think is the way one can manage the internal k8s's network policies

load_balancer_sku : this one is clear to me; no problem

docker_bridge_cidr: I think this isn't really used by azure and is more like some legacy stuff, docker requiring to be configured on the worker nodes.

service_cidr : I have no idea what the doc means by "The Network Range used by the Kubernetes service. Changing this forces a new resource to be created."

dns_service_ip : as above I'm not really sure

Also, when I provide my default_node_pool a vnet_subnet_id to live in, it populates the given subnet with 31 Scale set instance tho I've only given my cluster a min_count of 1 and max_count of 2 and the vnet_subnet_id is a /24 (251 free IP). Where that 31 instances come from ?


问:
How to run multi parameter function with if, elif and else?
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.</p>
```<code>def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)
</code>```

答:
You should make first, second, third, fourth, hungry variables global. Otherwise, you will get UnboundLocalError. The function should be corrected as follows.

```<code>def food_ch(i, a, b, c, d):
    global first, second, third, fourth, hungry    # this part should be added
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "Mexican")

print (first, second, third, fourth, hungry)
</code>```

Body:
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.

def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)

Body:
You should make first, second, third, fourth, hungry variables global. Otherwise, you will get UnboundLocalError. The function should be corrected as follows.

def food_ch(i, a, b, c, d):
    global first, second, third, fourth, hungry    # this part should be added
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "Mexican")

print (first, second, third, fourth, hungry)


问:
Identifying duplicates in a list of character vectors in R
I have a list of character vectors like this:

```<code>my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")
</code>```

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

答:
A binary output can be generated with

```<code>any(duplicated(unlist(my_list)))
[1] TRUE
</code>```

As pointed out correctly in comments by @sindri_baldur, if duplicates appear in groups they should be handled with unique, if desired:

```<code>any(duplicated(unlist(lapply(my_list, unique))))
[1] TRUE
</code>```

or another base R alternative

```<code>anyDuplicated(unlist(lapply(my_list, unique))) > 1
[1] TRUE
</code>```

Body:
I have a list of character vectors like this:

my_list <- list(c('a','b','c','d','e'),c('e','f','g'),c('h','i','j'))
names(my_list) <- c("group1","group2","group3")

And I want to have a simple way to test my_list for duplicates in the letters across any of the 3 groups/vectors in my list.  So for instance, "e" appears in both group 1 and group 2 so that would be a duplicate.  Anything simple that just returns a logical if there is at least one or more duplicates across 2 or more groups would be ideal.  So a FALSE return would mean that the letters in each group are unique to that group only (this isn't the case in my example here obviously).

Thanks so much!

Body:
A binary output can be generated with

any(duplicated(unlist(my_list)))
[1] TRUE

As pointed out correctly in comments by @sindri_baldur, if duplicates appear in groups they should be handled with unique, if desired:

any(duplicated(unlist(lapply(my_list, unique))))
[1] TRUE

or another base R alternative

anyDuplicated(unlist(lapply(my_list, unique))) > 1
[1] TRUE


问:
Maintaining message integrity
I have a message that I am passing to myself which will be subject to man-in-the-middle attacks.  Because of that, I am concerned about the integrity of the message being maintained between the time I send it, and the time that I receive it back.

It should be assumed that once I send the message to myself, no information about the message sent will be available to me in the future.  The message is completely self-contained.

To that end, I know that should hash the message contents and compare the hashes before I send the message, and after I send the message, if they differ, then the message has been tampered with.

Of course, if the man-in-the-middle knows that the hash is really just the hash of the message contents, as-is, then because the message is self-contained, he can just create new contents and apply the same hash algorithm to the contents.

The question is, to what lengths should I go to randomize the message contents when generating the hash?  When does it reach the point of diminishing returns?

In this scenario, I have a set of key/value pairs.  To that end, the steps that I know I HAVE to take are:

Add a salt to the message.  The salt is a secret to the rest of the world.  It gets attached to the contents of the message before hashing.

Order the key/value pairs in a consistent manner before generating the hash.

While not directly relevant, a timestamp is going to be added to the contents of each message before hashing, to prevent replay attacks.

These are the optional steps that I am considering:

Transforming the keys before I order them.  I've considered reversing them, then ordering by count/key.

Playing with the separators that separate key/value pairs (both for the separator for the key/value and the separator for the pair).

NOTE

Message privacy is not a requirement here, so I am not looking for encryption.  The values must be transmitted in plain-text.

Finally, what hashing algorithms should I avoid?

Specifics

I have an ASP.NET MVC site which I have a controller which handles input validation and persistence.

If (based on a heuristic, it's not important which) the input is determined to be an automated spam attempt, a model of IDictionary<string, string> is created with the input values and a ViewResult is sent to a general CAPTCHA page.

In that view, in the form that contains the CAPTCHA control, the contents of the IDictionary<string, string> will be written out in hidden input fields, and the action of the form will be the same action that the contents were originally posted to.  This way, MVC can pick up the values when the form is resubmitted.

It's because of this I can't encrypt the key/value pairs (or maybe I can and should, tell me why and how!).

Of course, I need to add one more value, which contains the hashed message contents.  If that value is there, then the controller will check to see that the message integrity is maintained, and allow the input to be persisted if it has.

Solution

I've opted to go with the SignedCms class in the System.Security.Cyrptography.Pkcs namespace, which represents the signging and verifying of CMS/PKCS #7 messages.

To elaborate, I've created a self-issued certificate with MAKECERT.EXE and then in my code, I use the example here to digitally sign the data:

http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

Now, it should be a matter of keeping the password on the exported private key secure, as well as security on the server, which makes it less about programming.

I'll have to add an extra key for the timestamp for replay attacks, but that won't be too hard.

The answer goes to Kalium, not for his initial post, but for his follow up comments which pointed the way to digital signatures, and eventually my discovery of how to utilize them in .NET.

Thanks to everyone who contributed.

答: You should probably digitally sign the message (hence PGP/GPG recommended by Kalium is relevant as an option).  Any pure hash that you can create can be recreated by the attacker.  Digital signing - using your private signing key so that your public key can be used to verify it - is the solution.  Anything else is an exercise in futility.</p>

OwnerDisplayName: casperOne

ContentLicense: CC BY-SA 2.5

Title: Maintaining message integrity

LastEditorDisplayName: casperOne

OwnerDisplayName: Jonathan Leffler


问:
Java BigDecimal vs R vs Java Float, Double
I am working on a financial system where precision required is 6 decimal places only.  We are currently using R but converting to Java.  I had a debate with a colleague over whether we should go with BigDecimals or double / float primitive in Java.  I was in favor of BigDecimal but his point was that R would be using primitives same as Java primitives so we would have already noticed if there were any issues with the precision.  It should be noted that the end result we would convert to BigDecimal anyway this is just for the calculation itself.  Who is correct here?</p>

答:
You should definitely use BigDecimal with DECIMAL 128. You should do this knowing that specifications may change in the future and more decimal points may be required. DECIMAL 128 is too too much solution, but it's bullet proof.

Performance is important, but when it comes to money, accuracy is much much more important.


问:
pytest mock response with multiple calls
I am trying to mock the response of api call but in my one function i have two seperate api call and i want to mock only one. below is the code and i want o mock only my second api call

```<code>apicall.py

def call_api():
    response_of_api1_to_get_token = request.post() # some url to post 1st. DO Not Mock this
    response_of_api2 = request.post() # some url to post 2nd api, i want to mock this

# test.py

import pytest
import requests_mock
from requests.exceptions import HTTPError
from apicall import call_api

def test_some_func():
    with requests_mock.mock() as m:
        m.get(requests_mock.ANY, status_code=500, text='some error')

        with pytest.raises(HTTPError):
            # You cannot make any assertion on the result
            # because some_func raises an exception and
            # wouldn't return anything
            call_api(a="a", b="b") # here it mock my first api

</code>```

is there anyway i can avoid mocking 1st api call and do mock on 2nd api call?

答:
You can pass in real_http=True to the Mocker's init call. This will result in only mocking the requests that you have registered a URL for. In the example below, the request to test.com will be mocked, the one to google.com will not be mocked.

import requests
import requests_mock
with requests_mock.Mocker(real_http=True) as m:
    m.get('http://test.com', text='resp')
    requests.get('http://test.com').text
    requests.get('https://www.google.com').text
```

Body:
I am trying to mock the response of api call but in my one function i have two seperate api call and i want to mock only one. below is the code and i want o mock only my second api call

apicall.py

def call_api():
    response_of_api1_to_get_token = request.post() # some url to post 1st. DO Not Mock this
    response_of_api2 = request.post() # some url to post 2nd api, i want to mock this

# test.py

import pytest
import requests_mock
from requests.exceptions import HTTPError
from apicall import call_api

def test_some_func():
    with requests_mock.mock() as m:
        m.get(requests_mock.ANY, status_code=500, text='some error')

        with pytest.raises(HTTPError):
            # You cannot make any assertion on the result
            # because some_func raises an exception and
            # wouldn't return anything
            call_api(a="a", b="b") # here it mock my first api

is there anyway i can avoid mocking 1st api call and do mock on 2nd api call?