答:
You should type your httpClient.get method call, like this:

```<code>http.get<any[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
   this.posts = response;
})
</code>```

Best practice is also to create an interface for your model, for example:

```<code>export interface Post {
  id: number,
  title: string,
  ...
}
</code>```

So your code could be :

```<code>export class PostsComponent implements OnInit {
  posts: Post[];

  constructor(http: HttpClient) {

    http.get<Post[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
      this.posts = response;
    })
  }

  ngOnInit(): void {
  }

}
</code>```

Title: how to assign values to an array using .subscribe in angular?

Body:
I am using a HttpClient calling.I am trying to assign values to posts[] which i hav defined as type any.

I am getting error as follows:

The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
    Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.

My code for posts.component.html

import { Component, OnInit } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

  posts: any[];

  constructor(http:HttpClient) {

    http.get('http://jsonplaceholder.typicode.com/posts').subscribe(response =>{
      this.posts=response;})
  }

  ngOnInit(): void {
  }

}

Body:
You should type your httpClient.get method call, like this:

http.get<any[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
   this.posts = response;
})

Best practice is also to create an interface for your model, for example:

export interface Post {
  id: number,
  title: string,
  ...
}

So your code could be :

export class PostsComponent implements OnInit {
  posts: Post[];

  constructor(http: HttpClient) {

    http.get<Post[]>('http://jsonplaceholder.typicode.com/posts').subscribe(response => {
      this.posts = response;
    })
  }

  ngOnInit(): void {
  }

}


来源: stackexchange

问:
Cuda and pytorch memory usage
I am using Cuda and Pytorch:1.4.0.

When I try to increase batch_size, I've got the following error:

CUDA out of memory. Tried to allocate 20.00 MiB (GPU 0; 4.00 GiB total capacity;  2.74 GiB already allocated; 7.80 MiB free; 2.96 GiB reserved in total by PyTorch)

I haven't found anything about Pytorch memory usage.

Also, I don't understand why I have only 7.80 mib available?

Should I just use a videocard with better perfomance, or can I free some memory? FYI, I have a GTX 1050 TI, python 3,7 and torch==1.4.0 and my os is Windows 10.

答:
I had the same problem, the following worked for me:

```<code>torch.cuda.empty_cache()
# start training from here
</code>```

Even after this if you get the error, then you should decrease the batch_size

ContentLicense: CC BY-SA 4.0

Title: Cuda and pytorch memory usage

Body:
I had the same problem, the following worked for me:

torch.cuda.empty_cache()
# start training from here

Even after this if you get the error, then you should decrease the batch_size


问:
Coding convention for adding rows to Pandas Dataframe in for loop
I'm writing a program where I want to extract data from multiple docx files and fill it into a pandas dataframe. I'm currently achieving this in a for loop like so:

```<code>cols = ["path","col1", "col2", "col3", "col4"]

def add_to_df(path):
    col1_val = extract_col1(path)
    col2_val = extract_col2(path)
    col3_val = extract_col3(path)
    col4_val = extract_col4(path)

    temp_df = pd.DataFrame(
        [[path, col1_val,col2_val,col3_val,col4_val]],
        columns=cols)
    return temp_df

df = pd.DataFrame()
for path in paths:
    df = df.append(add_to_df(path), ignore_index=True)
</code>```

Is this the best way to do this? Or is there a nicer, more accepted way? (This is just a simplified example of what I'm trying to do, the actual code looks a lot messier...)

答:
I prefer extracting data to a dictionary first and then create a dataframe from that dictionary. Example:

```<code>data = {'doc1': {'subject': 'x', 'n_words': 100},
        'doc2': {'subject': 'y', 'n_words': 200},
        'doc3': {'subject': 'z', 'n_words': 300}}

df = pd.DataFrame.from_dict(data, orient='index')

print(df)
</code>```

Result:

```<code>     subject  n_words
doc1       x      100
doc2       y      200
doc3       z      300
</code>```

Body:
I'm writing a program where I want to extract data from multiple docx files and fill it into a pandas dataframe. I'm currently achieving this in a for loop like so:

cols = ["path","col1", "col2", "col3", "col4"]

def add_to_df(path):
    col1_val = extract_col1(path)
    col2_val = extract_col2(path)
    col3_val = extract_col3(path)
    col4_val = extract_col4(path)

    temp_df = pd.DataFrame(
        [[path, col1_val,col2_val,col3_val,col4_val]],
        columns=cols)
    return temp_df

df = pd.DataFrame()
for path in paths:
    df = df.append(add_to_df(path), ignore_index=True)

Is this the best way to do this? Or is there a nicer, more accepted way? (This is just a simplified example of what I'm trying to do, the actual code looks a lot messier...)

Body:
I prefer extracting data to a dictionary first and then create a dataframe from that dictionary. Example:

data = {'doc1': {'subject': 'x', 'n_words': 100},
        'doc2': {'subject': 'y', 'n_words': 200},
        'doc3': {'subject': 'z', 'n_words': 300}}

df = pd.DataFrame.from_dict(data, orient='index')

print(df)

Result:

     subject  n_words
doc1       x      100
doc2       y      200
doc3       z      300


问:
Need a comparable Function in C# to display a Variable as Array like in VB.NET
If a function in VB.NET wants an Array as param, like this:

```<code> private function DoSomeStuff(int[] numbers)
</code>```

I can write in VB.NET this, and give the int in {} as array

```<code>dim example as Integer = 10
doSomeStuff({example})
</code>```

Is there something comparable in C#?

答:
You can do it as below</p>

```<code>int example = 10;

doSomeStuff(new int[] { example });
</code>```

Body:
If a function in VB.NET wants an Array as param, like this:

 private function DoSomeStuff(int[] numbers)

I can write in VB.NET this, and give the int in {} as array

dim example as Integer = 10
doSomeStuff({example})

Is there something comparable in C#?

Body:
You can do it as below

int example = 10;

doSomeStuff(new int[] { example });


问:
issue in query params in angular 8
I have a problem with the query parameters in angular 8. This is the code:

```<code>headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }
</code>```

I also tried

```<code>let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);
</code>```

and

```<code>let params = new HttpParams().set('username', username).set('password', password);
</code>```

and

```<code>let params = new HttpParams().append('username', username).append('password', password);
</code>```

The backend server get username and password as undefined, previously I had this code that worked correctly:

```<code> login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}
</code>```

What's wrong? Thanks

答:
You are posting the options as body. The third parameter of the http.post should be the options:

```<code>let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);

const options = { headers: this.headers, params: params };

return this.http.post<any>(this.host + 'login', null, options);
</code>```

Why is this a post, if there is no body though? Wouldn't a GET make more sense?

Title: issue in query params in angular 8

Body:
I have a problem with the query parameters in angular 8. This is the code:

headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }

I also tried

let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);

and

let params = new HttpParams().set('username', username).set('password', password);

and

let params = new HttpParams().append('username', username).append('password', password);

The backend server get username and password as undefined, previously I had this code that worked correctly:

 login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}

What's wrong? Thanks

Body:
You are posting the options as body. The third parameter of the http.post should be the options:

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);

const options = { headers: this.headers, params: params };

return this.http.post<any>(this.host + 'login', null, options);

Why is this a post, if there is no body though? Wouldn't a GET make more sense?


问:
Not able to inject dependencies inside the AWS Lambda function through Springs framework
I am trying to create a SQS poller inside the AWS Lambda, and I am trying to process the messages fetched from the SQS queue.
In this code I am using Spring Framework to inject the dependencies, so for now I am not using Guice or Dagger or creating objects using "new" operator.

But when I declare all the beans in the ApplicationBeans.java file inside the spring folder, none of my beans gets initialized.

My ApplicationBeans.java looks like this:

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class ApplicationBeans
{

@Bean
-----------
-----------
----------
}
</code>```

And my main class where I need to inject the dependencies looks like these:

```<code>import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
private Dependency1 dependency1;
-----
-----
-----

}
</code>```

But now when I try to access the dependency1 in the code, it gives me a nullPointer exception.
What is going wrong in configuring Springs in AWS Lambda?

答:
In your code here, you have to specify annotations such as

@Autowired

or

@Resource

so that spring realizes to inject bean to it.

```<code>import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
    @Autowired
    private Dependency1 dependency1;
    -----
    -----
    -----
}
</code>```

If you are not willing to use annotations, then you have to use ApplicationContext class to get the Beans using getBean() method.

Hope this helps!!

Body:
I am trying to create a SQS poller inside the AWS Lambda, and I am trying to process the messages fetched from the SQS queue.
In this code I am using Spring Framework to inject the dependencies, so for now I am not using Guice or Dagger or creating objects using "new" operator.

But when I declare all the beans in the ApplicationBeans.java file inside the spring folder, none of my beans gets initialized.

My ApplicationBeans.java looks like this:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class ApplicationBeans
{

@Bean
-----------
-----------
----------
}

And my main class where I need to inject the dependencies looks like these:

import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
private Dependency1 dependency1;
-----
-----
-----

}

But now when I try to access the dependency1 in the code, it gives me a nullPointer exception.
What is going wrong in configuring Springs in AWS Lambda?

Body:
In your code here, you have to specify annotations such as

@Autowired

or

@Resource

so that spring realizes to inject bean to it.

import lombok.AllArgsConstructor;
@AllArgsConstructor
public class MainClass implements RequestHandler<SQSEvent, Void>
{
    @Autowired
    private Dependency1 dependency1;
    -----
    -----
    -----
}

If you are not willing to use annotations, then you have to use ApplicationContext class to get the Beans using getBean() method.

Hope this helps!!


问:
Assigning value to tooltip of an ASP.net Custom Validator using javascript
I would like to provide a message as tooltip of a custom Validator  based on some condition in Javascript.

Can any one please help me out?

答:
The validator will no doubt spit out some HTML markup, so you could use some jQuery like this:</p>

```<code>if(yourCondition) {
  $('#id-of-validator-span').attr('title', 'Your tooltip value');
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The validator will no doubt spit out some HTML markup, so you could use some jQuery like this:

if(yourCondition) {
  $('#id-of-validator-span').attr('title', 'Your tooltip value');
}


问:
How to select using multiple attribute selectors?
I am trying to disable multiple fields in a checkbox survey at the same time. Is it possible to select by multiple classes on same the div? I tried below but its not working. The code works with one class.</p>

```<code>function surveyInit(){
  $("div[class*='addressLine1', class*='addressLine2'] input"  ).attr('disabled', 'disabled');
}
</code>```

答:
You need to use multiple selectors separated by commas, not put the commas inside the attribute selector.</p>

```<code>function surveyInit(){
    $("div[class*='addressLine1'] input, div[class*='addressLine2'] input").attr('disabled', 'disabled');
}
</code>```

Body:
I am trying to disable multiple fields in a checkbox survey at the same time. Is it possible to select by multiple classes on same the div? I tried below but its not working. The code works with one class.

function surveyInit(){
  $("div[class*='addressLine1', class*='addressLine2'] input"  ).attr('disabled', 'disabled');
}

Body:
You need to use multiple selectors separated by commas, not put the commas inside the attribute selector.

function surveyInit(){
    $("div[class*='addressLine1'] input, div[class*='addressLine2'] input").attr('disabled', 'disabled');
}


问:
SwiftUI: Drawing rectangles around elements recognized with Firebase ML Kit
I am currently trying to achieve to draw boxes of the text that was recognized with Firebase ML Kit on top of the image.
Currently, I did not have success yet and I can't see any box at all as they are all shown offscreen. I was looking at this article for a reference: https://medium.com/swlh/how-to-draw-bounding-boxes-with-swiftui-d93d1414eb00 and also at that project: https://github.com/firebase/quickstart-ios/blob/master/mlvision/MLVisionExample/ViewController.swift

This is the view where the boxes should be shown:

```<code>struct ImageScanned: View {
var image: UIImage
@Binding var rectangles: [CGRect]
@State var viewSize: CGSize = .zero

var body: some View {
    // TODO: fix scaling
       ZStack {
           Image(uiImage: image)
               .resizable()
               .scaledToFit()
               .overlay(
                   GeometryReader { geometry in
                    ZStack {
                        ForEach(self.transformRectangles(geometry: geometry)) { rect in
                            Rectangle()
                            .path(in: CGRect(
                                x: rect.x,
                                y: rect.y,
                                width: rect.width,
                                height: rect.height))
                            .stroke(Color.red, lineWidth: 2.0)
                        }
                    }
                }
           )
       }
}
private func transformRectangles(geometry: GeometryProxy) -> [DetectedRectangle] {
    var rectangles: [DetectedRectangle] = []

    let imageViewWidth = geometry.frame(in: .global).size.width
    let imageViewHeight = geometry.frame(in: .global).size.height
    let imageWidth = image.size.width
    let imageHeight = image.size.height

    let imageViewAspectRatio = imageViewWidth / imageViewHeight
    let imageAspectRatio = imageWidth / imageHeight
    let scale = (imageViewAspectRatio > imageAspectRatio)
      ? imageViewHeight / imageHeight : imageViewWidth / imageWidth

    let scaledImageWidth = imageWidth * scale
    let scaledImageHeight = imageHeight * scale
    let xValue = (imageViewWidth - scaledImageWidth) / CGFloat(2.0)
    let yValue = (imageViewHeight - scaledImageHeight) / CGFloat(2.0)

    var transform = CGAffineTransform.identity.translatedBy(x: xValue, y: yValue)
    transform = transform.scaledBy(x: scale, y: scale)

    for rect in self.rectangles {
        let rectangle = rect.applying(transform)
        rectangles.append(DetectedRectangle(width: rectangle.width, height: rectangle.height, x: rectangle.minX, y: rectangle.minY))
    }
    return rectangles
}
</code>```

}

```<code>struct DetectedRectangle: Identifiable {
    var id = UUID()
    var width: CGFloat = 0
    var height: CGFloat = 0
    var x: CGFloat = 0
    var y: CGFloat = 0
}
</code>```

This is the view where this view is nested in:

```<code>struct StartScanView: View {
@State var showCaptureImageView: Bool = false
@State var image: UIImage? = nil
@State var rectangles: [CGRect] = []

var body: some View {
    ZStack {
        if showCaptureImageView {
            CaptureImageView(isShown: $showCaptureImageView, image: $image)
        } else {
            VStack {

                Button(action: {
                    self.showCaptureImageView.toggle()
                }) {
                    Text("Start Scanning")
                }

                // show here View with rectangles on top of image
                if self.image != nil {
                    ImageScanned(image: self.image ?? UIImage(), rectangles: $rectangles)
                }

                Button(action: {
                    self.processImage()
                }) {
                    Text("Process Image")
                }
            }
        }
    }
}

func processImage() {
    let scaledImageProcessor = ScaledElementProcessor()
    if image != nil {
        scaledImageProcessor.process(in: image!) { text in
            for block in text.blocks {
                for line in block.lines {
                    for element in line.elements {
                        self.rectangles.append(element.frame)
                    }
                }
            }
        }
    }
}
</code>```

}

The calculation of the tutorial caused the rectangles being to big and the one of the sample project them being too small.
(Similar for height)
Unfortunately I can't find on which size Firebase determines the element's size.
This is how it looks like:

Without calculating the width & height at all, the rectangles seem to have about the size they are supposed to have (not exactly), so this gives me the assumption, that ML Kit's size calculation is not done in proportion to the image.size.height/width.

答:
ML Kit has a QuickStart app showing exactly what you are trying to do: recognizing the text and drawing a rectangle around the text.  Here is the Swift code:

https://github.com/firebase/quickstart-ios/tree/master/mlvision/MLVisionExample

Body:
I am currently trying to achieve to draw boxes of the text that was recognized with Firebase ML Kit on top of the image.
Currently, I did not have success yet and I can't see any box at all as they are all shown offscreen. I was looking at this article for a reference: https://medium.com/swlh/how-to-draw-bounding-boxes-with-swiftui-d93d1414eb00 and also at that project: https://github.com/firebase/quickstart-ios/blob/master/mlvision/MLVisionExample/ViewController.swift

This is the view where the boxes should be shown:

struct ImageScanned: View {
var image: UIImage
@Binding var rectangles: [CGRect]
@State var viewSize: CGSize = .zero

var body: some View {
    // TODO: fix scaling
       ZStack {
           Image(uiImage: image)
               .resizable()
               .scaledToFit()
               .overlay(
                   GeometryReader { geometry in
                    ZStack {
                        ForEach(self.transformRectangles(geometry: geometry)) { rect in
                            Rectangle()
                            .path(in: CGRect(
                                x: rect.x,
                                y: rect.y,
                                width: rect.width,
                                height: rect.height))
                            .stroke(Color.red, lineWidth: 2.0)
                        }
                    }
                }
           )
       }
}
private func transformRectangles(geometry: GeometryProxy) -> [DetectedRectangle] {
    var rectangles: [DetectedRectangle] = []

    let imageViewWidth = geometry.frame(in: .global).size.width
    let imageViewHeight = geometry.frame(in: .global).size.height
    let imageWidth = image.size.width
    let imageHeight = image.size.height

    let imageViewAspectRatio = imageViewWidth / imageViewHeight
    let imageAspectRatio = imageWidth / imageHeight
    let scale = (imageViewAspectRatio > imageAspectRatio)
      ? imageViewHeight / imageHeight : imageViewWidth / imageWidth

    let scaledImageWidth = imageWidth * scale
    let scaledImageHeight = imageHeight * scale
    let xValue = (imageViewWidth - scaledImageWidth) / CGFloat(2.0)
    let yValue = (imageViewHeight - scaledImageHeight) / CGFloat(2.0)

    var transform = CGAffineTransform.identity.translatedBy(x: xValue, y: yValue)
    transform = transform.scaledBy(x: scale, y: scale)

    for rect in self.rectangles {
        let rectangle = rect.applying(transform)
        rectangles.append(DetectedRectangle(width: rectangle.width, height: rectangle.height, x: rectangle.minX, y: rectangle.minY))
    }
    return rectangles
}

}

struct DetectedRectangle: Identifiable {
    var id = UUID()
    var width: CGFloat = 0
    var height: CGFloat = 0
    var x: CGFloat = 0
    var y: CGFloat = 0
}

This is the view where this view is nested in:

struct StartScanView: View {
@State var showCaptureImageView: Bool = false
@State var image: UIImage? = nil
@State var rectangles: [CGRect] = []

var body: some View {
    ZStack {
        if showCaptureImageView {
            CaptureImageView(isShown: $showCaptureImageView, image: $image)
        } else {
            VStack {

                Button(action: {
                    self.showCaptureImageView.toggle()
                }) {
                    Text("Start Scanning")
                }

                // show here View with rectangles on top of image
                if self.image != nil {
                    ImageScanned(image: self.image ?? UIImage(), rectangles: $rectangles)
                }

                Button(action: {
                    self.processImage()
                }) {
                    Text("Process Image")
                }
            }
        }
    }
}

func processImage() {
    let scaledImageProcessor = ScaledElementProcessor()
    if image != nil {
        scaledImageProcessor.process(in: image!) { text in
            for block in text.blocks {
                for line in block.lines {
                    for element in line.elements {
                        self.rectangles.append(element.frame)
                    }
                }
            }
        }
    }
}

}

The calculation of the tutorial caused the rectangles being to big and the one of the sample project them being too small.
(Similar for height)
Unfortunately I can't find on which size Firebase determines the element's size.
This is how it looks like:

Without calculating the width & height at all, the rectangles seem to have about the size they are supposed to have (not exactly), so this gives me the assumption, that ML Kit's size calculation is not done in proportion to the image.size.height/width.


问:
Kubernetes Container application process recovery in case of Node failure
In case of ec2 spot instances, if the node fails is there any way to migrate the running process of an application inside the docker container automatically to another node in the same state it was before the termination started?</p>

答: Kubernetes doesn't support container migration.</p>


问:
Updating multiple rows in single column
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

```<code>ALTER TABLE Invoice
ADD ItemsSum int NULL
</code>```

I tried following query but it gave error because of multiple results

```<code>UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)
</code>```

How to achieve this correctly in SQL Server?

答:
You can use correlated subquery :

```<code>UPDATE Invoice
     SET ItemsSum = (SELECT SUM(it.Amount)
                     FROM InvoiceItem it
                     WHERE it.InvoiceID = Invoice.ID
                    );
</code>```

ItemsSum will be invalid if underlying invoice amount will be change.

Title: Updating multiple rows in single column

Body:
I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

ALTER TABLE Invoice
ADD ItemsSum int NULL

I tried following query but it gave error because of multiple results

UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)

How to achieve this correctly in SQL Server?

Body:
You can use correlated subquery :

UPDATE Invoice
     SET ItemsSum = (SELECT SUM(it.Amount)
                     FROM InvoiceItem it
                     WHERE it.InvoiceID = Invoice.ID
                    );

ItemsSum will be invalid if underlying invoice amount will be change.


问:
Nearest index of a logical vector in R
I'm trying to get the index of the nearest TRUE value from a column based on the entry of another column. My sample dataframe goes like this:

```<code>a <- c(FALSE,TRUE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,FALSE)
b <- c(NA, NA, 3, NA, NA, NA, NA, 8, NA, NA, NA, 12, NA, NA, NA)
df <- data.frame(a, b)
</code>```

I would like to make a new column that gives the index of the nearest TRUE value before a given value from b. To illustrate, the resulting df should look like this:

```<code>       a  b  c
1  FALSE NA NA
2   TRUE NA NA
3  FALSE  3  2
4  FALSE NA NA
5  FALSE NA NA
6   TRUE NA NA
7  FALSE NA NA
8  FALSE  8  6
9   TRUE NA NA
10  TRUE NA NA
11 FALSE NA NA
12 FALSE 12 10
13 FALSE NA NA
14 FALSE NA NA
15 FALSE NA NA
</code>```

I know I can use max(which(df$a == TRUE)) but I don't know how to make it work in such a way that it only considers the index of the preceding values. Thanks!

答:
We can get the index of all TRUE values and then use findInterval to get the closest one for each value in b.

```<code>inds <- which(df$a)
df$c <- inds[findInterval(df$b, inds)]
df

#       a  b  c
#1  FALSE NA NA
#2   TRUE NA NA
#3  FALSE  3  2
#4  FALSE NA NA
#5  FALSE NA NA
#6   TRUE NA NA
#7  FALSE NA NA
#8  FALSE  8  6
#9   TRUE NA NA
#10  TRUE NA NA
#11 FALSE NA NA
#12 FALSE 12 10
#13 FALSE NA NA
#14 FALSE NA NA
#15 FALSE NA NA
</code>```

Title: Nearest index of a logical vector in R

Body:
I'm trying to get the index of the nearest TRUE value from a column based on the entry of another column. My sample dataframe goes like this:

a <- c(FALSE,TRUE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,FALSE)
b <- c(NA, NA, 3, NA, NA, NA, NA, 8, NA, NA, NA, 12, NA, NA, NA)
df <- data.frame(a, b)

I would like to make a new column that gives the index of the nearest TRUE value before a given value from b. To illustrate, the resulting df should look like this:

       a  b  c
1  FALSE NA NA
2   TRUE NA NA
3  FALSE  3  2
4  FALSE NA NA
5  FALSE NA NA
6   TRUE NA NA
7  FALSE NA NA
8  FALSE  8  6
9   TRUE NA NA
10  TRUE NA NA
11 FALSE NA NA
12 FALSE 12 10
13 FALSE NA NA
14 FALSE NA NA
15 FALSE NA NA

I know I can use max(which(df$a == TRUE)) but I don't know how to make it work in such a way that it only considers the index of the preceding values. Thanks!

Body:
We can get the index of all TRUE values and then use findInterval to get the closest one for each value in b.

inds <- which(df$a)
df$c <- inds[findInterval(df$b, inds)]
df

#       a  b  c
#1  FALSE NA NA
#2   TRUE NA NA
#3  FALSE  3  2
#4  FALSE NA NA
#5  FALSE NA NA
#6   TRUE NA NA
#7  FALSE NA NA
#8  FALSE  8  6
#9   TRUE NA NA
#10  TRUE NA NA
#11 FALSE NA NA
#12 FALSE 12 10
#13 FALSE NA NA
#14 FALSE NA NA
#15 FALSE NA NA


问:
How to add another column in a QColumnView based on the user's selection?
Using PySide2, I have an interface which contains a QColumnView widget, for which I am trying to create functionality similar to that of a contact-lookup: select a person's name and the next column over then displays more options/details about that selection.

Currently, I populate the view when the UI loads and it displays the first level of options available to the user.

Desired functionality: When the user makes a selection, another column is added to the QColumnView which displays the options available based on the user's selection.

Current problem: When the user makes a selection, since I am unsure of how to add another column/level to the QColumnView, instead, the model for the QColumnView is updated and only the next level of options are shown - meaning the previous values are overwritten in the view, so to speak. While this is functional, it is not ideal, as having the previous column still in view, enables the user to see which category they are currently searching.

As seen here, the user has selected 'Address' which then brings up options associated with 'Address' in the column to the right.

Just to create a basic interface that incorporates a QColumnView, it would look something like this:

```<code>import sys
from PySide2 import QtWidgets, QtCore
import PySide2

class UserInput(object):
    def setupUi(self, get_user_input=None):
        # Basic shape
        self.width = 425
        get_user_input.setObjectName("get_user_input")
        get_user_input.resize(425, self.width)
        self.frame = QtWidgets.QFrame(get_user_input)
        self.frame.setGeometry(QtCore.QRect(11, 10, 401, 381))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.frame.setObjectName("frame")
        # Creating the grid layout for most of the display elements
        self.gridLayoutWidget = QtWidgets.QWidget(self.frame)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 381, 361))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.get_user_input_layout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.get_user_input_layout.setContentsMargins(5, 5, 5, 5)
        self.get_user_input_layout.setObjectName("get_user_input_layout")
        # Grid layout for the buttons
        self.buttonLayoutGrid = QtWidgets.QWidget(get_user_input)
        self.buttonLayoutGrid.setGeometry(QtCore.QRect(10, 390, 401, 41))
        self.buttonLayoutGrid.setObjectName("buttonLayoutGrid")
        self.buttonLayout = QtWidgets.QGridLayout(self.buttonLayoutGrid)
        self.buttonLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonLayout.setObjectName("buttonLayout")
        # Buttons
        self.buttonOK = QtWidgets.QPushButton(self.buttonLayoutGrid)
        self.buttonOK.setObjectName("buttonOK")
        self.buttonOK.setText("OK")
        self.buttonLayout.addWidget(self.buttonOK, 0, 1, 1, 1)
        self.buttonCancel = QtWidgets.QPushButton(self.buttonLayoutGrid)
        self.buttonCancel.setObjectName("buttonCancel")
        self.buttonCancel.setText("CANCEL")
        self.buttonLayout.addWidget(self.buttonCancel, 0, 2, 1, 1)

        #Column View Data
        self.t = PySide2.QtWidgets.QColumnView()
        self.t.setColumnWidths([10,10])

        model = PySide2.QtGui.QStandardItemModel()
        model.setColumnCount(1)
        model.setHorizontalHeaderLabels(['Data Collections'])

        self._dict = {'Test 1': [1, 2, 3], 'Test 2': [4, 5, 6], 'Test 3': [7, 8, 9]}
        _data = []

        for each in self._dict:
            resultItem = PySide2.QtGui.QStandardItem()
            insertText = each
            resultItem.setText(str(insertText))
            model.appendRow(resultItem)

        self.t.setModel(model)
        self.t.clicked.connect(self.column_view_clicked)
        self.get_user_input_layout.addWidget(self.t, 2,0,1,1)

    def column_view_clicked(self, row):
        model = PySide2.QtGui.QStandardItemModel()
        model.setColumnCount(1)
        model.setHorizontalHeaderLabels(['Analysis Variables'])
        _data = []

        for i in self._dict[row.data()]:
            resultItem = PySide2.QtGui.QStandardItem()
            resultItem.setText(str(i))
            model.appendRow(resultItem)

        self.t.createColumn(row)

class UserInputPrompt(PySide2.QtWidgets.QDialog, UserInput):

    def __init__(self, path_to_image=None):
        app = PySide2.QtWidgets.QApplication(sys.argv)
        super(UserInputPrompt, self).__init__()
        self.setupUi(self)
        super(UserInputPrompt, self).exec_()

    def get_user_input(self):
        print("Get user selection")

def main():
    UserInputPrompt()

if __name__ == '__main__':
    main()
</code>```

When you run the above code, click on any of items on the left of the interface ('Test 1, 'Test 2' or 'Test 3') and the result will add a column to the right of the existing column but no data is currently being populated there - since I don't know how to do that at the moment.

答:
What the OP points out as a requirement is just the functionality of ColumnView, the problem is that you are not passing the model with the data structured correctly. As you can see the structure is of a tree where there are parent nodes and child nodes, so you must create a model with that structure. In this case I have used a QStandardItemModel to handle the data as I show below:

import sys
from PySide2 import QtCore, QtGui, QtWidgets

def populateTree(children, parent):
    for child in children:
        child_item = QtGui.QStandardItem(child)
        parent.appendRow(child_item)
        if isinstance(children, dict):
            populateTree(children[child], child_item)

class Dialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.frame = QtWidgets.QFrame(
            frameShape=QtWidgets.QFrame.StyledPanel, frameShadow=QtWidgets.QFrame.Sunken
        )
        self.buttonOK = QtWidgets.QPushButton(self.tr("OK"))
        self.buttonCancel = QtWidgets.QPushButton(self.tr("CANCEL"))

        self.columnview = QtWidgets.QColumnView()

        grid_layout = QtWidgets.QGridLayout(self)
        grid_layout.addWidget(self.frame, 0, 0, 1, 2)
        grid_layout.addWidget(self.buttonOK, 1, 0)
        grid_layout.addWidget(self.buttonCancel, 1, 1)

        lay = QtWidgets.QVBoxLayout(self.frame)
        lay.addWidget(self.columnview)

        data = {
            "root1": {
                "child11": ["subchild111", "subchild112"],
                "child12": ["subchild121"],
            },
            "root2": {
                "child21": ["subchild211"],
                "child22": ["subchild221", "subchild222"],
            },
        }

        self.model = QtGui.QStandardItemModel(self)
        self.columnview.setModel(self.model)
        populateTree(data, self.model.invisibleRootItem())

        self.resize(1280, 480)

def main():
    app = QtWidgets.QApplication(sys.argv)
    w = Dialog()
    w.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
```

Body:
Using PySide2, I have an interface which contains a QColumnView widget, for which I am trying to create functionality similar to that of a contact-lookup: select a person's name and the next column over then displays more options/details about that selection.

Currently, I populate the view when the UI loads and it displays the first level of options available to the user.

Desired functionality: When the user makes a selection, another column is added to the QColumnView which displays the options available based on the user's selection.

Current problem: When the user makes a selection, since I am unsure of how to add another column/level to the QColumnView, instead, the model for the QColumnView is updated and only the next level of options are shown - meaning the previous values are overwritten in the view, so to speak. While this is functional, it is not ideal, as having the previous column still in view, enables the user to see which category they are currently searching.

As seen here, the user has selected 'Address' which then brings up options associated with 'Address' in the column to the right.

Just to create a basic interface that incorporates a QColumnView, it would look something like this:

import sys
from PySide2 import QtWidgets, QtCore
import PySide2

class UserInput(object):
    def setupUi(self, get_user_input=None):
        # Basic shape
        self.width = 425
        get_user_input.setObjectName("get_user_input")
        get_user_input.resize(425, self.width)
        self.frame = QtWidgets.QFrame(get_user_input)
        self.frame.setGeometry(QtCore.QRect(11, 10, 401, 381))
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.frame.setObjectName("frame")
        # Creating the grid layout for most of the display elements
        self.gridLayoutWidget = QtWidgets.QWidget(self.frame)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 10, 381, 361))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.get_user_input_layout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.get_user_input_layout.setContentsMargins(5, 5, 5, 5)
        self.get_user_input_layout.setObjectName("get_user_input_layout")
        # Grid layout for the buttons
        self.buttonLayoutGrid = QtWidgets.QWidget(get_user_input)
        self.buttonLayoutGrid.setGeometry(QtCore.QRect(10, 390, 401, 41))
        self.buttonLayoutGrid.setObjectName("buttonLayoutGrid")
        self.buttonLayout = QtWidgets.QGridLayout(self.buttonLayoutGrid)
        self.buttonLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonLayout.setObjectName("buttonLayout")
        # Buttons
        self.buttonOK = QtWidgets.QPushButton(self.buttonLayoutGrid)
        self.buttonOK.setObjectName("buttonOK")
        self.buttonOK.setText("OK")
        self.buttonLayout.addWidget(self.buttonOK, 0, 1, 1, 1)
        self.buttonCancel = QtWidgets.QPushButton(self.buttonLayoutGrid)
        self.buttonCancel.setObjectName("buttonCancel")
        self.buttonCancel.setText("CANCEL")
        self.buttonLayout.addWidget(self.buttonCancel, 0, 2, 1, 1)

        #Column View Data
        self.t = PySide2.QtWidgets.QColumnView()
        self.t.setColumnWidths([10,10])

        model = PySide2.QtGui.QStandardItemModel()
        model.setColumnCount(1)
        model.setHorizontalHeaderLabels(['Data Collections'])

        self._dict = {'Test 1': [1, 2, 3], 'Test 2': [4, 5, 6], 'Test 3': [7, 8, 9]}
        _data = []

        for each in self._dict:
            resultItem = PySide2.QtGui.QStandardItem()
            insertText = each
            resultItem.setText(str(insertText))
            model.appendRow(resultItem)

        self.t.setModel(model)
        self.t.clicked.connect(self.column_view_clicked)
        self.get_user_input_layout.addWidget(self.t, 2,0,1,1)

    def column_view_clicked(self, row):
        model = PySide2.QtGui.QStandardItemModel()
        model.setColumnCount(1)
        model.setHorizontalHeaderLabels(['Analysis Variables'])
        _data = []

        for i in self._dict[row.data()]:
            resultItem = PySide2.QtGui.QStandardItem()
            resultItem.setText(str(i))
            model.appendRow(resultItem)

        self.t.createColumn(row)

class UserInputPrompt(PySide2.QtWidgets.QDialog, UserInput):

    def __init__(self, path_to_image=None):
        app = PySide2.QtWidgets.QApplication(sys.argv)
        super(UserInputPrompt, self).__init__()
        self.setupUi(self)
        super(UserInputPrompt, self).exec_()

    def get_user_input(self):
        print("Get user selection")

def main():
    UserInputPrompt()

if __name__ == '__main__':
    main()

When you run the above code, click on any of items on the left of the interface ('Test 1, 'Test 2' or 'Test 3') and the result will add a column to the right of the existing column but no data is currently being populated there - since I don't know how to do that at the moment.


问:
Send Multiple JSON Files from Directory to a REST API with JMETER
I'm really struggling with getting Jmeter to work with sending multiple json files in Jmeter to a REST API. I have tried other questions on stack and tutorials online and none of them answer my specific requirement.

My requirement is that I will have various json messages saved to a file directory and I'm trying to use JMeter to loop through the folder, pick up the json's and pop it into a HTTP request one at a time i.e. one file = one request and view the result.

Does any one know how to do this?

答:
The easiest solution would be:

Directory Listing Config plugin to read file names into a JMeter Variable

__FileToString() function to read the file content


问:
Perl : creating array of known size

I have to store data from request runned with Parallel::ForkManager.

But it comes not in order, I mean, I poll all ports of a switch, but some of them answer faster than others. So, I don't know how to save it, to display it later.

Can I do like that ?

```<code>my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
...
print @array;
</code>```

Or should I use a %hash with number of port as keys, but it seems not the best.

Thank you.

答:
A hash is a good data-type to use for "sparse arrays."  It seems like you're describing just that; a sparse array -- one where most of the elements would be undefined.  Perl would let you pre-size a standard array, but that's not what you need.  You seem to need a hash, where it wouldn't matter if you have $array[2], and $array[23], but none between, for example.  Using a native array, as soon as you create $array[23], all unused elements below 23 would spring into existence with 'undef' as their value.

With the hash, you would have $item{2}, and $item{23}.  You could get a list of which items are being held in the hash using the keys() function.

Title: Perl : creating array of known size

Body:
I have to store data from request runned with Parallel::ForkManager.

But it comes not in order, I mean, I poll all ports of a switch, but some of them answer faster than others. So, I don't know how to save it, to display it later.

Can I do like that ?

my @array = ();
$array[10] = "i am a string corresponding to port 10"
$array[2] = "the one for the port 2"
...
print @array;

Or should I use a %hash with number of port as keys, but it seems not the best.

Thank you.


问:
I want to return new column using Recursive in SQL?
I have table with column shown below

```<code>| Employee ID | Manager ID |
|:-----------:|:----------:|
| E068        | E067       |
| E071        | E067       |
| E229        | E069       |
| E248        | E144       |
| E226        | E223       |
| E236        | E241       |
| E066        | E001       |
| E067        | E001       |
| E144        | E001       |
| E223        | E001       |
| E001        | Null       |
| E241        | Null       |
</code>```

And we do have table which contains 'Leader ID'

```<code>| Leader ID |
|-----------|
| E001      |
| E241      |
</code>```

Problem Statement:

This problem is to identify the Head of Manager by using Employee and their Manager data.

About: We have an Employee ID and their Manager ID. Please note that Manager ID are from Employee ID. Since each manager has one Manager above their level.

First, we'll take all UNIQUE ID in Manager ID column.
Then for each ID from Manager ID column, we will look for their respective Manager ID(Manager)
Then we will create a new column name Leader which will contain all hierarchy of Manager.

Required Output:

```<code>| Employee ID | Manager ID  | Leader ID |
|-------------|-------------|-----------|
| E068        | E067        | E001      |
| E071        | E067        | E001      |
| E229        | E069        | E001      |
| E248        | E144        | E001      |
| E226        | E223        | E001      |
| E236        | E241        | E241      |
| E066        | E001        | E001      |
| E067        | E001        | E001      |
| E144        | E001        | E001      |
| E223        | E001        | E001      |

</code>```

The Employee ID column contain UNIQUE ID while Manager ID contain DUPLICATES ID.

答:
This is a canonical example of WITH RECURSIVE

Using RECURSIVE, a WITH query can refer to its own output.

Try this:

```<code>with recursive subordinates as
  (select
      employeid,
      e.managerid,
      e.managerid as leader
   from employes e
   where e.managerid in(select * from leaders) -- non recursive term
   union
   select
      e.employeid,
      e.managerid,
      a.managerid as leader
    from employes e
          join subordinates a on a.employeid = e.managerid -- recursive term
) select * from subordinates
</code>```

As described in documentation:

A WITH RECURSCIVE is always composed by

A non recursive term

UNION or UNION ALL

A recursive term, the only one which can refer to the query output

The recusion teminates when the previous iteration has no output.

Body:
I have table with column shown below

| Employee ID | Manager ID |
|:-----------:|:----------:|
| E068        | E067       |
| E071        | E067       |
| E229        | E069       |
| E248        | E144       |
| E226        | E223       |
| E236        | E241       |
| E066        | E001       |
| E067        | E001       |
| E144        | E001       |
| E223        | E001       |
| E001        | Null       |
| E241        | Null       |

And we do have table which contains 'Leader ID'

| Leader ID |
|-----------|
| E001      |
| E241      |

Problem Statement:

This problem is to identify the Head of Manager by using Employee and their Manager data.

About: We have an Employee ID and their Manager ID. Please note that Manager ID are from Employee ID. Since each manager has one Manager above their level.

First, we'll take all UNIQUE ID in Manager ID column.
Then for each ID from Manager ID column, we will look for their respective Manager ID(Manager)
Then we will create a new column name Leader which will contain all hierarchy of Manager.

Required Output:

| Employee ID | Manager ID  | Leader ID |
|-------------|-------------|-----------|
| E068        | E067        | E001      |
| E071        | E067        | E001      |
| E229        | E069        | E001      |
| E248        | E144        | E001      |
| E226        | E223        | E001      |
| E236        | E241        | E241      |
| E066        | E001        | E001      |
| E067        | E001        | E001      |
| E144        | E001        | E001      |
| E223        | E001        | E001      |

The Employee ID column contain UNIQUE ID while Manager ID contain DUPLICATES ID.

Body:
This is a canonical example of WITH RECURSIVE

Using RECURSIVE, a WITH query can refer to its own output.

Try this:

with recursive subordinates as
  (select
      employeid,
      e.managerid,
      e.managerid as leader
   from employes e
   where e.managerid in(select * from leaders) -- non recursive term
   union
   select
      e.employeid,
      e.managerid,
      a.managerid as leader
    from employes e
          join subordinates a on a.employeid = e.managerid -- recursive term
) select * from subordinates

As described in documentation:

A WITH RECURSCIVE is always composed by

A non recursive term

UNION or UNION ALL

A recursive term, the only one which can refer to the query output

The recusion teminates when the previous iteration has no output.


问:
I need to pass multiple arrays back to the model
```<code>  List<siplist> itemList = new List<siplist>();

 string AUNT= form["Amount"].Trim();    result  123,1234,123
 string Date = form["Date"].Trim();     result  2020-02-18,2020-02-17,2020-02-16
 string index = form["index"].Trim();   result 1,4,6

       itemList.Add(new siplist()
            {
                 Date= form["Date"].Trim()

            });
</code>```

I want get result  as

```<code>{index :1 ,Date: 2020-02-18 ,Aunt:123},{index :4 ,Date: 2020-02-17 ,Aunt:1234}
</code>```

I want to get the result is LIST return VIEW TO MODEL

答:
Here you go

```<code>List<siplist> itemList = new List<siplist>();
for(int i=0;i<3;i++)
{
    itemList.Add(new siplist() { index = index.Split(',')[i], Date = Date.Split(',')[i], Aunt = AUNT.Split(',')[i] });
}
Console.WriteLine(JsonConvert.SerializeObject(itemList));
</code>```

OUTPUT

```<code>[
    {
        "index": "1",
        "Date": "2020-02-18",
        "Aunt": "123"
    },
    {
        "index": "4",
        "Date": "2020-02-17",
        "Aunt": "1234"
    },
    {
        "index": "6",
        "Date": "2020-02-16",
        "Aunt": "123"
    }
]
</code>```

Body:
  List<siplist> itemList = new List<siplist>();

 string AUNT= form["Amount"].Trim();    result  123,1234,123
 string Date = form["Date"].Trim();     result  2020-02-18,2020-02-17,2020-02-16
 string index = form["index"].Trim();   result 1,4,6

       itemList.Add(new siplist()
            {
                 Date= form["Date"].Trim()

            });

I want get result  as

{index :1 ,Date: 2020-02-18 ,Aunt:123},{index :4 ,Date: 2020-02-17 ,Aunt:1234}

I want to get the result is LIST return VIEW TO MODEL

Body:
Here you go

List<siplist> itemList = new List<siplist>();
for(int i=0;i<3;i++)
{
    itemList.Add(new siplist() { index = index.Split(',')[i], Date = Date.Split(',')[i], Aunt = AUNT.Split(',')[i] });
}
Console.WriteLine(JsonConvert.SerializeObject(itemList));

OUTPUT

[
    {
        "index": "1",
        "Date": "2020-02-18",
        "Aunt": "123"
    },
    {
        "index": "4",
        "Date": "2020-02-17",
        "Aunt": "1234"
    },
    {
        "index": "6",
        "Date": "2020-02-16",
        "Aunt": "123"
    }
]


问:
How to Swap a Table from Vertical to horizontal in javascript?
What I want is exactly the same attributes but in horizontal view instead of vertical one.

Here I am just providing few json objects to add inside the table, just to see if it will be possible or not. In actual code, I have over 100 json objects for the table.

I tried the Swap method for this issue but I don't know how to use the swap method for Json objects.

My code for vertical table is given below:

var attributes = [{
    "name": "Asset #",
    "display_name": "Asset #",
    "key": "header2",
    "values": {
      "MSSBL": "4-194169767930##1-2H77NZSQ",
      "SNOW": "4-194169767930##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "Serial Number",
    "display_name": "Serial Number",
    "key": "header3",
    "values": {
      "MSSBL": "21256112##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
    "display_name": "ACCOUNT NUMBER",
    "key": "header6",
    "values": {
      "MSSBL": "532649##1-2H77NZSQ",
      "SNOW": "NA##1-2H77NZSQ"
    },
    "type": "header",
    "data_type": "Text",
    "editable": "N"
  }
]

var key = [];

document.write("

");
for (key in attributes[0]) {
  document.write('' + '' + key + '' + '	');
}
document.write("
");
for (var i = 0; i < attributes.length; i++) {
  document.write('
');
  for (key in attributes[i]) {
    document.write('' + attributes[i][key] + '	');
  }
  document.write('
');
}
document.write("
");```

答:
Try this One</p>

```<code>   function demo(attributes) {
    var key = [];

    document.write("<table border==\"1\">");
   var i = 0;
   for (key in attributes[i]) {
    document.write("<tr>");
document.write('<td>' + '<b>' + key + '</b>' + '</td>');
while (i < attributes.length) {
  if (attributes[i][key].constructor == Object) {
    var levelDown = attributes[i][key];
    document.write('<td>');
    for(var subKey in levelDown) {
      document.write(subKey + ':' + levelDown[subKey] + '<br>');
    }
    document.write('</td>');
  } else {
    document.write('<td>' + attributes[i][key] + '</td>');
  }
    i++;
   }
   i = 0;
  document.write("</tr>");
   }
    document.write("</tr>");
  document.write("</table>");
   }

      demo([{
   "name": "Asset #",
  "display_name": "Asset #",
  "key": "header2",
   "values": {
    "MSSBL": "4-194169767930##1-2H77NZSQ",
  "SNOW": "4-194169767930##1-2H77NZSQ"
},
"type": "header",
"data_type": "Text",
"editable": "N"
   },
    {
    "name": "Serial Number",
      "display_name": "Serial Number",
     "key": "header3",
     "values": {
  "MSSBL": "21256112##1-2H77NZSQ",
  "SNOW": "NA##1-2H77NZSQ"
   },
     "type": "header",
      "data_type": "Text",
     "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
   "display_name": "ACCOUNT NUMBER",
   "key": "header6",
    "values": {
     "MSSBL": "532649##1-2H77NZSQ",
     "SNOW": "NA##1-2H77NZSQ"
    },
   "type": "header",
   "data_type": "Text",
       "editable": "N"
     }
     ]);
</code>```

Body:
Try this One

   function demo(attributes) {
    var key = [];

    document.write("<table border==\"1\">");
   var i = 0;
   for (key in attributes[i]) {
    document.write("<tr>");
document.write('<td>' + '<b>' + key + '</b>' + '</td>');
while (i < attributes.length) {
  if (attributes[i][key].constructor == Object) {
    var levelDown = attributes[i][key];
    document.write('<td>');
    for(var subKey in levelDown) {
      document.write(subKey + ':' + levelDown[subKey] + '<br>');
    }
    document.write('</td>');
  } else {
    document.write('<td>' + attributes[i][key] + '</td>');
  }
    i++;
   }
   i = 0;
  document.write("</tr>");
   }
    document.write("</tr>");
  document.write("</table>");
   }

      demo([{
   "name": "Asset #",
  "display_name": "Asset #",
  "key": "header2",
   "values": {
    "MSSBL": "4-194169767930##1-2H77NZSQ",
  "SNOW": "4-194169767930##1-2H77NZSQ"
},
"type": "header",
"data_type": "Text",
"editable": "N"
   },
    {
    "name": "Serial Number",
      "display_name": "Serial Number",
     "key": "header3",
     "values": {
  "MSSBL": "21256112##1-2H77NZSQ",
  "SNOW": "NA##1-2H77NZSQ"
   },
     "type": "header",
      "data_type": "Text",
     "editable": "N"
  },
  {
    "name": "ACCOUNT NUMBER",
   "display_name": "ACCOUNT NUMBER",
   "key": "header6",
    "values": {
     "MSSBL": "532649##1-2H77NZSQ",
     "SNOW": "NA##1-2H77NZSQ"
    },
   "type": "header",
   "data_type": "Text",
       "editable": "N"
     }
     ]);


问:
Is there a way to wrap external type definitions into module?
Let's assume that we have type provided by some file like types.d.ts

```<code>declare function test(arg: string): void;
</code>```

Is there a way to import types into own type definition and wrapped it into namespace?
i would like to have something like

```<code>import { test } from 'some-weird-module/types.d.ts';

declare namespace MyModule {
    export test;
}
</code>```

答:
Types in a .d.ts file should not need to be imported => skip import { test } from 'some-weird-module/types.d.ts';.

Then, I don't thing that it's possible to wrap these types in a namespace in one line. But, for each type to export, we can try to create a type alias that can be exported:

declare namespace MyModule {
    export type T1bis = T1; // T1 came from 'some-weird-module/types.d.ts'
    export type T2bis = T2; // T2 came from 'some-weird-module/types.d.ts'
    // etc.
}
```

Body:
Let's assume that we have type provided by some file like types.d.ts

declare function test(arg: string): void;

Is there a way to import types into own type definition and wrapped it into namespace?
i would like to have something like

import { test } from 'some-weird-module/types.d.ts';

declare namespace MyModule {
    export test;
}


问:
Angular 9 production build with webpack
I have an Angular application that I regularly update and build with the latest Webpack bundler.
 Some days ago I upgraded the project to Angular 9 and encountered some issues that I couldn't resolve.

npm run build:prod

error TS2307: Cannot find module './app/app.module.ngfactory'.

I think it's casued by this part of webpack config because module import is changed in Angular 9. However, I'm not absolutely sure about it.

```<code>  plugins: [
    new ngw.AngularCompilerPlugin({
      tsConfigPath: path.resolve(rootPath, 'tsconfig.aot.json'),
      entryModule: path.resolve(rootPath, 'src', 'app', 'app.module#AppModule')
    })
  ]
</code>```

npm run test

File not found: ./node_modules/jest-preset-angular/InlineHtmlStripStylesTransformer (resolved as: .../angular-webpack-build/node_modules/jest-preset-angular/InlineHtmlStripStylesTransformer)

This error is a bit mysterious to me. I've read some posts about similar issues, but those advices didn't work.

Below you can find my configuration files, but the whole project is available on GitHub: https://github.com/aszidien/angular-webpack-build

package.json

```<code>...
  "scripts": {
    "build:dev": "cross-env NODE_ENV=development webpack --mode development",
    "build:prod": "cross-env NODE_ENV=production webpack --mode production",
    "test": "jest"
  }
...
</code>```

tsconfig.aot.json

```<code>{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "skipMetadataEmit": true
  }
}
</code>```

webpack.config.common.js

```<code>const webpackMerge = require('webpack-merge');

const commonConfig = require('./webpack.config.common');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',
  output: {
    publicPath: '/',
    filename: 'bundle.js',
    chunkFilename: '[id].chunk.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader', options: {
              transpileOnly: true
            }
          },
          { loader: 'angular2-template-loader' },
          { loader: 'angular-router-loader' }
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});
</code>```

webpack.config.prod.js

```<code>const webpackMerge = require('webpack-merge');

const commonConfig = require('./webpack.config.common');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',
  output: {
    publicPath: '/',
    filename: 'bundle.js',
    chunkFilename: '[id].chunk.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader', options: {
              transpileOnly: true
            }
          },
          { loader: 'angular2-template-loader' },
          { loader: 'angular-router-loader' }
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});
</code>```

答: in Angular 9 with Ivy, there are no ngfactory files anymore, you should remove the main-aot.ts file

Title: Angular 9 production build with webpack

Body:
I have an Angular application that I regularly update and build with the latest Webpack bundler.
 Some days ago I upgraded the project to Angular 9 and encountered some issues that I couldn't resolve.

npm run build:prod

error TS2307: Cannot find module './app/app.module.ngfactory'.

I think it's casued by this part of webpack config because module import is changed in Angular 9. However, I'm not absolutely sure about it.

  plugins: [
    new ngw.AngularCompilerPlugin({
      tsConfigPath: path.resolve(rootPath, 'tsconfig.aot.json'),
      entryModule: path.resolve(rootPath, 'src', 'app', 'app.module#AppModule')
    })
  ]

npm run test

File not found: ./node_modules/jest-preset-angular/InlineHtmlStripStylesTransformer (resolved as: .../angular-webpack-build/node_modules/jest-preset-angular/InlineHtmlStripStylesTransformer)

This error is a bit mysterious to me. I've read some posts about similar issues, but those advices didn't work.

Below you can find my configuration files, but the whole project is available on GitHub: https://github.com/aszidien/angular-webpack-build

package.json

...
  "scripts": {
    "build:dev": "cross-env NODE_ENV=development webpack --mode development",
    "build:prod": "cross-env NODE_ENV=production webpack --mode production",
    "test": "jest"
  }
...

tsconfig.aot.json

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "skipMetadataEmit": true
  }
}

webpack.config.common.js

const webpackMerge = require('webpack-merge');

const commonConfig = require('./webpack.config.common');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',
  output: {
    publicPath: '/',
    filename: 'bundle.js',
    chunkFilename: '[id].chunk.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader', options: {
              transpileOnly: true
            }
          },
          { loader: 'angular2-template-loader' },
          { loader: 'angular-router-loader' }
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});

webpack.config.prod.js

const webpackMerge = require('webpack-merge');

const commonConfig = require('./webpack.config.common');

module.exports = webpackMerge(commonConfig, {
  devtool: 'cheap-module-eval-source-map',
  output: {
    publicPath: '/',
    filename: 'bundle.js',
    chunkFilename: '[id].chunk.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader', options: {
              transpileOnly: true
            }
          },
          { loader: 'angular2-template-loader' },
          { loader: 'angular-router-loader' }
        ]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    stats: 'minimal'
  }
});


问:
how to make assigned id not change with data binding in angular 2
I want to make the dynamic ids like canvas1, canvas2, canvas3, etc. Here i binded id with {{cc}}

```<code><canvas width="100%" height="100%" id="canvas{{cc}}" class="canvas-size"></canvas>
</code>```

```<code>public cc = 1 ;
  ngAfterViewInit() {
    console.log('AfterViewInit', this.cc);
    for (var i in this.testing) {
      console.log("cc",this.cc);
      this.chart = new Chart('canvas'+ this.cc, {
        type: 'doughnut',
        data: {
          labels: ['Data1', 'Data2', 'Data3', 'Data4'],
          datasets: [
            {
              data: [25, 50, 20, 5],
              backgroundColor: ['#2D5E9E', '#46AACE', '#DCECC9', '#f7f9fa']
            }
          ]
        },
        options: {
          responsive: true,
          tooltips: {
            enabled: false
          },
          cutoutPercentage: 75,
          title: {
            display: false,
            position: 'top',
            fontStyle: 'bold',
            fontSize: 0,
            fullWidth: false,
            padding: 0
          },
          legend: {
            display: false,
            position: 'top',
            fullWidth: false,
            labels: {
              display: false,
              usePointStyle: true,
              fontSize: 15,
              fontStyle: 'bold'
            }
          }
        }
      });
      this.cc++;
    }
  }
</code>```

Problem is after the loop ended, all canvas id become canvas5 (last count).
Is there a way to assign so it becomes canvas1, canvas2, canvas3 etc. without just assigning the last count?
Note I cant assign the id from html because of nested loops hence I'm finding a way to bind thx.

答:
Put your charts into an array and you can do something similar to this.</p>

```<code><mat-cell *matCellDef="let chartsArray; let cc = index;" class="px-0 col">
  <canvas width="100%" height="100%" id="canvas{{cc}}" class="canvas-size"></canvas>
</code>```

Body:
I want to make the dynamic ids like canvas1, canvas2, canvas3, etc. Here i binded id with {{cc}}

<canvas width="100%" height="100%" id="canvas{{cc}}" class="canvas-size"></canvas>

public cc = 1 ;
  ngAfterViewInit() {
    console.log('AfterViewInit', this.cc);
    for (var i in this.testing) {
      console.log("cc",this.cc);
      this.chart = new Chart('canvas'+ this.cc, {
        type: 'doughnut',
        data: {
          labels: ['Data1', 'Data2', 'Data3', 'Data4'],
          datasets: [
            {
              data: [25, 50, 20, 5],
              backgroundColor: ['#2D5E9E', '#46AACE', '#DCECC9', '#f7f9fa']
            }
          ]
        },
        options: {
          responsive: true,
          tooltips: {
            enabled: false
          },
          cutoutPercentage: 75,
          title: {
            display: false,
            position: 'top',
            fontStyle: 'bold',
            fontSize: 0,
            fullWidth: false,
            padding: 0
          },
          legend: {
            display: false,
            position: 'top',
            fullWidth: false,
            labels: {
              display: false,
              usePointStyle: true,
              fontSize: 15,
              fontStyle: 'bold'
            }
          }
        }
      });
      this.cc++;
    }
  }

Problem is after the loop ended, all canvas id become canvas5 (last count).
Is there a way to assign so it becomes canvas1, canvas2, canvas3 etc. without just assigning the last count?
Note I cant assign the id from html because of nested loops hence I'm finding a way to bind thx.

Body:
Put your charts into an array and you can do something similar to this.

<mat-cell *matCellDef="let chartsArray; let cc = index;" class="px-0 col">
  <canvas width="100%" height="100%" id="canvas{{cc}}" class="canvas-size"></canvas>


问:
ReactJS material makeStyles
I have my own theme, I can theming well.
Right now I have three different styles with material UI tabs. That's why I need to change styles using makeStyles.

This is example of tab I need to change

```<code>...

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: "100%",
    backgroundColor: theme.pallete.primary
  },
  tabs: {
  /// some styles
  }
...
}
));

...

<Tabs
 ...someProps
 className={classes.tabs}
>
</code>```

 element inside tab have such classes:

```<code> <button class="MuiButtonBase-root MuiTab-root MuiTab-textColorSecondary Mui-selected MuiTab-labelIcon">
</code>```

I have tried to edit styles the same way as

```<code>... = createMuiTHeme ({
overrides: {
...some overrides
}
</code>```

in my case:

```<code>const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: "100%",
    backgroundColor: "#121D42",
   MuiButtonBase: {
    root: {
    ///some styles
    },
   }
  },
...
</code>```

but it doesn't work with makeStyles

So how can I edit buttons inside tabs using makeStyles(), is it possible? Or help me with solution please

答:
I have found a solution for now.

Using Styled Components and with creating a styled element - we can change styles easier. We should StylesProvider

```<code>const NewButton = styled(({styledComponentProp, ...rest}) => (
  <Button classes={{label: 'label'}} {...rest}/>
))`
  .label {
    color: blue;
    font-size: ${props => props.styledComponentProp};
  }
`

export const BlueButton = styled(props => {
  return (

    <StylesProvider injectFirst>
    <NewButton variant="contained" styledComponentProp="20px"> Red Labeled Button </NewButton>
  </StylesProvider>
  );
})`

`;
</code>```

But have we any better solutions?

Title: ReactJS material makeStyles

Body:
I have my own theme, I can theming well.
Right now I have three different styles with material UI tabs. That's why I need to change styles using makeStyles.

This is example of tab I need to change

...

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: "100%",
    backgroundColor: theme.pallete.primary
  },
  tabs: {
  /// some styles
  }
...
}
));

...

<Tabs
 ...someProps
 className={classes.tabs}
>

 element inside tab have such classes:

 <button class="MuiButtonBase-root MuiTab-root MuiTab-textColorSecondary Mui-selected MuiTab-labelIcon">

I have tried to edit styles the same way as

... = createMuiTHeme ({
overrides: {
...some overrides
}

in my case:

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: "100%",
    backgroundColor: "#121D42",
   MuiButtonBase: {
    root: {
    ///some styles
    },
   }
  },
...

but it doesn't work with makeStyles

So how can I edit buttons inside tabs using makeStyles(), is it possible? Or help me with solution please

Body:
I have found a solution for now.

Using Styled Components and with creating a styled element - we can change styles easier. We should StylesProvider

const NewButton = styled(({styledComponentProp, ...rest}) => (
  <Button classes={{label: 'label'}} {...rest}/>
))`
  .label {
    color: blue;
    font-size: ${props => props.styledComponentProp};
  }
`

export const BlueButton = styled(props => {
  return (

    <StylesProvider injectFirst>
    <NewButton variant="contained" styledComponentProp="20px"> Red Labeled Button </NewButton>
  </StylesProvider>
  );
})`

`;

But have we any better solutions?


问:
Logout for an app which having multiple storyboards swift 5 (Going back to root view controller)
How to go back to rootview controller in swift 5 where scenedelegate is available instead of Appdelegate

```<code>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        guard let _ = (scene as? UIWindowScene) else { return }
        if let windowScene = scene as? UIWindowScene {
            self.window = UIWindow(windowScene: windowScene)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController =
                storyboard.instantiateViewController(withIdentifier: "first_page")
            self.window!.rootViewController = initialViewController
            self.window!.makeKeyAndVisible()
        }
    }
</code>```

this is my scenedelegate code need to dismiss/popback to my first page.

i am having the first page in
Main.storyboard but my logout function is in another storyboard called Home.storyboard

tried

```<code>self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
</code>```

and

```<code>self.navigationController?.popToRootViewController(animated: true)
</code>```

But not working i have only one navigation controller that is for the first viewcontroller

答:
Try this:-

```<code>let viewController = UIApplication.shared.windows.first!.rootViewController as!
YourViewController
</code>```

And then use this viewController

Body:
How to go back to rootview controller in swift 5 where scenedelegate is available instead of Appdelegate

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
//        guard let _ = (scene as? UIWindowScene) else { return }
        if let windowScene = scene as? UIWindowScene {
            self.window = UIWindow(windowScene: windowScene)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let initialViewController =
                storyboard.instantiateViewController(withIdentifier: "first_page")
            self.window!.rootViewController = initialViewController
            self.window!.makeKeyAndVisible()
        }
    }

this is my scenedelegate code need to dismiss/popback to my first page.

i am having the first page in
Main.storyboard but my logout function is in another storyboard called Home.storyboard

tried

self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)

and

self.navigationController?.popToRootViewController(animated: true)

But not working i have only one navigation controller that is for the first viewcontroller

Body:
Try this:-

let viewController = UIApplication.shared.windows.first!.rootViewController as!
YourViewController

And then use this viewController


问:
Regex strip all html tags excluding
 &
I am relatively new to regex but my aim is to strip all html tags from a string excluding
s and  tags with the class='user'. I want to user this regex to clean unwanted html garbage from contentedittable fields.

Hope one of you regex masters can help...

Here is an example to test on: http://gskinner.com/RegExr/?2tpai

I think I'm close, but the closing tag of the a class='user' is currently still being selected as garbage when it is required.

答:
Formally speaking you can't parse HTML with regex, because HTML is not a regular language. See also Can you provide some examples of why it is hard to parse XML and HTML with a regex? for some nightmare material.

Undoubtedly you can come up with some regexes that work in "most" situations, or "sensible" situations, but if you're sanitising user input via the regex this won't be sufficient.  It's not a million miles away from trying to substitute SQL parameters via elaborate textual replacement and escaping; no matter how clever you are, the correct answer is to use a different approach as some weakness will still exist.

In this case, that approach would be using an HTML parsing library to read the text, and then remove the
 and  tags from the parsed DOM.  (This is much more robust then trying to remove a sequence of characters from the raw text, and probably creates more understandable source code too!).  In fact, since you're probably talking about JS in the client, you already have the DOM available, pre-parsed by the browser, so this would be a simple operation.

If you're unfamiliar with JavaScript's DOM manipulation methods, I consider the quirksmode intro to be approachable and informative.

Title:
Regex strip all html tags excluding
 &

Body:
Formally speaking you can't parse HTML with regex, because HTML is not a regular language. See also Can you provide some examples of why it is hard to parse XML and HTML with a regex? for some nightmare material.

Undoubtedly you can come up with some regexes that work in "most" situations, or "sensible" situations, but if you're sanitising user input via the regex this won't be sufficient.  It's not a million miles away from trying to substitute SQL parameters via elaborate textual replacement and escaping; no matter how clever you are, the correct answer is to use a different approach as some weakness will still exist.

In this case, that approach would be using an HTML parsing library to read the text, and then remove the <br> and <a> tags from the parsed DOM.  (This is much more robust then trying to remove a sequence of characters from the raw text, and probably creates more understandable source code too!).  In fact, since you're probably talking about JS in the client, you already have the DOM available, pre-parsed by the browser, so this would be a simple operation.

If you're unfamiliar with JavaScript's DOM manipulation methods, I consider the quirksmode intro to be approachable and informative.


问:
How to send a message to specific user using aspnetcore signalR?
I have a requirement to send notification to specific user. I am using dotnet core 3.1. ASPNETCORE signalR for the notification.
I am able to send the messages to all clients but unablt to do so for specific user.

EDIT 1

My Hub looks like :

```<code>public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}
</code>```

And i am calling the SendAsync method from Controller as :

```<code> private IHubContext<NotificationHub> _hub;

    public NotificationController(IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

[HttpGet]
    public IActionResult Get()
    {
        //_hub.Clients.All.SendAsync("SendMessage",
        _hub.Clients.All.SendAsync("SendMessage",
            new
            {
                val1 = getRandomString(),
                val2 = getRandomString(),
                val3 = getRandomString(),
                val4 = getRandomString()
            });

        return Ok(new { Message = "Request Completed" });
    }
</code>```

答:
You can send message to specific user via user id

In this example, we will try to get current user info and send some data back to that user using user id:

In the hub:

public async Task GetInfo()
{
    var user = await _userManager.GetUserAsync(Context.User);

    await Clients.User(user.Id).SendCoreAsync("msg", new object[] { user.Id, user.Email });
}
```

<p>In the client:</p>

<pre class="lang-js prettyprint-override"><code>connection.on('msg', function (...data) {
    console.log('data:', data); // ["27010e2f-a47f-4c4e-93af-b55fd95f48a5", "foo@bar.com"]
});

connection.start().then(function () {
    connection.invoke('getinfo');
});
</code>```

Note: Make sure you've already mapped the hub inside UseEndpoints method:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapHub<YourHubName>("/yourhubname");
});
```

Body:
I have a requirement to send notification to specific user. I am using dotnet core 3.1. ASPNETCORE signalR for the notification.
I am able to send the messages to all clients but unablt to do so for specific user.

EDIT 1

My Hub looks like :

public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}

And i am calling the SendAsync method from Controller as :

 private IHubContext<NotificationHub> _hub;

    public NotificationController(IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

[HttpGet]
    public IActionResult Get()
    {
        //_hub.Clients.All.SendAsync("SendMessage",
        _hub.Clients.All.SendAsync("SendMessage",
            new
            {
                val1 = getRandomString(),
                val2 = getRandomString(),
                val3 = getRandomString(),
                val4 = getRandomString()
            });

        return Ok(new { Message = "Request Completed" });
    }

Body:
You can send message to specific user via user id

In this example, we will try to get current user info and send some data back to that user using user id:

In the hub:

public async Task GetInfo()
{
    var user = await _userManager.GetUserAsync(Context.User);

    await Clients.User(user.Id).SendCoreAsync("msg", new object[] { user.Id, user.Email });
}

In the client:

connection.on('msg', function (...data) {
    console.log('data:', data); // ["27010e2f-a47f-4c4e-93af-b55fd95f48a5", "foo@bar.com"]
});

connection.start().then(function () {
    connection.invoke('getinfo');
});

Note: Make sure you've already mapped the hub inside UseEndpoints method:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapHub<YourHubName>("/yourhubname");
});


问:
issue in query params in angular 8
I have a problem with the query parameters in angular 8. This is the code:

```<code>headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }
</code>```

I also tried

```<code>let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);
</code>```

and

```<code>let params = new HttpParams().set('username', username).set('password', password);
</code>```

and

```<code>let params = new HttpParams().append('username', username).append('password', password);
</code>```

The backend server get username and password as undefined, previously I had this code that worked correctly:

```<code> login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}
</code>```

What's wrong? Thanks

答:
I'd write it like this

```<code>const options = {headers: this.headers, params: {username, password}};
this.http.post<any>(this.host + 'login', null, options);
</code>```

You need to change your headers object, there's no need for the HttpHeader wrapper around it

```<code>headers = {
    'Content-Type' : 'application/json',
    'Accept': 'application/json'
};
</code>```

Btw: if your don't send a body maybe reevaluate the need for a post request

Title: issue in query params in angular 8

Body:
I have a problem with the query parameters in angular 8. This is the code:

headers = {
        headers: new HttpHeaders({
            'Content-Type' : 'application/json',
            'Accept': 'application/json'
        })
    };

login(username, password) {

        console.log('login');

        let params = new HttpParams();
        params = params.append('username', username);
        params = params.append('password', password);
        let options = { headers: this.headers, params: params };

        return this.http.post<any>(this.host + 'login', options).pipe(map(data => {

                console.table(data);
                this.setSession(data);
                this.currentUserSubject.next(data.user);

            }));

    }

I also tried

let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);

and

let params = new HttpParams().set('username', username).set('password', password);

and

let params = new HttpParams().append('username', username).append('password', password);

The backend server get username and password as undefined, previously I had this code that worked correctly:

 login(username, password) {

    console.log('login');

    return this.http.post<any>('http://localhost:8080/login?username='+username+'&password='+password,
        {headers:{
            'Content-Type' : 'application/json',
            'Accept': 'application/json'}}
    ).pipe(map(data => {

        this.setSession(data);
        this.currentUserSubject.next(data.user);

    }));

}

What's wrong? Thanks

Body:
I'd write it like this

const options = {headers: this.headers, params: {username, password}};
this.http.post<any>(this.host + 'login', null, options);

You need to change your headers object, there's no need for the HttpHeader wrapper around it

headers = {
    'Content-Type' : 'application/json',
    'Accept': 'application/json'
};

Btw: if your don't send a body maybe reevaluate the need for a post request


问:
azure functions unable to scaffold dbcontext
Using VS 2019, .net core 2.1 and 3.1 I tried to create a map of existing db.

I executed the following npm commands

```<code>Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.1
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.1

Scaffold-DbContext "Server=yourservername;Database=yourDbName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
</code>```

Got the following error:

Error:   An assembly specified in the application dependencies
manifest (FunctionApp1.deps.json) was not found:
package: 'FunctionApp1', version: '1.0.0'
path: 'FunctionApp1.dll'

I tried to create a Class Library that executes that NPM above and reference it from my azure function as a workaround. However, whenever I run the method (eg: function1), it generates the following error message

An unhandled host error has occurred. [17/02/2020 12:42:30 PM] Microsoft.Azure.WebJobs.Host: 'Function1' can't be invoked from Azure
WebJobs SDK. Is it missing Azure WebJobs SDK attributes?

can someone please help?

screenshot as per below

答:
Found the solution.

go to your .csproj file and have the following tag:

<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT' ">
    <Exec Command="copy /Y "$(TargetDir)bin\*.dll" "$(TargetDir)*.dll"
\n" />
</Target>
```
<p>go th nuget command</p>
```Install-Package Microsoft.EntityFrameworkCore -Version 2.2.1
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.1
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.1
 Scaffold-DbContext "Server=yourservername;Database=yourdbname;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
```

And then do not forget to build the project.

It works on mine

Body:
Using VS 2019, .net core 2.1 and 3.1 I tried to create a map of existing db.

I executed the following npm commands

Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.1
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.1

Scaffold-DbContext "Server=yourservername;Database=yourDbName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Got the following error:

Error:   An assembly specified in the application dependencies
manifest (FunctionApp1.deps.json) was not found:
package: 'FunctionApp1', version: '1.0.0'
path: 'FunctionApp1.dll'

I tried to create a Class Library that executes that NPM above and reference it from my azure function as a workaround. However, whenever I run the method (eg: function1), it generates the following error message

An unhandled host error has occurred. [17/02/2020 12:42:30 PM] Microsoft.Azure.WebJobs.Host: 'Function1' can't be invoked from Azure
WebJobs SDK. Is it missing Azure WebJobs SDK attributes?

can someone please help?

screenshot as per below

Body:
Found the solution.

go to your .csproj file and have the following tag:

<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(OS)' == 'Windows_NT' ">
    <Exec Command="copy /Y &quot;$(TargetDir)bin\*.dll&quot; &quot;$(TargetDir)*.dll&quot;&#xD;&#xA;" />
</Target>

go th nuget command

Install-Package Microsoft.EntityFrameworkCore -Version 2.2.1
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.1
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.1
 Scaffold-DbContext "Server=yourservername;Database=yourdbname;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

And then do not forget to build the project.

It works on mine