问:
How do we store and pass list of selected values form Mat-Check box selected rows into another Router Service
I am very new to the angular and I have a component which has a mat-table with checkboxes using SelectionModel. Below is the Component and HTML code.

I have to pass the array of selection Emploee_number values into another EmployeeDetails Router service to display the detailed employee information.

Please help me how to store all the selected emploee_numbers into array and pass the values into another router service.

Component Code

```<code>import { SelectionModel } from "@angular/cdk/collections";
import { AfterViewInit, Component, ViewChild, OnInit } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import { EmployeeTableService } from "src/app/Services/employers.service";

export interface EmployersData {
  Employee_name: string;
  Employee_number: string;
  start_date_active: string;
  end_date_active: string;
}

@Component({
  selector: "employers",
  styleUrls: ["./employers.css"],
  templateUrl: "./employers.html",
})

export class Employees implements AfterViewInit {
  displayedColumns: string[] = [
    "select",
    "Employee_name",
    "Employee_number",
    "start_date_active",
    "end_date_active
  ];
  dataSource: MatTableDataSource<EmployeesData>;
  selection = new SelectionModel<EmployeesData>(true, []);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private EmployeeTableService: EmployeeTableService
  ) {}

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.data.forEach((row) => this.selection.select(row));
  }

  ngAfterViewInit() {
     this.retrieveEmployees();
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  retrieveSuppliers(): void {
    this.EmployeeTableService.getEmployees().subscribe(
      (data) => {
        this.dataSource = new MatTableDataSource(data);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        console.log("Data Successfully Retrived");
      },
      (error) => {
        console.log(error);
      }
    );
  }
}
</code>```

HTML code

```<code><div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="select">
      <th mat-header-cell *matHeaderCellDef>
        <mat-checkbox (change)="$event ? masterToggle() : null"
                      [checked]="selection.hasValue() && isAllSelected()"
                      [indeterminate]="selection.hasValue() && !isAllSelected()">
        </mat-checkbox>
      </th>

    <td mat-cell *matCellDef = "let row">
      <mat-checkbox (click)= "$event.stopPropagation()"
                     (change) = "$event ? selection.toggle(row) : null"
                     [checked]="selection.isSelected(row)">
      </mat-checkbox>
    </td>
  </ng-container>

      <ng-container matColumnDef="Employee_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Employee Name </th>
        <td mat-cell *matCellDef="let row"> {{row.Employee_name}} </td>
      </ng-container>

      <ng-container matColumnDef="Employee_number">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Vendor Number </th>
        <td mat-cell *matCellDef="let row"> {{row.Employee_number}} </td>
      </ng-container>

      <ng-container matColumnDef="start_date_active">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> End Date Active </th>
        <td mat-cell *matCellDef="let row"> {{row.start_date_active}} </td>
      </ng-container>

      <ng-container matColumnDef="end_date_active">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> End Date Active </th>
        <td mat-cell *matCellDef="let row"> {{row.end_date_active}} </td>
      </ng-container>

           </table>

    </div>
</code>```

Employers table Service

```<code>     import { Injectable } from '@angular/core';
     import { HttpClient } from '@angular/common/http';
     import { Observable } from 'rxjs';
     import { map, publishReplay, refCount } from 'rxjs/operators';

     import { environment } from '../../environments/environment';
     const baseUrl = environment.BACKEND_URL;

     export interface EmployersData {
     employee_name: string;
     employee_number: string;
     start_date_active: string;
     end_date_active: string;
        }

       @Injectable({
       providedIn: 'root'
        })

     export class EmployersTablesService {

     employersData: Observable<EmployersData[]>;

     constructor(private http: HttpClient) { }

      getEmployers() {
        if (!this.employersData) {
      this.employersData = this.http.get(`${baseUrl}/employers`).pipe(
          map((data:any) => data.data),
          publishReplay(1),
          refCount()
          );
       }
     return this.employersData;
       }

       }
</code>```

答:
I see that on each checking of an Employee we run masterToggle() and we store checked Employees using this.dataSource.data.forEach((row) => this.selection.select(row)); into selection.

I don't see class or interface for EmployeesData so I don't know exactly what it's data structure is like, so be ready to refactor a little bit. Also I don't know what EmployeeTableService does but we're going to use that as medium to share data. from ArchSuppliers -> EmployeeTableService -> EmployeeDetails.

Let's take Employee_number's from all selected items and send it to

masterToggle() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.data.forEach((row) => this.selection.select(row));
this.sendEmployeeNumbers();
  }

sendEmployeeNumbers() {
  let selectedEmployeeNumbers = [];
    for (let employee of this.selection) {
      selectedEmployeeNumbers.push(employee.Employee_number)
    }
 this.EmployeeTableService.selectedEmployeeNumbers.next(selectedEmployeeNumbers);
}
```
<p>To your EmployeeTableService add an observer that receives an array of selectedEmployeeNumbers and emits this to all subscribers</p>
<pre class="lang-js prettyprint-override"><code>selectedEmployeeNumbers = new ReplaySubject<number[]>(1);
</code>```

And subscribe to that data on EmployeeDetails

this.selectedEmployeeNumbers$ = this.EmployeeTableService.selectedEmployeeNumbers.pipe(data => {return data;})
```

Body:
I am very new to the angular and I have a component which has a mat-table with checkboxes using SelectionModel. Below is the Component and HTML code.

I have to pass the array of selection Emploee_number values into another EmployeeDetails Router service to display the detailed employee information.

Please help me how to store all the selected emploee_numbers into array and pass the values into another router service.

Component Code

import { SelectionModel } from "@angular/cdk/collections";
import { AfterViewInit, Component, ViewChild, OnInit } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import { EmployeeTableService } from "src/app/Services/employers.service";

export interface EmployersData {
  Employee_name: string;
  Employee_number: string;
  start_date_active: string;
  end_date_active: string;
}

@Component({
  selector: "employers",
  styleUrls: ["./employers.css"],
  templateUrl: "./employers.html",
})

export class Employees implements AfterViewInit {
  displayedColumns: string[] = [
    "select",
    "Employee_name",
    "Employee_number",
    "start_date_active",
    "end_date_active
  ];
  dataSource: MatTableDataSource<EmployeesData>;
  selection = new SelectionModel<EmployeesData>(true, []);

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(
    private EmployeeTableService: EmployeeTableService
  ) {}

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.data.forEach((row) => this.selection.select(row));
  }

  ngAfterViewInit() {
     this.retrieveEmployees();
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  retrieveSuppliers(): void {
    this.EmployeeTableService.getEmployees().subscribe(
      (data) => {
        this.dataSource = new MatTableDataSource(data);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        console.log("Data Successfully Retrived");
      },
      (error) => {
        console.log(error);
      }
    );
  }
}

HTML code

    <ng-container matColumnDef="select">

        <mat-checkbox (change)="$event ? masterToggle() : null"
                      [checked]="selection.hasValue() && isAllSelected()"
                      [indeterminate]="selection.hasValue() && !isAllSelected()">
        </mat-checkbox>

      <mat-checkbox (click)= "$event.stopPropagation()"
                     (change) = "$event ? selection.toggle(row) : null"
                     [checked]="selection.isSelected(row)">
      </mat-checkbox>

  </ng-container>

      <ng-container matColumnDef="Employee_name">
         Employee Name
         {{row.Employee_name}}
      </ng-container>

      <ng-container matColumnDef="Employee_number">
         Vendor Number
         {{row.Employee_number}}
      </ng-container>

      <ng-container matColumnDef="start_date_active">
         End Date Active
         {{row.start_date_active}}
      </ng-container>

      <ng-container matColumnDef="end_date_active">
         End Date Active
         {{row.end_date_active}}
      </ng-container>

Employers table Service

     import { Injectable } from '@angular/core';
     import { HttpClient } from '@angular/common/http';
     import { Observable } from 'rxjs';
     import { map, publishReplay, refCount } from 'rxjs/operators';

     import { environment } from '../../environments/environment';
     const baseUrl = environment.BACKEND_URL;

     export interface EmployersData {
     employee_name: string;
     employee_number: string;
     start_date_active: string;
     end_date_active: string;
        }

       @Injectable({
       providedIn: 'root'
        })

     export class EmployersTablesService {

     employersData: Observable<EmployersData[]>;

     constructor(private http: HttpClient) { }

      getEmployers() {
        if (!this.employersData) {
      this.employersData = this.http.get(`${baseUrl}/employers`).pipe(
          map((data:any) => data.data),
          publishReplay(1),
          refCount()
          );
       }
     return this.employersData;
       }

       }

Body:
I see that on each checking of an Employee we run masterToggle() and we store checked Employees using this.dataSource.data.forEach((row) => this.selection.select(row)); into selection.

I don't see class or interface for EmployeesData so I don't know exactly what it's data structure is like, so be ready to refactor a little bit. Also I don't know what EmployeeTableService does but we're going to use that as medium to share data. from ArchSuppliers -> EmployeeTableService -> EmployeeDetails.

Let's take Employee_number's from all selected items and send it to

masterToggle() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.data.forEach((row) => this.selection.select(row));
this.sendEmployeeNumbers();
  }

sendEmployeeNumbers() {
  let selectedEmployeeNumbers = [];
    for (let employee of this.selection) {
      selectedEmployeeNumbers.push(employee.Employee_number)
    }
 this.EmployeeTableService.selectedEmployeeNumbers.next(selectedEmployeeNumbers);
}

To your EmployeeTableService add an observer that receives an array of selectedEmployeeNumbers and emits this to all subscribers

selectedEmployeeNumbers = new ReplaySubject<number[]>(1);

And subscribe to that data on EmployeeDetails

this.selectedEmployeeNumbers$ = this.EmployeeTableService.selectedEmployeeNumbers.pipe(data => {return data;})


来源: stackexchange

问:
Separate "for" loop iterations
How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.

`public class SentenceMaker {

```<code>static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}

public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();

    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i++){
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence.);
    }
}
</code>```

}`

答:
I would start by moving everything into a single class, your code is needlessly complicated by the way you have organized it.

```<code>private static String[] article = { "the", "a", "one", "some", "any" };
private static String[] noun = { "boy", "girl", "dog", "town", "car" };
private static String[] verb = { "drove", "jumped", "ran", "walked", "skipped" };
private static String[] preposition = { "to", "from", "over", "under", "on" };
</code>```

Next, I would write a method to get the title case of a given word. You only need to capitalize the first character, but a StringBuilder is great for that.

```<code>private static String getTitleCase(String w) {
    StringBuilder sb = new StringBuilder(w);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    return sb.toString();
}
</code>```

Then building a sentence, I would move that to a method. You currently only get a single random index and build a single sentence. Instead, get a random value appropriate to each array length and I would use a StringJoiner to simplify adding the spaces between words. Like,

```<code>private static String buildSentence() {
    Random rand = ThreadLocalRandom.current();
    StringJoiner sj = new StringJoiner(" ");
    sj.add(getTitleCase(article[rand.nextInt(article.length)]));
    sj.add(noun[rand.nextInt(noun.length)]);
    sj.add(verb[rand.nextInt(verb.length)]);
    sj.add(preposition[rand.nextInt(preposition.length)]);
    sj.add(article[rand.nextInt(article.length)]);
    sj.add(noun[rand.nextInt(noun.length)]);
    return String.format("%s.", sj);
}
</code>```

Finally, call the above method twenty times

```<code>public static void main(String[] args) {
    for (int i = 0; i < 20; i++) {
        System.out.println(buildSentence());
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Separate "for" loop iterations

Body:
How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.

`public class SentenceMaker {

static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}

public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();

    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i++){
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence.);
    }
}

}`

Body:
I would start by moving everything into a single class, your code is needlessly complicated by the way you have organized it.

private static String[] article = { "the", "a", "one", "some", "any" };
private static String[] noun = { "boy", "girl", "dog", "town", "car" };
private static String[] verb = { "drove", "jumped", "ran", "walked", "skipped" };
private static String[] preposition = { "to", "from", "over", "under", "on" };

Next, I would write a method to get the title case of a given word. You only need to capitalize the first character, but a StringBuilder is great for that.

private static String getTitleCase(String w) {
    StringBuilder sb = new StringBuilder(w);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    return sb.toString();
}

Then building a sentence, I would move that to a method. You currently only get a single random index and build a single sentence. Instead, get a random value appropriate to each array length and I would use a StringJoiner to simplify adding the spaces between words. Like,

private static String buildSentence() {
    Random rand = ThreadLocalRandom.current();
    StringJoiner sj = new StringJoiner(" ");
    sj.add(getTitleCase(article[rand.nextInt(article.length)]));
    sj.add(noun[rand.nextInt(noun.length)]);
    sj.add(verb[rand.nextInt(verb.length)]);
    sj.add(preposition[rand.nextInt(preposition.length)]);
    sj.add(article[rand.nextInt(article.length)]);
    sj.add(noun[rand.nextInt(noun.length)]);
    return String.format("%s.", sj);
}

Finally, call the above method twenty times

public static void main(String[] args) {
    for (int i = 0; i < 20; i++) {
        System.out.println(buildSentence());
    }
}


问:
React native application start crash [ios]
Some ios version has app crash.

The app started and turned off after a few seconds.

Our tried ios version up then some ios phone solve this issues.

My Conjecture is firebase issue
this is my error report please help me

```<code>Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: TCC 0
This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSUserTrackingUsageDescription key with a string value explaining to the user how the app uses this data.

Triggered by Thread:  3

Application Specific Information:
CoreSimulator 783.5 - Device: iPhone 11 Pro (60FEA29F-5103-487C-B421-B5C031AB0D88) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 11 Pro
dyld4 config: DYLD_ROOT_PATH=/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 14.4.simruntime/Contents/Resources/RuntimeRoot

Kernel Triage:
VM - pmap_enter failed with resource shortage

Error Formulating Crash Report:
thread_get_state(PAGEIN) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(EXCEPTION) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(FLAVOR) returned 0x10000003: (ipc/send) invalid destination port
</code>```

答:
A significant change in iOS is that you must declare ahead of time any access to private data or your App will crash.

Once you link with iOS you must declare access to any user private data types. You do this by adding a usage key to your app’s Info.plist together with a purpose string. The list of frameworks that count as private data is a long one

Contacts, Calendar, Reminders, Photos, Bluetooth Sharing, Microphone, Camera, Location, Health, HomeKit, Media Library, Motion, CallKit, Speech Recognition, SiriKit, TV Provider.

You need to put the NSCameraUsageDescription in your plist.

```<code><key> NSCameraUsageDescription </key>
<string>$(PRODUCT_NAME) uses Cameras</string>
</code>```

Body:
Some ios version has app crash.

The app started and turned off after a few seconds.

Our tried ios version up then some ios phone solve this issues.

My Conjecture is firebase issue
this is my error report please help me

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: TCC 0
This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSUserTrackingUsageDescription key with a string value explaining to the user how the app uses this data.

Triggered by Thread:  3

Application Specific Information:
CoreSimulator 783.5 - Device: iPhone 11 Pro (60FEA29F-5103-487C-B421-B5C031AB0D88) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 11 Pro
dyld4 config: DYLD_ROOT_PATH=/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 14.4.simruntime/Contents/Resources/RuntimeRoot

Kernel Triage:
VM - pmap_enter failed with resource shortage

Error Formulating Crash Report:
thread_get_state(PAGEIN) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(EXCEPTION) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(FLAVOR) returned 0x10000003: (ipc/send) invalid destination port

Body:
A significant change in iOS is that you must declare ahead of time any access to private data or your App will crash.

Once you link with iOS you must declare access to any user private data types. You do this by adding a usage key to your app’s Info.plist together with a purpose string. The list of frameworks that count as private data is a long one

Contacts, Calendar, Reminders, Photos, Bluetooth Sharing, Microphone, Camera, Location, Health, HomeKit, Media Library, Motion, CallKit, Speech Recognition, SiriKit, TV Provider.

You need to put the NSCameraUsageDescription in your plist.

<key> NSCameraUsageDescription </key>
<string>$(PRODUCT_NAME) uses Cameras</string>


问:
Testing navigation with react-testing-library
I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made

```<code><ul>
  <li><Link to="/location1">location 1</Link></li>
  <li><Link to="/location2">location 2</Link></li>
</ul>
</code>```

this is my test

```<code>const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})
</code>```

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test? or any suggestions how should I test navigation?

答:
From the Checking location in tests doc:

You can also use BrowserRouter if your test environment has the browser globals window.location and window.history (which is the default in Jest through JSDOM, but you cannot reset the history between tests).

Instead of passing a custom route to MemoryRouter, you can use the base Router with a history prop from the history package

E.g.

index.tsx:

```<code>import React from 'react';
import { Link } from 'react-router-dom';

export function SideBar() {
  return (
    <ul>
      <li>
        <Link to="/location1">location 1</Link>
      </li>
      <li>
        <Link to="/location2">location 2</Link>
      </li>
    </ul>
  );
}
</code>```

index.test.tsx:

```<code>import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { createMemoryHistory } from 'history';
import { SideBar } from './';
import { Router } from 'react-router';

const createRouterWrapper = (history): React.ComponentType => ({ children }) => (
  <Router history={history}>{children}</Router>
);

describe('SideBar', () => {
  it('navigation to location 1', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 1'));
    expect(history.location.pathname).toBe('/location1');
  });

  it('navigation to location 2', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 2'));
    expect(history.location.pathname).toBe('/location2');
  });
});
</code>```

Test result:

 PASS  stackoverflow/70974339/index.test.tsx (8.701 s)
  SideBar
    ✓ navigation to location 1 (40 ms)
    ✓ navigation to location 2 (4 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |
 index.tsx |     100 |      100 |     100 |     100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.232 s
```

Body:
I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made

<Link to="/location1">location 1</Link>

<Link to="/location2">location 2</Link>

this is my test

const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test? or any suggestions how should I test navigation?

Body:
From the Checking location in tests doc:

You can also use BrowserRouter if your test environment has the browser globals window.location and window.history (which is the default in Jest through JSDOM, but you cannot reset the history between tests).

Instead of passing a custom route to MemoryRouter, you can use the base Router with a history prop from the history package

E.g.

index.tsx:

import React from 'react';
import { Link } from 'react-router-dom';

export function SideBar() {
  return (
    <ul>
      <li>
        <Link to="/location1">location 1</Link>
      </li>
      <li>
        <Link to="/location2">location 2</Link>
      </li>
    </ul>
  );
}

index.test.tsx:

import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { createMemoryHistory } from 'history';
import { SideBar } from './';
import { Router } from 'react-router';

const createRouterWrapper = (history): React.ComponentType => ({ children }) => (
  <Router history={history}>{children}</Router>
);

describe('SideBar', () => {
  it('navigation to location 1', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 1'));
    expect(history.location.pathname).toBe('/location1');
  });

  it('navigation to location 2', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 2'));
    expect(history.location.pathname).toBe('/location2');
  });
});

Test result:

 PASS  stackoverflow/70974339/index.test.tsx (8.701 s)
  SideBar
    ✓ navigation to location 1 (40 ms)
    ✓ navigation to location 2 (4 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |
 index.tsx |     100 |      100 |     100 |     100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.232 s


问:
Visual Studio Code Python Timeout waiting for debugger connection
I'm running the visual studio code tutorial with Python and am unable to connect to the debugger.  Google / SO are coming up empty when I search.  Usually I use Anaconda with Jupyter, so I'm connecting Visual Studio Code to the python in my activated 3.6 virtual environment. I tried pip installing ptvsd in my virtual environment, but that did not make a difference in what I am seeing.

I would welcome any suggestions.  Screenshots included below. launch.json in the bottom screenshot

答:
Changing your "integratedTerminal" shell to cmd.exe will fix it, because it's using "PowerShell".

Open a new terminal pane : Press Ctrl+` (or View > Terminal in menu)

Open a "Command Prompt"
Open a "Command Prompt"

Switch "cmd" to default (DO NOT switch to PowerShell)
Switch to default profile


问:
Is there a WEBGL Manual?
Is there some kind of WebGL manual that lists all the functions etc. ? I tried Google but found nothing.</p>

答:
There is also the official manual — the WebGL specification:

https://www.khronos.org/registry/webgl/specs/1.0/

ContentLicense: CC BY-SA 3.0

Title: Is there a WEBGL Manual?


问:
Creating a template for DataFlow throws the error AttributeError: 'RuntimeValueProvider' object has no attribute 'tableId'
I have made a pipeline with Apache Beam which runs successfully with the DataFlow runner. I'm trying to create a template, but when using a RuntimeValueProvider for the apache_beam.io.gcp.bigquery.WriteToBigQuery transformer, the following error is thrown:

AttributeError: 'RuntimeValueProvider' object has no attribute 'tableId'.

The code (excerpt) looks as follows:

```<code>class ProcessOptions(PipelineOptions):
    @classmethod
    def _add_argparse_args(cls, parser):
        parser.add_value_provider_argument(
            '--output_gcs',
            dest='output_gcs',
            default='gs://nlp-text-classification/results/stackoverflow_template',
            type=str,
            required=False,
            help='Google Cloud Storage Path.')

        parser.add_value_provider_argument(
            '--output_bq_table',
            dest='output_bq_table',
            default='nlp-text-classification:stackoverflow.template_test',
            type=str,
            required=False,
            help='BigQuery table.')

process_options = options.view_as(ProcessOptions)

with beam.Pipeline(options=options) as p:
    [...]
    "Write Posts to BigQuery" >> beam.io.WriteToBigQuery(table=process_options.output_bq_table,
                                                         schema=table_schema)
    [...]
</code>```

Is this a bug or am I doing something wrong?

答: Instead of 'Write To BigQuery' >> beam.io.Write(beam.io.BigQuerySink(..)) I used beam.io.WriteToBigQuery(..) and also used --experiment=use_beam_bq_sink which worked for me and I am not getting the below error anymore AttributeError: 'RuntimeValueProvider' object has no attribute 'datasetId</p>

Body:
I have made a pipeline with Apache Beam which runs successfully with the DataFlow runner. I'm trying to create a template, but when using a RuntimeValueProvider for the apache_beam.io.gcp.bigquery.WriteToBigQuery transformer, the following error is thrown:

AttributeError: 'RuntimeValueProvider' object has no attribute 'tableId'.

The code (excerpt) looks as follows:

class ProcessOptions(PipelineOptions):
    @classmethod
    def _add_argparse_args(cls, parser):
        parser.add_value_provider_argument(
            '--output_gcs',
            dest='output_gcs',
            default='gs://nlp-text-classification/results/stackoverflow_template',
            type=str,
            required=False,
            help='Google Cloud Storage Path.')

        parser.add_value_provider_argument(
            '--output_bq_table',
            dest='output_bq_table',
            default='nlp-text-classification:stackoverflow.template_test',
            type=str,
            required=False,
            help='BigQuery table.')

process_options = options.view_as(ProcessOptions)

with beam.Pipeline(options=options) as p:
    [...]
    "Write Posts to BigQuery" >> beam.io.WriteToBigQuery(table=process_options.output_bq_table,
                                                         schema=table_schema)
    [...]

Is this a bug or am I doing something wrong?


问:
How to round robin by UUID in SQL database?
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query
```

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)

答:
I don't have PostgreSQL handy right now, but this works under SQL Server and I don't see an obvious reason why it shouldn't under any other DBMS:

```<code>COALESCE(
    (SELECT TOP 1 id FROM agents WHERE @current_id < id ORDER BY id),
    (SELECT TOP 1 id FROM agents ORDER BY id)
)
</code>```

So it simply tries to get the next id (the first argument of COALESCE), and if there is no next id gets the first id (the second argument of COALESCE).

Here is a full T-SQL demo, something similar can probably be done under PostgreSQL...

```<code>CREATE TABLE agents  (
    id uniqueidentifier PRIMARY KEY
);

INSERT INTO agents VALUES (NEWID()), (NEWID()), (NEWID()), (NEWID());

DECLARE @current_id uniqueidentifier;

DECLARE @i int = 0;
WHILE @i < 10 BEGIN

    SET @current_id = COALESCE(
        (SELECT TOP 1 id FROM agents WHERE @current_id < id ORDER BY id),
        (SELECT TOP 1 id FROM agents ORDER BY id)
    );

    PRINT CONCAT('@current_id = ', @current_id);

    SET @i = @i + 1;

END
</code>```

Body:
I have a list of agents that I want to assign tasks to using round robin.

agents table:

id

uuid1

uuid2

uuid3

uuid4

How to get rows of the table above in a round robin fashion?

Desired outcome:

uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat)

I tried ordering uuids then selecting the next one based on the previous uuid

SELECT id FROM agents ORDER BY id; // When there is no previous

SELECT id FROM agents WHERE id > 'uuid1' ORDER BY id; // After the first query

But I don't know how to repeat when I reach the last uuid (when uuid4 is retrieved and uuid1 must be selected again)

Body:
I don't have PostgreSQL handy right now, but this works under SQL Server and I don't see an obvious reason why it shouldn't under any other DBMS:

COALESCE(
    (SELECT TOP 1 id FROM agents WHERE @current_id < id ORDER BY id),
    (SELECT TOP 1 id FROM agents ORDER BY id)
)

So it simply tries to get the next id (the first argument of COALESCE), and if there is no next id gets the first id (the second argument of COALESCE).

Here is a full T-SQL demo, something similar can probably be done under PostgreSQL...

CREATE TABLE agents  (
    id uniqueidentifier PRIMARY KEY
);

INSERT INTO agents VALUES (NEWID()), (NEWID()), (NEWID()), (NEWID());

DECLARE @current_id uniqueidentifier;

DECLARE @i int = 0;
WHILE @i < 10 BEGIN

    SET @current_id = COALESCE(
        (SELECT TOP 1 id FROM agents WHERE @current_id < id ORDER BY id),
        (SELECT TOP 1 id FROM agents ORDER BY id)
    );

    PRINT CONCAT('@current_id = ', @current_id);

    SET @i = @i + 1;

END


问:
AnyLogic Resource Pool
I am modelling a machine that can process two different products. The ratio of space needed per product is 0.75:1 i.e. product A requires 75% of the spot required for product B. I wanted to draw from the resource pool using float values. That is each time product B is passed it draws one whole unit from the pool while if product A is passed then it should seize only 0.75 units. However it seems the resource pool can only take integer values. Is there any world around for this? Note that the machine is such that it can process both products at the same time.</p>

答:
Since resource pools are made up of agents and you can't seize part of an agent the best option I can think of is to multiply the number of resources you have by 100 and then let the products seize 100x of what they normally would.

So if you currently had 10 units in the resource pool and products tried to seize 0.75 and 1 you will now have 1000 units in the resource pool and the products seize 75 and 100 units.

This should be a very simple workaround

Title: AnyLogic Resource Pool


问:
Javascript question: How to update Google Analytics code in LightBox Slideshow 1.1
I am using Lightbox Slideshow 1.1 (www.justinbarkhuff.com/lab/lightbox_slideshow) on my site which uses javascript to display photos in a modal window and it has a Google Analytics option built-in to its javascript file, but it uses the old urchintracker code.  I'm very unfamiliar with modifying javascript.  I was wondering if anyone could help me transform this code from the old urchintracker to the new Asynchronous code. More info on migrating to that new code can be found here - http://code.google.com/apis/analytics/docs/tracking/asyncMigrationExamples.html

The code in the lightbox.js file in question is:

```<code>if(this.options.googleAnalytics){
    urchinTracker(this.imageArray[this.activeImage].link);
}
</code>```

With "(this.imageArray[this.activeImage].link)" being the variable which passes the path and filename of  the image currently being viewed (i.e. "p/image1.jpg") to Google Analytics.  This works great and my Google Analytics is receiving data fine, but I need to convert to the latest Asynchronous code.

I want to convert to an Event tracker in the new code, so instead of the script just sending urchinTracker('p/image1.jpg'); I would need it to be instead:

```<code>_gaq.push(['_trackEvent', 'Photos', 'View', 'currentimage.jpg']);
</code>```

(Where "currentimage.jpg" is the value passed by "(this.imageArray[this.activeImage].link);" in the lightbox.js file.

("_gaq.push" is the new "urchintracker")

To view the lightbox.js file, go to: http://www.justinbarkhuff.com/lab/lightbox_slideshow/lightbox.js and search for "urchintracker".

If anyone who knows Javascript could help me transform this above code so I can use the latest code for Google Analytics, I'd really appreciate it.  Or if you could point me in the right direction.  Thanks in advance.

I wonder..
could it be as simple as this?

```<code>if(this.options.googleAnalytics){
    _gaq.push(['_trackEvent', 'Photos', 'View', this.imageArray[this.activeImage].link]);
}
</code>```

What about the ' symbols around this.imageArray[this.activeImage].link?  Will the script automatically pass them on without me adding them to the code?

Thanks in advance for any and all help!

答: Yes. Your code is perfectly well adopted. Try it out; assuming it was working before, it should work now. </p>

Body:
I am using Lightbox Slideshow 1.1 (www.justinbarkhuff.com/lab/lightbox_slideshow) on my site which uses javascript to display photos in a modal window and it has a Google Analytics option built-in to its javascript file, but it uses the old urchintracker code.  I'm very unfamiliar with modifying javascript.  I was wondering if anyone could help me transform this code from the old urchintracker to the new Asynchronous code. More info on migrating to that new code can be found here - http://code.google.com/apis/analytics/docs/tracking/asyncMigrationExamples.html

The code in the lightbox.js file in question is:

if(this.options.googleAnalytics){
    urchinTracker(this.imageArray[this.activeImage].link);
}

With "(this.imageArray[this.activeImage].link)" being the variable which passes the path and filename of  the image currently being viewed (i.e. "p/image1.jpg") to Google Analytics.  This works great and my Google Analytics is receiving data fine, but I need to convert to the latest Asynchronous code.

I want to convert to an Event tracker in the new code, so instead of the script just sending urchinTracker('p/image1.jpg'); I would need it to be instead:

_gaq.push(['_trackEvent', 'Photos', 'View', 'currentimage.jpg']);

(Where "currentimage.jpg" is the value passed by "(this.imageArray[this.activeImage].link);" in the lightbox.js file.

("_gaq.push" is the new "urchintracker")

To view the lightbox.js file, go to: http://www.justinbarkhuff.com/lab/lightbox_slideshow/lightbox.js and search for "urchintracker".

If anyone who knows Javascript could help me transform this above code so I can use the latest code for Google Analytics, I'd really appreciate it.  Or if you could point me in the right direction.  Thanks in advance.

I wonder..
could it be as simple as this?

if(this.options.googleAnalytics){
    _gaq.push(['_trackEvent', 'Photos', 'View', this.imageArray[this.activeImage].link]);
}

What about the ' symbols around this.imageArray[this.activeImage].link?  Will the script automatically pass them on without me adding them to the code?

Thanks in advance for any and all help!


问:
AWK how to check if first column contains an ip address
I have a file that contains a list of DHCP bindings. I want to extract some of the data, however its not as straight forward as it first appeared it would be, often the hardware identifier is across multiple lines.

You can see those in the second column, they have a period at the end when they continue onto the next line.

So to sum up what I want to achieve here. Extract column 1 and 2 where there is an IP address and just column 2 where there is none, the end result being the IP and full hardware address on a single line.

The goal being to make it faster to get the hardware identifier, currently if I want to assign a static IP I have to perform up to three copy/pastes, not a big deal I know, but I would still like to be able to do it in one copy.

Data example:

```<code>10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.1146.a45b.6916.
                    7ae3.be
10.x.x.x            ff29.ed05.1200.0100.    Infinite                Manual
                    0128.c2e3.9300.0c29.
                    ed05.12
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11e7.d0ba.2f43.
                    f135.f2
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11b2.f37a.8a39.
                    e6bf.93
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.115c.5da2.eecf.
                    09d7.41
10.x.x.x            000c.29a0.40a3          Feb 07 2022 05:44 PM    Automatic
10.x.x.x            01e8.3935.e98c.14       Infinite                Manual
10.x.x.x            0168.b599.bed2.94       Infinite                Manual
10.x.x.x            01d0.67e5.0530.ef       Feb 07 2022 11:54 PM    Automatic
10.x.x.x            ff29.a040.a300.0100.    Infinite                Manual
                    0129.88be.c700.0c29.
                    a040.a3
</code>```

The following code I have managed to put together looking around for a solution. Searches like "awk if column 1 = ip address" came back with the regex, I am not even sure that I am using it correctly.

```<code>awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        ip="\n$1"
        addr=$2
    } else {
        addr="$1"
    }
    printf "%s %s",ip,addr;
}' data.txt
</code>```

I am aware I need some way to combine the addr variable too, I can work on that later, just getting the columns correctly would be a massive help. (Think I sorted the combining part, adjusted the code to the following, removing the variables.)

```<code>awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        printf "\nIP Address: %s", $1
        printf $2
    } else {
        printf $1
    }
}' data.txt
</code>```

So, if I can get help with how to check if the first column contains an IP address I should be there.

Body:
I have a file that contains a list of DHCP bindings. I want to extract some of the data, however its not as straight forward as it first appeared it would be, often the hardware identifier is across multiple lines.

You can see those in the second column, they have a period at the end when they continue onto the next line.

So to sum up what I want to achieve here. Extract column 1 and 2 where there is an IP address and just column 2 where there is none, the end result being the IP and full hardware address on a single line.

The goal being to make it faster to get the hardware identifier, currently if I want to assign a static IP I have to perform up to three copy/pastes, not a big deal I know, but I would still like to be able to do it in one copy.

Data example:

10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.1146.a45b.6916.
                    7ae3.be
10.x.x.x            ff29.ed05.1200.0100.    Infinite                Manual
                    0128.c2e3.9300.0c29.
                    ed05.12
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11e7.d0ba.2f43.
                    f135.f2
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.11b2.f37a.8a39.
                    e6bf.93
10.x.x.x            ff9f.6e85.2400.0200.    Infinite                Manual
                    00ab.115c.5da2.eecf.
                    09d7.41
10.x.x.x            000c.29a0.40a3          Feb 07 2022 05:44 PM    Automatic
10.x.x.x            01e8.3935.e98c.14       Infinite                Manual
10.x.x.x            0168.b599.bed2.94       Infinite                Manual
10.x.x.x            01d0.67e5.0530.ef       Feb 07 2022 11:54 PM    Automatic
10.x.x.x            ff29.a040.a300.0100.    Infinite                Manual
                    0129.88be.c700.0c29.
                    a040.a3

The following code I have managed to put together looking around for a solution. Searches like "awk if column 1 = ip address" came back with the regex, I am not even sure that I am using it correctly.

awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        ip="\n$1"
        addr=$2
    } else {
        addr="$1"
    }
    printf "%s %s",ip,addr;
}' data.txt

I am aware I need some way to combine the addr variable too, I can work on that later, just getting the columns correctly would be a massive help. (Think I sorted the combining part, adjusted the code to the following, removing the variables.)

awk '{
    if ($1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/) {
        printf "\nIP Address: %s", $1
        printf $2
    } else {
        printf $1
    }
}' data.txt

So, if I can get help with how to check if the first column contains an IP address I should be there.

Body:
It seems like the task here is to reformat a table.

awk '
l && /^[^[:space:]]/ {print l; l=""}
/^[^[:space:]]/ {l = "IP Address: "$1" "$2; next}
l {l = l$1}
END {if (l) {print l}}'

Prints:

IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.1146.a45b.6916.7ae3.be
IP Address: 10.x.x.x ff29.ed05.1200.0100.0128.c2e3.9300.0c29.ed05.12
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11e7.d0ba.2f43.f135.f2
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.11b2.f37a.8a39.e6bf.93
IP Address: 10.x.x.x ff9f.6e85.2400.0200.00ab.115c.5da2.eecf.09d7.41
IP Address: 10.x.x.x 000c.29a0.40a3
IP Address: 10.x.x.x 01e8.3935.e98c.14
IP Address: 10.x.x.x 0168.b599.bed2.94
IP Address: 10.x.x.x 01d0.67e5.0530.ef
IP Address: 10.x.x.x ff29.a040.a300.0100.0129.88be.c700.0c29.a040.a3

This works by checking if a line begins with a space (padding) or not (IP Address).


问:
How to verify domain ownership via text record check? (like flippa, godaddy, etc)
I'm looking to start a domain name marketplace for niche domains and need to verify domain ownership when people submit their domains for sale on the site. Similar to the process like Flippa or Godaddy domain auctions, where they give user a domain txt record value to add to their DNS and then they check to make sure the person owns the domain before making the listing active on the marketplace.

Would appreciate if anyone knows how to check a domain txt records to make sure the domain owner has added the txt record. For example, we ask them to submit new txt record "xyz123xyz123xyz123blahblah" and then we can check to make sure they have added the txt record to their domain records.

Sorry, not familiar with txt records and if there is a certain format that is required. Any info on that would be greatly appreciated. Thank you for any help on this!

答:
You can easily check with dig example.com txt on Linux. Most languages should be able to query this. There should be libraries/packages for it as well, so this shouldn't be a problem for your application.

TXT value is just a string, so you can put anything you wish. Official format for the string is with attributes and their values: verification=qwerty123. Most DNS servers have a limitation on the size of the string, so you can't put a huge value in it.

More about TXT: https://www.cloudflare.com/learning/dns/dns-records/dns-txt-record/


问:
Multiple definition of ... linker error
I defined a special file: config.h

My project also has files:

```<code>t.c, t.h
pp.c, pp.h
b.c b.h
l.cpp
</code>```

and #includes:

in t.c:

```<code>    #include "t.h"
    #include "b.h"
    #include "pp.h"
    #include "config.h"
</code>```

in b.c:

```<code>    #include "b.h"
    #include "pp.h"
</code>```

in pp.c:

```<code>    #include "pp.h"
    #include "config.h"
</code>```

in l.cpp:

```<code>    #include "pp.h"
    #include "t.h"
    #include "config.h"
</code>```

there are no include directives in my *.h files, only in *.c files. I defined this in config.h:

```<code>const char *names[i] =
        {
            "brian", "stefan", "steve"
        };
</code>```

and need that array in l.cpp, t.c, pp.c but Im getting this error:

```<code>pp.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
t.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [link] Error 1
</code>```

I have include guards in every *.h file I use in my project. Any help solving this?

答: Make your definitions static in the header files.</p>

Title: Multiple definition of ... linker error

Body:
I defined a special file: config.h

My project also has files:

t.c, t.h
pp.c, pp.h
b.c b.h
l.cpp

and #includes:

in t.c:

    #include "t.h"
    #include "b.h"
    #include "pp.h"
    #include "config.h"

in b.c:

    #include "b.h"
    #include "pp.h"

in pp.c:

    #include "pp.h"
    #include "config.h"

in l.cpp:

    #include "pp.h"
    #include "t.h"
    #include "config.h"

there are no include directives in my *.h files, only in *.c files. I defined this in config.h:

const char *names[i] =
        {
            "brian", "stefan", "steve"
        };

and need that array in l.cpp, t.c, pp.c but Im getting this error:

pp.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
t.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [link] Error 1

I have include guards in every *.h file I use in my project. Any help solving this?


问:
All buildscript {} blocks must appear before any plugins {} blocks in the script in Jitpack
I am trying to publish my android library with jitpack. But getting buildscript {} blocks must appear before any plugins {} blocks error.
I have already referred to this question : Getting 'buildscript {} blocks must appear before any plugins {} blocks' error in jitpack but did not found any solution.

Error:

```<code>FAILURE: Build failed with an exception.

* Where:
Build file '/home/jitpack/build/build.gradle' line: 26

* What went wrong:
Could not compile build file '/home/jitpack/build/build.gradle'.
> startup failed:
  build file '/home/jitpack/build/build.gradle': 26: all buildscript {} blocks must appear before any plugins {} blocks in the script

  See https://docs.gradle.org/7.0.2/userguide/plugins.html#sec:plugins_block for information on the plugins {} block

   @ line 26, column 1.
     buildscript {
     ^

  1 error
</code>```

This is what my project level gradle looks like:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"

        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

plugins {
    id "com.jfrog.bintray" version "1.8.4"
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

This is what my app level gradle looks like:

```<code>plugins {
    id 'com.android.application'
    id "com.jfrog.bintray"
}

android {
    compileSdk 30

    defaultConfig {
        applicationId "com.siddydevelops.logutil"
        minSdk 23
        targetSdk 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

</code>```

My gradle version is 7.0.2.

I am pretty sure that this block is causing the error: (in project level gradle)

```<code>plugins {
    id "com.jfrog.bintray" version "1.8.4"
}
</code>```

I cant move it to app level gradle.

答:
i have the same problem too, i just change the position inside build.gradle project like this:</p>
```<code>buildscript {
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"

    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Body:
I am trying to publish my android library with jitpack. But getting buildscript {} blocks must appear before any plugins {} blocks error.
I have already referred to this question : Getting 'buildscript {} blocks must appear before any plugins {} blocks' error in jitpack but did not found any solution.

Error:

FAILURE: Build failed with an exception.

* Where:
Build file '/home/jitpack/build/build.gradle' line: 26

* What went wrong:
Could not compile build file '/home/jitpack/build/build.gradle'.
> startup failed:
  build file '/home/jitpack/build/build.gradle': 26: all buildscript {} blocks must appear before any plugins {} blocks in the script

  See https://docs.gradle.org/7.0.2/userguide/plugins.html#sec:plugins_block for information on the plugins {} block

   @ line 26, column 1.
     buildscript {
     ^

  1 error

This is what my project level gradle looks like:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.2"

        classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

plugins {
    id "com.jfrog.bintray" version "1.8.4"
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is what my app level gradle looks like:

plugins {
    id 'com.android.application'
    id "com.jfrog.bintray"
}

android {
    compileSdk 30

    defaultConfig {
        applicationId "com.siddydevelops.logutil"
        minSdk 23
        targetSdk 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

My gradle version is 7.0.2.

I am pretty sure that this block is causing the error: (in project level gradle)

plugins {
    id "com.jfrog.bintray" version "1.8.4"
}

I cant move it to app level gradle.

Body:
i have the same problem too, i just change the position inside build.gradle project like this:

buildscript {
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"

    }
}

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Why aren't my git logs logged in git and github?
I did commit and push in terminal,
I checked that the file was properly uploaded to Github.

However, it was recorded as no contribution in Github, and my commit was not recorded in the Git log.

How do I solve this problem?

Thanks in advance for your reply.

p.s.
I'm not familiar with the question, so the information is a bit lacking. I'm sorry.

答:
Sorry everyone,
I have very little knowledge of git.

I proceeded with git commit while looking for old codes,
In the past, the default branch was all master, so
All the codes I saw were explained to commit to the master branch.

But now, since the main branch is the default branch, it seems that the codes I uploaded to the master branch were not displayed on the dashboard.

Sorry to confuse everyone.
Thank you.


问:
Algorithm for Minimising Sum of Distance of agents to visiting targets
I'm working on implementing a model in Python. As part of this model, I have a set of agents (e.g. humans) that need to visit a set of targets (e.g. places). Each agent has its own initial location (i.e. starting point) and I can calculate the distance from each agent to each target.

What I need at this point is to allocate a first job to each agent in a way that the sum of all travel distances for agents from their starting location to their first job is minimum.

I considered greedy algorithm, but I found examples that proves order of allocation can lead to non-optimal solutions. I also looked into nearest neighbour algorithm in TSP, but all I could find was for one agent (or salesman) not multiple.

Could someone point me to any (non-exhaustive search) algorithm/approach that could be used for this purpose please? Thanks

答:
If the number of agents = number of targets, we end up with a standard assignment problem. This can be solved in different ways:

as an LP (linear programming problem). Technically a MIP but variables are automatically integer-valued, so an LP solver suffices.

as a network problem

or using specialized algorithms.

If, say, the number of locations > number of agents, we still can use an LP/MIP:

```<code> min sum((i,j), d(i,j)*x(i,j))
 sum(j, x(i,j)) = 1  for all agents i  (each agent should be assigned to exactly one location)
 sum(i, x(i,j)) <= 1  for all locations j (each location should be assigned to at most one agent)
 x(i,j) in {0,1}
</code>```

For the network approach, we would need to add some dummy nodes.

All these methods are quite fast (this is an easy model). To give you an indication: I solved a random example with 500 agents and 1000 locations as an LP and it took 0.3 seconds.

Body:
If the number of agents = number of targets, we end up with a standard assignment problem. This can be solved in different ways:

as an LP (linear programming problem). Technically a MIP but variables are automatically integer-valued, so an LP solver suffices.

as a network problem

or using specialized algorithms.

If, say, the number of locations > number of agents, we still can use an LP/MIP:

 min sum((i,j), d(i,j)*x(i,j))
 sum(j, x(i,j)) = 1  for all agents i  (each agent should be assigned to exactly one location)
 sum(i, x(i,j)) <= 1  for all locations j (each location should be assigned to at most one agent)
 x(i,j) in {0,1}

For the network approach, we would need to add some dummy nodes.

All these methods are quite fast (this is an easy model). To give you an indication: I solved a random example with 500 agents and 1000 locations as an LP and it took 0.3 seconds.


问:
How to use Microsoft.Win32.Registry.OpenSubKey to go directly to a particular key?
Now this is a simple question. It should be clearly documented in MSDN. I looked but I couldn't find it. The only thing I got was that I had to open subkey after subkey after subkey to get to the particular key I'm interested in.

Surely there is a more direct method to access a key 3 levels deep. What is it?

I've already tried

```<code>RegistryKey reg = Registry.LocalMachine;
reg.OpenSubKey(@"Software\Microsoft", true);  // reg is still HKLM !
</code>```

and

```<code>reg.OpenSubKey(@"Software\Microsoft\", true); // reg is still HKLM !
</code>```

答:
Sure just put your full path of that key, example:</p>

```<code>Registry.CurrentUser.OpenSubKey("the registry full path");
</code>```

Body:
Now this is a simple question. It should be clearly documented in MSDN. I looked but I couldn't find it. The only thing I got was that I had to open subkey after subkey after subkey to get to the particular key I'm interested in.

Surely there is a more direct method to access a key 3 levels deep. What is it?

I've already tried

RegistryKey reg = Registry.LocalMachine;
reg.OpenSubKey(@"Software\Microsoft", true);  // reg is still HKLM !

and

reg.OpenSubKey(@"Software\Microsoft\", true); // reg is still HKLM !

Body:
Sure just put your full path of that key, example:

Registry.CurrentUser.OpenSubKey("the registry full path");


问:
Custom edit and delete components on row DataGrid MUI v5 component hovered
I'm using Material UI or MUI v5 components for the UI library in my React Js app.

I'm creating a custom edit and delete row inside the DataGrid/DataGridPro component.

The specification is to show edit and delete icons for the hovered row but not by adding a new column (not adding an action column). I found the example for a private dashboard here.

So if the user decreases the width of the browser, the edit and delete icons wouldn't be hidden instead it would hide the row as seen in the image below.

I made it here https://codesandbox.io/s/learn-mui-data-grid-hover-row-367vh?file=/demo.js but I found some drawbacks below:

1. The Popper component is rendered on top of the DataGrid component

When our mouse cursor hovered the row that was not fully shown, the Popper component was shown like these images below.

I've tried to add the disablePortal={true} prop to the Popper component but it would make the Popper component rendered outside the row like this image below.

I also have tried to change the zIndex prop for the column header (became 1000), the row (became 10), and the pagination container (became 1000) of the DataGrid component also changed the zIndex prop of the Popper component (became 100) but still the Popper component was rendered on top of the DataGrid component like this image below.

Question 1: What should I do to make the Popper component rendered on the top of the row but still inside the DataGrid component like this image below?

2. The Popper component was not sticking to the DataGrid component

If I add a few new columns, the Popper component was sticking on the end of the row like this image below. This was the condition I want.

If we scroll our mouse to the start of the row, the Popper component was not sticking to the end of the row like this image below. This was not the condition I want.

Question 2: What should I do to make the Popper component stick to the end of the row regardless of scrolling horizontally our mouse like this image below?

Here is the demo https://codesandbox.io/s/learn-mui-data-grid-hover-row-367vh?file=/Demo2.jsx

Or is there any better way to achieve this case?

答:
Finally, I could make it after learning about these features:

column pinning feature https://mui.com/components/data-grid/columns/#column-pinning to create the edit and delete icons container

componentsProps https://mui.com/components/data-grid/components/#row to control which row is hovered

Here are the steps:

use componentsProps to control which row is hovered

componentsProps={{
  row: {
    onMouseEnter: onMouseEnterRow,
    onMouseLeave: onMouseLeaveRow
  }
}}
```
<ol start="2">
<li>add <code>actions</code> column and only show the edit and delete icons when the row is hovered</li>
</ol>
<pre class="lang-js prettyprint-override"><code>{
  field: "actions",
  headerName: "",
  width: 120,
  sortable: false,
  disableColumnMenu: true,
  renderCell: (params) => {
    if (hoveredRow === params.id) {
      return (
        <Box
          sx={{
            backgroundColor: "whitesmoke",
            width: "100%",
            height: "100%",
            display: "flex",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <IconButton onClick={() => console.log(params.id)}>
            <EditIcon />
          </IconButton>
          <IconButton onClick={() => console.log(params.id)}>
            <DeleteIcon />
          </IconButton>
        </Box>
      );
    } else return null;
  }
}
</code>```

pin the actions column and change the DataGrid styles

<DataGridPro
  // some code here ...
  initialState={{ pinnedColumns: { right: ["actions"] } }}
  sx={{
    "& .MuiDataGrid-iconSeparator": {
      display: "none"
    },
    "& .MuiDataGrid-pinnedColumnHeaders": {
      boxShadow: "none",
      backgroundColor: "transparent"
    },
    "& .MuiDataGrid-pinnedColumns": {
      boxShadow: "none",
      backgroundColor: "transparent",
      "& .MuiDataGrid-cell": {
        padding: 0
      }
    },
    "& .MuiDataGrid-row": {
      cursor: "pointer",
      "&:hover": {
        backgroundColor: "whitesmoke"
      },
      "&:first-child": {
        borderTop: "1px solid rgba(224, 224, 224, 1)"
      }
    },
    "& .MuiDataGrid-cell:focus": {
      outline: "none"
    },
    "& .MuiDataGrid-cell:focus-within": {
      outline: "none"
    }
  }}
/>
```

Here is the demo https://codesandbox.io/s/learn-mui-data-grid-column-pinning-gzgn0?file=/demo.js

Body:
Finally, I could make it after learning about these features:

column pinning feature https://mui.com/components/data-grid/columns/#column-pinning to create the edit and delete icons container

componentsProps https://mui.com/components/data-grid/components/#row to control which row is hovered

Here are the steps:

use componentsProps to control which row is hovered

componentsProps={{
  row: {
    onMouseEnter: onMouseEnterRow,
    onMouseLeave: onMouseLeaveRow
  }
}}

add actions column and only show the edit and delete icons when the row is hovered

{
  field: "actions",
  headerName: "",
  width: 120,
  sortable: false,
  disableColumnMenu: true,
  renderCell: (params) => {
    if (hoveredRow === params.id) {
      return (
        <Box
          sx={{
            backgroundColor: "whitesmoke",
            width: "100%",
            height: "100%",
            display: "flex",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <IconButton onClick={() => console.log(params.id)}>
            <EditIcon />
          </IconButton>
          <IconButton onClick={() => console.log(params.id)}>
            <DeleteIcon />
          </IconButton>
        </Box>
      );
    } else return null;
  }
}

pin the actions column and change the DataGrid styles

<DataGridPro
  // some code here ...
  initialState={{ pinnedColumns: { right: ["actions"] } }}
  sx={{
    "& .MuiDataGrid-iconSeparator": {
      display: "none"
    },
    "& .MuiDataGrid-pinnedColumnHeaders": {
      boxShadow: "none",
      backgroundColor: "transparent"
    },
    "& .MuiDataGrid-pinnedColumns": {
      boxShadow: "none",
      backgroundColor: "transparent",
      "& .MuiDataGrid-cell": {
        padding: 0
      }
    },
    "& .MuiDataGrid-row": {
      cursor: "pointer",
      "&:hover": {
        backgroundColor: "whitesmoke"
      },
      "&:first-child": {
        borderTop: "1px solid rgba(224, 224, 224, 1)"
      }
    },
    "& .MuiDataGrid-cell:focus": {
      outline: "none"
    },
    "& .MuiDataGrid-cell:focus-within": {
      outline: "none"
    }
  }}
/>

Here is the demo https://codesandbox.io/s/learn-mui-data-grid-column-pinning-gzgn0?file=/demo.js


问:
AWS Codebuild Ruby 2.6.5 runtime missing on Amazon Linux Standard 3.0 image
I have a ruby project and I am trying to build via AWS codedeploy and having some issues specifying the ruby version. I am using Ruby 2.6.5 and I am using AWS Codedeploy standard image (aws/codebuild/standard:2.0) because according to the docs it supports Ruby 2.6.5. .ruby-version has 2.6.5. I also attempted a build where I put "runtime-versions: ruby: 2.6.5" in the buildspec but that threw the following error: "Phase context status code: YAML_FILE_ERROR Message: Unknown runtime version named '2.6.5' of ruby. This build image has the following versions: 2.6". This is my buildspec.

```<code>version: 0.2
phases:
  install:
    runtime-versions:
      ruby: 2.6.5
    commands:
      - echo Installing Bundler...
      - gem install bundler -v 2.2.27
      - bundle install
  build:
    commands:
       - bundle exec rspec
</code>```

I also tried using aws/codebuild/amazonlinux2-x86_64-standard:3.0-20.03.13 image version from AL Standard 3.0 image instead of the latest but I get the same error while on github I see ruby version 2.6.5 has been added https://github.com/aws/aws-codebuild-docker-images/tree/20.03.13.
I also tried Ubuntu Standard 5.0 and same thing.
What am I missing?

答:
I was in a similar situation like this and I couldn't find any other solution than installing the required version inside buildspec file

```<code>version: 0.2

phases:
  install:
    runtime-versions:
      ruby: 2.6
    commands:
      - echo Installing app dependencies...
      - rbenv install 2.6.5 && rbenv global 2.6.5
      - bundle install
</code>```

This might increase your build time, since it has to pull the required version

Body:
I have a ruby project and I am trying to build via AWS codedeploy and having some issues specifying the ruby version. I am using Ruby 2.6.5 and I am using AWS Codedeploy standard image (aws/codebuild/standard:2.0) because according to the docs it supports Ruby 2.6.5. .ruby-version has 2.6.5. I also attempted a build where I put "runtime-versions: ruby: 2.6.5" in the buildspec but that threw the following error: "Phase context status code: YAML_FILE_ERROR Message: Unknown runtime version named '2.6.5' of ruby. This build image has the following versions: 2.6". This is my buildspec.

version: 0.2
phases:
  install:
    runtime-versions:
      ruby: 2.6.5
    commands:
      - echo Installing Bundler...
      - gem install bundler -v 2.2.27
      - bundle install
  build:
    commands:
       - bundle exec rspec

I also tried using aws/codebuild/amazonlinux2-x86_64-standard:3.0-20.03.13 image version from AL Standard 3.0 image instead of the latest but I get the same error while on github I see ruby version 2.6.5 has been added https://github.com/aws/aws-codebuild-docker-images/tree/20.03.13.
I also tried Ubuntu Standard 5.0 and same thing.
What am I missing?

Body:
I was in a similar situation like this and I couldn't find any other solution than installing the required version inside buildspec file

version: 0.2

phases:
  install:
    runtime-versions:
      ruby: 2.6
    commands:
      - echo Installing app dependencies...
      - rbenv install 2.6.5 && rbenv global 2.6.5
      - bundle install

This might increase your build time, since it has to pull the required version


问:
How to use a map() function to show a list of elements in React with Redux Saga
I was trying to use React with Redux Saga.

The code that I use can be found here:

https://codesandbox.io/s/redux-toolkit-saga-stoic-euler-cjhgx-forked-udh3r?file=/src/App.js

When I use the code with the url below:

https://jsonplaceholder.typicode.com/todos/1

the code works for me

but I wanna use it with this url

https://jsonplaceholder.typicode.com/todos

This way I can get the list of all values

I use this code to show the information from the user/todo list

```<code>{user.title}
</code>```

And it works for me

But I was not able to get the list of all values to be displayed in the app.

I try to use the code below

```<code>{user.map((parameter) => <p>1</p>)}
</code>```

It says that map() is not a function.

How can I fix this?

答:
You are setting user as an object by doing setUser({...data}), Array.prototype.map can only be used for array.

Since response data is an array, you can directly set it as setUser(data)

user.js

```<code> export function* handleGetUser(action) {
      try {
        const response = yield call(requestGetUser);
        const { data } = response; //data is an Array
        console.log('data',data);
        yield put(setUser(data));
      } catch (error) {
        console.log(error);
      }
    }
</code>```

userSlice.js

```<code>const userSlice = createSlice({
  name: "user",
  initialState: {},
  reducers: {
    getUser() {},
    setUser(state, action) {
      const userData = action.payload; //setting userData (Array) as data
      return { ...state, data:userData };
    }
  }
});
</code>```

App

```<code>return (
    <div className="App">
      {user.data.length}
      {user.data?.map((obj) => <h1 key = {obj.id}>{obj.id}.{obj.title}</h1>)}
    </div>
  );
</code>```

Body:
I was trying to use React with Redux Saga.

The code that I use can be found here:

https://codesandbox.io/s/redux-toolkit-saga-stoic-euler-cjhgx-forked-udh3r?file=/src/App.js

When I use the code with the url below:

https://jsonplaceholder.typicode.com/todos/1

the code works for me

but I wanna use it with this url

https://jsonplaceholder.typicode.com/todos

This way I can get the list of all values

I use this code to show the information from the user/todo list

{user.title}

And it works for me

But I was not able to get the list of all values to be displayed in the app.

I try to use the code below

{user.map((parameter) =>
1
)}

It says that map() is not a function.

How can I fix this?

Body:
You are setting user as an object by doing setUser({...data}), Array.prototype.map can only be used for array.

Since response data is an array, you can directly set it as setUser(data)

user.js

 export function* handleGetUser(action) {
      try {
        const response = yield call(requestGetUser);
        const { data } = response; //data is an Array
        console.log('data',data);
        yield put(setUser(data));
      } catch (error) {
        console.log(error);
      }
    }

userSlice.js

const userSlice = createSlice({
  name: "user",
  initialState: {},
  reducers: {
    getUser() {},
    setUser(state, action) {
      const userData = action.payload; //setting userData (Array) as data
      return { ...state, data:userData };
    }
  }
});

App

return (
    <div className="App">
      {user.data.length}
      {user.data?.map((obj) => <h1 key = {obj.id}>{obj.id}.{obj.title}</h1>)}
    </div>
  );


问:
Angular - Can't assign null to File type
I have got an interface like this

export interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile: File;
}
```
<p>And in my component, I declared the object as</p>
<pre class="lang-js prettyprint-override"><code>export class MyComponent Implements OnInit {
  RF:  ReportFiles = { ReportName: "", Log: 0, MyFile: null }
  ...
  ...
}
</code>```

The error message shows

'null' is not assignable to File

How can I resolve this?

答:
We usually don't assign type any because it defeats the purpose of type checking but any type may be used when type changes are expected.

```<code>export interface ReportFiles{
  ReportName: string;
  Log: number;
  MyFile: any;
}
</code>```

Seeing your need to initialize a obj RF type of ReportFiles I would suggest converting ReportFiles and File into class objects. But this is optional. If you need/wish to create an instance of perhaps a custom object, whilst getting the benefits of type-checking things such as arguments, return types or generics - a class makes sense. If you’re not creating instances - we have interfaces at our disposal, and their benefit comes from not generating any source code, yet allowing us to somewhat “virtually” type-check our code.

Body:
I have got an interface like this

export interface ReportFiles {
  ReportName: string;
  Log: number;
  MyFile: File;
}

And in my component, I declared the object as

export class MyComponent Implements OnInit {
  RF:  ReportFiles = { ReportName: "", Log: 0, MyFile: null }
  ...
  ...
}

The error message shows

'null' is not assignable to File

How can I resolve this?

Body:
We usually don't assign type any because it defeats the purpose of type checking but any type may be used when type changes are expected.

export interface ReportFiles{
  ReportName: string;
  Log: number;
  MyFile: any;
}

Seeing your need to initialize a obj RF type of ReportFiles I would suggest converting ReportFiles and File into class objects. But this is optional. If you need/wish to create an instance of perhaps a custom object, whilst getting the benefits of type-checking things such as arguments, return types or generics - a class makes sense. If you’re not creating instances - we have interfaces at our disposal, and their benefit comes from not generating any source code, yet allowing us to somewhat “virtually” type-check our code.


问:
WinAPI equivalent for Linux/POSIX pthread_wait/pthread_post
I have an application which takes care of some syncronization problems, it relies heavily on the POSIX functions, sem_wait, pthread_join and sem_post, I'd like to know what are the winapi equivalents for these?</p>

答:
sem_wait() -> WaitForSingleObject() on a Semaphore object

pthread_join() -> WaitForSingleObject() on a Thread object

sem_post()-> ReleaseSemaphore() on a Semaphore object

See Using Semaphore Objects in MSDN's documentation.


问:
why cursor not go to next line? When getline() take "\n" as an input
I was learning from https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdstring/
and a question arises from the below code

```<code>#include <string>
#include <iostream>

int main()
{
    std::cout << "Pick 1 or 2: ";
    int choice{};
    std::cin >> choice;

    std::cout << "Now enter your name: ";
    std::string name{};
    std::getline(std::cin, name); // note: no std::ws here

    std::cout << "Hello, " << name << ", you picked " << choice << '\n';

    return 0;
}
</code>```

the question arising line is

```<code>std::getline(std::cin, name); // note: no std::ws here
</code>```

here above code accepts '\n' as input for std::cin ok!

And the output is below

```<code>Pick 1 or 2: 2
Now enter your name: Hello, , you picked 2
</code>```

Simple!

so my question is why the output does not go in the next line after 'Hello,' because std::cin takes the value "\n"?

the problem is not to buffer! I want to say that the output must print

```<code>Pick 1 or 2: 2
Now enter your name: Hello,
, you picked 2
</code>```

答:
because there is still a \n in the input buffer from the first read of choice, you need to tell cin to ignore it.

```<code>int choice{};
std::cin >> choice;
std::cin.ignore(); <<<=============
std::cout << "Now enter your name: ";
std::string name{};
</code>```

EDIT

you wonder why name isnt equal to "\n" instead of ""

the reason is that getline ignores \n. it returns everything upto \n but not including the \n. So when the input buffer just has \n in it getline returns an empty string into name

Body:
I was learning from https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdstring/
and a question arises from the below code

#include <string>
#include <iostream>

int main()
{
    std::cout << "Pick 1 or 2: ";
    int choice{};
    std::cin >> choice;

    std::cout << "Now enter your name: ";
    std::string name{};
    std::getline(std::cin, name); // note: no std::ws here

    std::cout << "Hello, " << name << ", you picked " << choice << '\n';

    return 0;
}

the question arising line is

std::getline(std::cin, name); // note: no std::ws here

here above code accepts '\n' as input for std::cin ok!

And the output is below

Pick 1 or 2: 2
Now enter your name: Hello, , you picked 2

Simple!

so my question is why the output does not go in the next line after 'Hello,' because std::cin takes the value "\n"?

the problem is not to buffer! I want to say that the output must print

Pick 1 or 2: 2
Now enter your name: Hello,
, you picked 2

Body:
because there is still a \n in the input buffer from the first read of choice, you need to tell cin to ignore it.

int choice{};
std::cin >> choice;
std::cin.ignore(); <<<=============
std::cout << "Now enter your name: ";
std::string name{};

EDIT

you wonder why name isnt equal to "\n" instead of ""

the reason is that getline ignores \n. it returns everything upto \n but not including the \n. So when the input buffer just has \n in it getline returns an empty string into name


问:
aiohttp: UnboundLocalError: local variable 'url' referenced before assignment
This error has had me scratching my head all night long. This is part of my script, and the most problematic one.

```<code>async def main():

        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                for url in pepsi:
                    bottle.append((url, response.status))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code>```

It outputs the following error:

```<code>UnboundLocalError: local variable 'url' referenced before assignment
</code>```

What does this error exactly mean, and how can I fix it? The loop works just fine without async, so why does utilizing async make this error appear?

Thank you.

答:
Exactly what the error message says. Have a look at the annotations:</p>
```<code>async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
                               ^^^ `url` is used here
            for url in pepsi:
                ^^^ `url` is assigned for the first time here
                bottle.append((url, response.status))
</code>```

Body:
This error has had me scratching my head all night long. This is part of my script, and the most problematic one.

async def main():

        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                for url in pepsi:
                    bottle.append((url, response.status))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

It outputs the following error:

UnboundLocalError: local variable 'url' referenced before assignment

What does this error exactly mean, and how can I fix it? The loop works just fine without async, so why does utilizing async make this error appear?

Thank you.

Body:
Exactly what the error message says. Have a look at the annotations:

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
                               ^^^ `url` is used here
            for url in pepsi:
                ^^^ `url` is assigned for the first time here
                bottle.append((url, response.status))


问:
How do you log information using a static method from a class using TypeScript?
This is for a school project. I'm having trouble getting the names from the class to log using a method. I have a class that maakes the monster and another one that extends it.

abstract class genMonster {
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}
```
<p>I have the monster objects</p>
```const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);
```
<p>and this is the method I tried but doesn't work</p>
```class organize extends genMonster{
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number){
    super(id, name, weaknesses, location, challenge, mortality, safety)
  }

  public static getNames(){
    return this.name
  }
}

console.log(organize.getNames());
//logs 'organize'
```

Any help is appreciated

答:
Since a static method cannot access instance fields, you might need to keep a record of all the names taken by monsters on a static field (takenNames) when each monster is created.

Then you could have a static method (getTakenNames) that returns takenNames

```<code>abstract class genMonster {
  static takenNames: string[] = [];
  static getTakenNames(): string[] {
    return ghost.takenNames;
  }
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {

  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
    ghost.takenNames.push(name);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

console.log(genMonster.getTakenNames())
</code>```

playground

Body:
This is for a school project. I'm having trouble getting the names from the class to log using a method. I have a class that maakes the monster and another one that extends it.

abstract class genMonster {
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

I have the monster objects

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

and this is the method I tried but doesn't work

class organize extends genMonster{
  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number){
    super(id, name, weaknesses, location, challenge, mortality, safety)
  }

  public static getNames(){
    return this.name
  }
}

console.log(organize.getNames());
//logs 'organize'

Any help is appreciated

Body:
Since a static method cannot access instance fields, you might need to keep a record of all the names taken by monsters on a static field (takenNames) when each monster is created.

Then you could have a static method (getTakenNames) that returns takenNames

abstract class genMonster {
  static takenNames: string[] = [];
  static getTakenNames(): string[] {
    return ghost.takenNames;
  }
  constructor(
    public id: string,
    public name: string,
    public weaknesses: string[],
    public location: string,
    public challenge: number,
    public mortality: boolean = false,
    public safety: number,
  ) {}

  monsterLogger() {
    return this
  }
}

class ghost extends genMonster {

  constructor(id: string, name: string, weaknesses: string[], location: string, challenge: number, mortality: boolean, safety: number, public type: string, public signs: string[]) {
    super(id, name, weaknesses, location, challenge, mortality, safety);
    ghost.takenNames.push(name);
  }

  get info() {
    return console.log(this.name, this.type, this.signs);
  }
}

const Jerry = new ghost("0234", "Jerry", ["soap", "attractive people"], "-74.4835, 171.4803",  3, false, 2, "boring", ["libra", "ectoplasm puddles", "yamaha piano music"]);
const Patricia = new ghost("8765", "Patricia", ["being sent to the corner", "milk and cookies"], "-89.3921, -30.4079",  1, false, 2, "spooky", ["stray drawing supplies", "messy living rooms", "spilled milk"]);
const Lola = new ghost("4569", "Lola", ["makeup remover", "tied shoelaces"], "-61.6134, -90.1008",  10, false, 10, "boss music", ["water tasting like cotton candy", "spontaneous laughing", "socks mysteriously becoming fun and colorful"]);

console.log(genMonster.getTakenNames())

<a href="https://www.typescriptlang.org/play?ssl=8&ssc=30&pln=7&pc=29#code/IYIwzgLgTsDGEAJYBthjAg5gUwHYFkB7XSbKBAbwFgAoWhJYyKAV3kKgAp6GEAHFiGQBLWAmEATAFwJmw3JgA0PBgKGiEuYAFtsMuQuU1e-QSLEB3bMADWubOgf7o8zAG0AukZNrzCZISwwBDCxM5Qrt68vhqwABbAyMh4ODK4LNogZFGqZhraHBCJwhAAnjIghITJwLgIALwIAGaJYNg5pupiYMBN2GVpGVlQUQCUlAC%20tDwFJBBkADKEmDhc49TGvFD9LFB1EHHCYDxTNKe0KGgYmHGEkAjYAB7zuBLXeERzZJQ8kMEaRRseAAcjonLIXApPA0EJ4ANy-IohMQ4CAAFVsILBYE4o3CrmhGxM2wguzqNzuEAAdICsbowAjNudNrAmNA2BAOJxJPjDJowbylAgrLZ7I4wILPIp-IF-mEIRE%20fFEskFHpNENsggClAiiIBghKtVrLhpT0%20gb0pktTExGU%20OqDELbbJhJgSJKPOsVLIWA6uJJpVpdNKRXYHG0wNKAkEQsRpcqkil2trCsUymbev1SqNGSYKZAaZjcKD6VSBGA4pxg9hcydpptUeJcE1CLifpsGCSyYwSMaqQFMJwDkcqTXpSOwDTSg6J4cp2A3SQ60zaMzWXMEAApMhQUow%20wWLC3SCcABEAAYAEwAZgALGfpWed1A94-YWewIRgHx32fgtAcAhAAbtg-DYIQfDJGeXgIGeAC0ADsd5UneAAcN4AKzSgAjIhOGoWhF43u%20CA3tKLTIG00pXk%20lSKpg75uGeIggDAf7YOwUFoNopgSBIyRgH%20pQ6MACT8MItSENqLCLrAMErhu9wAArBBEsCSQe2BHgWEDnmhiEAGyYX%20qkuBpwBMWeWSuLIeCIJyCAHGBrJ7GQf7aMIyA2AgtQSIwhA2MIDgwU%208FoQAnFSN4RVeOHSvBN4XqhF6IRFpHxc0rQprRcFgHwVQ2KUVnMMA%204SDAFi2WAfpQcFQlPvSYD7iIwG2VAVTaA1eV8F5yT%20Z53kKYySmIEsqBaTpJ56Wed6YYZ6VPuNlnSsx2iYn6CDbAUoFQH%20ITYP5laENgqCwCFsEIYZBHXfeCURclOEXheaEZReFHZbh71wZU6AyXJVkWME3xFJAtkiECjAQJydRBK8xVPvlxBFPYhCyf4wAsDcrh-l%20sA2Bg2ilKQERo2AyD7lkrKeQozQsHUfmMAEUBNCwyDDQ2Sn9oOnC6VSqIYkCJbYrioxAA" rel="nofollow noreferrer">playground


问:
How to display discord.js greeting message?
I got some problem when tried my discord.js bot to send a greeting when somebody come in the server. I followed all of the instruction from documentation, but it doesn't change anything. My terminal didn't send an error and any commands is useable. My discord.js version is 12.5.3

client.on('guildMemberAdd', member => {
    const lobbyChannel = member.guild.channels.find(ch => ch.name === 'lobby');
    if (!lobbyChannel) return;
    lobbyChannel.send(`Welcome to the server, ${member}`).catch(console.error);
});

```

答:
You have to change your code to this since the .find() method is only there in the cached channels which you can access by using member.guild.channels.cache. You will also need the GUILD_MEMBERS intent when you declare the client if you want the information when a new member joins. Other than that, your code might look like this:

client.on('guildMemberAdd', member => {
    const lobbyChannel = member.guild.channels.cache.find(ch => ch.name === 'lobby');
    if (!lobbyChannel) return;
    lobbyChannel.send(`Welcome to the server, ${member}`).catch(console.error);
});
```