答:
Be careful to async program and result. Your code is not correct, try in this way:

```<code>addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
      }
    );

  }
</code>```

Now it must be work

Body:
I have an object in angular:

export class Task {
  taskId: number;
  description: string;
  date: string;
  project: Project;
}

And in a component, I want to have a method that adds a new task. And for this I created a component:

export class CreateNewTaskComponent implements OnInit {

  task: Task = new Task();
  projectName: string;
  newTask: Task = new Task();

  constructor(
    private taskService: TaskService,
    private projectService: ProjectService,
    private router: Router) {
  }

  addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {
        this.project = project;
        console.log('Project: ' + JSON.stringify(this.project));
      }
    );

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = this.project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
  }

I have created a Project object based on the project name. When I did console.log('Project: ' + JSON.stringify(this.project)); I received the correct answer. But when I tried to assign the project to a new task  this.newTask.project = this.project; the result is undefined.

Body:
Be careful to async program and result. Your code is not correct, try in this way:

addANewTask() {
    this.projectService.getProjectByProjectName(this.projectName).subscribe(
      (project) => {

    this.newTask.description = this.task.description;
    this.newTask.date = this.task.date;
    this.newTask.project = project;

    this.taskService.createNewTask(this.newTask).subscribe(
      task => {
        console.log(task);
        this.router.navigate(['/tasks']);
      });
      }
    );

  }

Now it must be work


来源: stackexchange

问:
Counting open files per process
I'm working on an application that monitors the processes' resources and gives a periodic report in Linux, but I faced a problem in extracting the open files count per process.

This takes quite a while if I take all of the files and group them according to their PID and count them.

How can I take the open files count for each process in Linux?

答:
This works for me:

```<code>ps -opid= -ax | xargs -L 1 -I{} -- sudo bash -c 'echo -n "{} ";lsof -p {} 2>/dev/null | wc -l' | sort -n -k2
</code>```

It prints numopenfiles per pid sorted by numopenfiles.

It will ask for sudo password once.

Note that the sum of the above numbers might be bigger than the total number of open files from all processes.

As I read here: forked processes can share file handles

ContentLicense: CC BY-SA 3.0

Title: Counting open files per process

Body:
This works for me:

ps -opid= -ax | xargs -L 1 -I{} -- sudo bash -c 'echo -n "{} ";lsof -p {} 2>/dev/null | wc -l' | sort -n -k2

It prints numopenfiles per pid sorted by numopenfiles.

It will ask for sudo password once.

Note that the sum of the above numbers might be bigger than the total number of open files from all processes.

As I read here: forked processes can share file handles

ContentLicense: CC BY-SA 4.0


问:
JSONata: method or function for testing JSON value datatype
JSONata offers conditional expressions and predicates which can be used to select values out of JSON trees.

However, I have not been able to find a way to test the datatype of a JSON value.

For example, given the array:

```<code>    [null, true, false, 1, 2.3, "a", ["x"], {}, {"y" : "z}]
</code>```

I only want to pull out the numeric values.

```<code>    [1, 2.3]
</code>```

Q: In a JSONata query, how does one test the JSON datatype (null, boolean, number, string, array, object) of a value?

答:
JSONata offers the $type-method to check datatype of a JSON value. For example. the following snippet will return the datatypes of the values in the invoices example data in https://try.jsonata.org.

```<code>Account.Order.Product.{
    "priceType": $type(Price),
    "productNameType": $type($.'Product Name'),
    "descriptionType": $type(Description)
}
</code>```

The result is:

```<code>[
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  }
]
</code>```

By changing values of Price and Product Name to null in the example JSON, the result will change for that particular object to:

```<code>{
    "priceType": "null",
    "productNameType": "null",
    "descriptionType": "object"
},
</code>```

One can check for 'null', 'number', 'string', 'array', 'object', 'boolean'.

For my concern I've used it to check for null values when converting dates to milliseconds:

```<code>'enddate': $type($v.enddate) = 'null' ? null : $toMillis($v.enddate),
</code>```

Body:
JSONata offers conditional expressions and predicates which can be used to select values out of JSON trees.

However, I have not been able to find a way to test the datatype of a JSON value.

For example, given the array:

    [null, true, false, 1, 2.3, "a", ["x"], {}, {"y" : "z}]

I only want to pull out the numeric values.

    [1, 2.3]

Q: In a JSONata query, how does one test the JSON datatype (null, boolean, number, string, array, object) of a value?

Body:
JSONata offers the $type-method to check datatype of a JSON value. For example. the following snippet will return the datatypes of the values in the invoices example data in https://try.jsonata.org.

Account.Order.Product.{
    "priceType": $type(Price),
    "productNameType": $type($.'Product Name'),
    "descriptionType": $type(Description)
}

The result is:

[
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  },
  {
    "priceType": "number",
    "productNameType": "string",
    "descriptionType": "object"
  }
]

By changing values of Price and Product Name to null in the example JSON, the result will change for that particular object to:

{
    "priceType": "null",
    "productNameType": "null",
    "descriptionType": "object"
},

One can check for 'null', 'number', 'string', 'array', 'object', 'boolean'.

For my concern I've used it to check for null values when converting dates to milliseconds:

'enddate': $type($v.enddate) = 'null' ? null : $toMillis($v.enddate),


问:
How do you balance fun feature creep with time constraints?
I enjoy programming, usually.  Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.

But a lot of my coding is fun and when I get in the 'zone' I just really enjoy myself.

Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.

How do you recognize this is happening before it exceeds your time frame?

What do you do before starting a potentially fun piece of code, or during, to get back on track?

When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?

-Adam

答: With a backlog. That way you'll always have in mind what needs to be done before you can start doing what you want to do.

OwnerDisplayName: Adam Davis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dF

OwnerDisplayName: Esteban


问:
"The number of parameters does not match number of values for stored procedure" System.Data.Common.DbCommand nuance
This could be an sql server database setup issue, but I am not to sure where to start looking.

I have a stored procedure:

```<code>CREATE PROCEDURE aStoredProcedure
@dteSince DATETIME = null
AS
...
</code>```

The C# code to call the stored procedure is:

```<code>using (IDataReader dr = database.ExecuteReader("aStoredProcedure"))
{
...
</code>```

The C# code works fine on the Production environment. Here, dteSince will be set to null as it is not supplied as a input parameter.

Problem is when I run this in the UAT environment, it returns the message shown in the title - wrong number of parameters...

I can fix this by changing the code to:

```<code>using (IDataReader dr = database.ExecuteReader (CommandType.StoredProcedure, "aStoredProcedure"))
{
...
</code>```

The fix just masks the real problem as to how can the code fails on one environment and works fine on another.

I have dropped and recreated the stored procedure, with no luck.

Technologies used C# 2.0 & Sql Server 2005.

答:
You can use SQL Profiler to see what is happening on the SQL Server perspective.

Ideally getting someone to capture a trace from production as well so they can be compared.

OwnerDisplayName: Ferds

Body:
This could be an sql server database setup issue, but I am not to sure where to start looking.

I have a stored procedure:

CREATE PROCEDURE aStoredProcedure
@dteSince DATETIME = null
AS
...

The C# code to call the stored procedure is:

using (IDataReader dr = database.ExecuteReader("aStoredProcedure"))
{
...

The C# code works fine on the Production environment. Here, dteSince will be set to null as it is not supplied as a input parameter.

Problem is when I run this in the UAT environment, it returns the message shown in the title - wrong number of parameters...

I can fix this by changing the code to:

using (IDataReader dr = database.ExecuteReader (CommandType.StoredProcedure, "aStoredProcedure"))
{
...

The fix just masks the real problem as to how can the code fails on one environment and works fine on another.

I have dropped and recreated the stored procedure, with no luck.

Technologies used C# 2.0 & Sql Server 2005.

LastEditorDisplayName: Ferds

OwnerDisplayName: Richard


问:
Something like margin or padding except where background doesn't draw
Is there something that will do what margin does but without the background drawing in that area? For instance, when you give an element margin: 1em you get a 1em border of blank space around the element, but the background draws in that area. Is there something similar to that except where the background doesn't draw?

My problem is I'm trying to put something below three float: lefted divs and right now I can't get any spacing between that and the floated divs above it. They just abut directly against each other.

The div that is going below the float: lefted divs has the property clear: both. If there was something that made that div have space between it and that floated div above it then that would work too.

答:
Perhaps you're looking for:</p>

```<code>border: 4px white; /* replace with your color */
</code>```

Body:
Perhaps you're looking for:

border: 4px white; /* replace with your color */


问:
Can't connect to NAS, even via IP
Background

Been having a lot if issues with this problem. Randomly PC won't connect to NAS for apparently no reason at all, while others it works. I read tonne of posts about various fixes, some worked sometimes, some didn't, but lately none did. Restarting PC, NAS, or router didn't work, nor did changing settings, checking firewall, antivirus, etc.. Finally I managed to figure it out.

Our nas allow us to make a network name to access it by, like \\MyServer, but sometimes when power goes out, or we have to restart router, this address won't work because the server's local IP had changed, and the address was still cached on our computer to the old one.

The reason can be one of many. In my case, it was none that I could find common answers to.

TL;DR
I randomly can't connect to my NAS via \\MyServer or it's IP \\10.0.0.3, but other PC's can.

答:
Reason (in my specific case)

Sometimes the PC would only connect to the NAS via IPv6 (almost feel like it does it on a whim), IPv4 won't work at all. That or the old IP is cached on your system.

IPv4 looks something like one of these: 10.0.0.5, 172.16.0.2, or 192.168.0.0

IPv6 looks something like: fe80::842a:a43d:3123:1332

Quick fix attempt first

First, just try opening command prompt and enter ipconfig /flushdns, then try to connect to your usual \\MyServer address, see if that works now.

Didn't work?

What you can try is to see if you can connect via its IPv6 — but first you need to somehow obtain it.

Step 1 In command prompt, type ping MyServer (replaced with whatever name you have), and it see if it manages to ping it. If it does, it will resolve the IP and show an IPv6. If it shows IPv4 or can't connect at all, see further down.

Step 2 Locate the IPv6 at the top, remove % and number after.

Step 3 Replace : with -. Note doubles if you have that: :: with --.

Step 4  Prefix the usual \\ at the start, and add .ipv6-literal.net at the end. Now try to connect to the server using that. With the IPv6 example above, it'd be something like: \\fe80--842a-a43d-3123-1332.ipv6-literal.net

Ping shows IPv4?

Try to ping with one of the other computers, or if you are able to, login to the web dashboard or equivalent on one of those computers, and see if you can find any information about the server's IP's, with goal of finding its IPv6.

Once found, do steps above.

Done!

Other stuff:

IPv6 in browser — remove the % and number, put IP inside brackets [] and then connect. Example: http://[fe80::842a:a43d:3123:1332].

Creating alias of the weird IPv6:

Step 1 Right click Notepad, and open as Administrator

Step 2 Go to File → Open, change the dropdown above 'open' from Textfiles (*.txt) to All files (*.*).

Step 3 Locate the hosts file, located at C:\C:\Windows\System32\drivers\etc\ and open

Step 4 At the bottom, write the IPv6 with the colons AND the %##, then a space, then the alias you want it to use (case insensitive). Example: fe80::842a:a43d:3123:1332%15 MyAlias and save. You should now be able to use \\MyAlias to connect to it.

NOTE The %## number is unique to each computer. E.g. your computer gets %15, the next get %7. The rest of the IP is identical. To get the %## number of a different PC, write ipconfig in its command prompt. It should list its own IPv6 with its appended %## at the end.

Another note: If you need to change an IP in the hosts file of an IP that no longer work, you also need to use ipconfig /flushdns again.

Title: Can't connect to NAS, even via IP


问:
Flutter List View through Future Provider Value
I am trying to call the output of a Future Provider of type Future> into a List View builder. I think I am very near as I am able to render the final List View itself, however, prior that, an error appears and is quickly replaced by the List View after completing the Future. I believe there may be something wrong with my implementation there.

Here's what I've got so far (these are derivatives of my actual code, there's too many going on there that aren't necessary, I tried to simplify it):

```<code>class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;

    Future<List<Widget>> getList() async{
        List _result = await db....
        _result.forEach((_item){
            addToList(_item);
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return FutureBuilder(
            initialData: <Widget>[],
            future: TempProvider().getList(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.none &&
                    snapshot.hasData == true) {
                    return ListView.builder(
                        itemCount: futureProvider.length,
                        itemBuilder: (BuildContext context, int index) {
                            return futureProvider[index];
                        },
                    );
                } else {
                    return Text('ALAWS');
                }
          },
        );
    }
}
</code>```

So basically, the output of my Future will be a list of widgets that will populate a List View that I am trying to build. Though I am able to render the list view in the end, the error below appears in between:

```<code>The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was
FutureBuilder<List<Widget>>
</code>```

Hoping someone can help with this one or at least give a better example.

Thank you so much!

答:
So I have been doing my research and found the article below which shows a definite implementation based on what I need:

Flutter Provider Examples - Codetober
Credits to Douglas Tober for the article. Thanks again to Kalpesh for the quick help!

Body:
I am trying to call the output of a Future Provider of type Future> into a List View builder. I think I am very near as I am able to render the final List View itself, however, prior that, an error appears and is quickly replaced by the List View after completing the Future. I believe there may be something wrong with my implementation there.

Here's what I've got so far (these are derivatives of my actual code, there's too many going on there that aren't necessary, I tried to simplify it):

class TempProvider extends ChangeNotifier(){
    List<Widget> _list = <Widget>[];
    List<Widget get list => _list;

    Future<List<Widget>> getList() async{
        List _result = await db....
        _result.forEach((_item){
            addToList(_item);
        });
    }

    addToList(Widget widget){
        _list.add(widget);
        notifyListeners();
    }
}

class Parent extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
        return FutureProvider(
        create: (context) => TempProvider().getList(),
        child: Child(),
        );
    }
}

class Child extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    var futureProvider = Provider.of<List<Widget>>(context);

        return FutureBuilder(
            initialData: <Widget>[],
            future: TempProvider().getList(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState == ConnectionState.none &&
                    snapshot.hasData == true) {
                    return ListView.builder(
                        itemCount: futureProvider.length,
                        itemBuilder: (BuildContext context, int index) {
                            return futureProvider[index];
                        },
                    );
                } else {
                    return Text('ALAWS');
                }
          },
        );
    }
}

So basically, the output of my Future will be a list of widgets that will populate a List View that I am trying to build. Though I am able to render the list view in the end, the error below appears in between:

The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was
FutureBuilder<List<Widget>>

Hoping someone can help with this one or at least give a better example.

Thank you so much!


问:
Remove Focus from AgGrid when click outside the ag-grid
I'm using AG Grid on a website. When the user clicks a cell, it is focused and gets a blue outline.
I need to remove this focus when the user clicks outside the selected element.

```<code>const body = document.body;
body.addEventListener('mouseup', (e) => {
    const container = this.commonAgGrid.nativeElement;
    if (!container.contains(e.target)) {
        this.gridApi.clearFocusedCell();
    }
 });
</code>```

But this is not working when I am using mat select component in ag-grid. Example- plunker

Please change the dropdown value, the value won't change because of this.

答:
Ok, here what you need to understand:

clicks listener should be implemented inside your custom component, cuz only withing this component you can bind listener for tracking
click-outside event

listener should be implemented inside ngAfterViewInit method cuz of @ViewChild rendering lifecycle

@ViewChild requires to get element and his scope - for outside-click tracking possibility

So you need to have ViewChild - bound to your template (inside custom component)

```<code>@ViewChild('yourElementRef') public yourElementRef:ElementRef
</code>```

Then, bound this property yourElementRef to the template (tag (div, form, whatever) should be HTML based - not directive from third party libraries - cuz reference could be missed)

```<code>template: `
    <mat-card>
    <form #yourElementRef class="container" tabindex="0" (keydown)="onKeyDown($event)">
    ...
</code>```

again if you put #yourElementRef in <mat-cad> - native element reference would be missed

And the last thing is tracking itself

```<code>ngAfterViewInit() {
    ...
    let body = document.body;
        body.addEventListener("mouseup", (e) => {
        let container = this.yourElementRef.nativeElement;
        if (!container.contains(e.target)){
            this.params.api.clearFocusedCell();
        }
    })
}
</code>```

DEMO

P.S: this is a solution for selection reset ONLY, on exact this example - values (models) doesn't update properly (cuz it's just wrong implemented)

Body:
I'm using AG Grid on a website. When the user clicks a cell, it is focused and gets a blue outline.
I need to remove this focus when the user clicks outside the selected element.

const body = document.body;
body.addEventListener('mouseup', (e) => {
    const container = this.commonAgGrid.nativeElement;
    if (!container.contains(e.target)) {
        this.gridApi.clearFocusedCell();
    }
 });

But this is not working when I am using mat select component in ag-grid. Example- plunker

Please change the dropdown value, the value won't change because of this.

Body:
Ok, here what you need to understand:

clicks listener should be implemented inside your custom component, cuz only withing this component you can bind listener for tracking
click-outside event

listener should be implemented inside ngAfterViewInit method cuz of @ViewChild rendering lifecycle

@ViewChild requires to get element and his scope - for outside-click tracking possibility

So you need to have ViewChild - bound to your template (inside custom component)

@ViewChild('yourElementRef') public yourElementRef:ElementRef

Then, bound this property yourElementRef to the template (tag (div, form, whatever) should be HTML based - not directive from third party libraries - cuz reference could be missed)

template: `
    <mat-card>
    <form #yourElementRef class="container" tabindex="0" (keydown)="onKeyDown($event)">
    ...

again if you put #yourElementRef in <mat-cad> - native element reference would be missed

And the last thing is tracking itself

ngAfterViewInit() {
    ...
    let body = document.body;
        body.addEventListener("mouseup", (e) => {
        let container = this.yourElementRef.nativeElement;
        if (!container.contains(e.target)){
            this.params.api.clearFocusedCell();
        }
    })
}

DEMO

P.S: this is a solution for selection reset ONLY, on exact this example - values (models) doesn't update properly (cuz it's just wrong implemented)


问:
How to set the docker volume in windows?
I have a folder test with a yaml file inside.

I have a following yaml file.

```<code>version: '3'
services:
  mariadb:
    image: 'bitnami/mariadb:10.3'
    volumes:
      - './test/docker_volumn/mariadb_data:/bitnami'
    environment:
      - MARIADB_USER=bn_wordpress
      - MARIADB_DATABASE=bitnami_wordpress
      - ALLOW_EMPTY_PASSWORD=yes
volumes:
  mariadb_data:
    driver: local
  wordpress_data:
    driver: local
</code>```

When I try to run docker-compose up -d, it gives me error:

```<code>ERROR: for test_mariadb_1  Cannot create container for service mariadb: invalid volume specification: 'D:\test\docker_volumn\mariadb_data:/bitnami:rw': invalid mount config for type "bind": bind source path does not exist: d:\test\docker_volumn\mariadb_data
</code>```

Does anyone knows how to fix this?

答:
Here are a few things to get you started:

You got a typo in your volume definition "volumn"

```<code>volumes:
  - './test/docker_volumn/mariadb_data:/bitnami'
</code>```

Does the folder D:/test/docker_volumn/mariadb_data exist on your host?
If not, create it beforehand (preferably without the typo ;) ).

Since you are writing a docker-compose file based on version: '3' I recommend to
 use the long syntax to define volumes as described in the docker-compose file reference to explicitly define the type of the volume in question.

```<code>volumes:
  - type: bind
    source: ./test/docker_volumn/mariadb_data
    target: /bitnami
</code>```

Source

https://docs.docker.com/compose/compose-file/#volumes

Body:
I have a folder test with a yaml file inside.

I have a following yaml file.

version: '3'
services:
  mariadb:
    image: 'bitnami/mariadb:10.3'
    volumes:
      - './test/docker_volumn/mariadb_data:/bitnami'
    environment:
      - MARIADB_USER=bn_wordpress
      - MARIADB_DATABASE=bitnami_wordpress
      - ALLOW_EMPTY_PASSWORD=yes
volumes:
  mariadb_data:
    driver: local
  wordpress_data:
    driver: local

When I try to run docker-compose up -d, it gives me error:

ERROR: for test_mariadb_1  Cannot create container for service mariadb: invalid volume specification: 'D:\test\docker_volumn\mariadb_data:/bitnami:rw': invalid mount config for type "bind": bind source path does not exist: d:\test\docker_volumn\mariadb_data

Does anyone knows how to fix this?

Body:
Here are a few things to get you started:

You got a typo in your volume definition "volumn"

volumes:
  - './test/docker_volumn/mariadb_data:/bitnami'

Does the folder D:/test/docker_volumn/mariadb_data exist on your host?
If not, create it beforehand (preferably without the typo ;) ).

Since you are writing a docker-compose file based on version: '3' I recommend to
 use the long syntax to define volumes as described in the docker-compose file reference to explicitly define the type of the volume in question.

volumes:
  - type: bind
    source: ./test/docker_volumn/mariadb_data
    target: /bitnami

Source

https://docs.docker.com/compose/compose-file/#volumes


问:
while compiling a code using gcc on mac OS linker failed in linking custom made static library
here is the file structure for my project file in c-language :

first is a fullCourse folder

fullCourse folder contains three folders :

1. include

2. src

3. lib

4. test

in include folder :

it contains a header file : temp.h

code for temp.h is as follow :

```<code>#ifndef __$__temp_h
#define __$__temp_h 234
int yash();
#endif
</code>```

in src folder :

It contains a source file : temp.c

code for temp.cc is as follow :

```<code>#ifndef __$__temp_c
#define __$__temp_c 234
int yash()
{
return 22;
}
#endif
</code>```

then staying in same folder, created .o file as follow :

```<code>gcc -I ../include -c temp.c
</code>```

next step was moving this temp.o file to lib folder as follow :

```<code>mv temp.o ../lib
</code>```

than staying in lib folder created a archived (or library) file as follow :

```<code>ar rcs libtmds.a temp.o
</code>```

than in test folder wrote a source code to test library(tempTest.c)

code for tempTest.c is as follow :

```<code>#include<stdio.h>
#include<temp.h>
int main()
{
int w;
w=yash();
printf("%d\n",w);
return 0;
}
</code>```

than staying in test folder tried to compile it as follow :

```<code>gcc -static -I ../include tempTest.c -L ../lib -ltmds -o tempTest.exe
</code>```

but code didn't compiled, showing following error :

```<code>ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

please help me resolve this problem.

答: -static is in error here.  To link to your static lib just plain link to it without any -static flag, which is for kernel compilation.

Body:
here is the file structure for my project file in c-language :

first is a fullCourse folder

fullCourse folder contains three folders :

1. include

2. src

3. lib

4. test

in include folder :

it contains a header file : temp.h

code for temp.h is as follow :

#ifndef __$__temp_h
#define __$__temp_h 234
int yash();
#endif

in src folder :

It contains a source file : temp.c

code for temp.cc is as follow :

#ifndef __$__temp_c
#define __$__temp_c 234
int yash()
{
return 22;
}
#endif

then staying in same folder, created .o file as follow :

gcc -I ../include -c temp.c

next step was moving this temp.o file to lib folder as follow :

mv temp.o ../lib

than staying in lib folder created a archived (or library) file as follow :

ar rcs libtmds.a temp.o

than in test folder wrote a source code to test library(tempTest.c)

code for tempTest.c is as follow :

#include<stdio.h>
#include<temp.h>
int main()
{
int w;
w=yash();
printf("%d\n",w);
return 0;
}

than staying in test folder tried to compile it as follow :

gcc -static -I ../include tempTest.c -L ../lib -ltmds -o tempTest.exe

but code didn't compiled, showing following error :

ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

please help me resolve this problem.


问:
How to share DbContext between different WebApps?
I've one missing link to understood how it could work to "connect" my EF core's DbContext to different applications in following scenario:

I've got one application project which contains the whole EF Core Code first datamodel (Entities, Business Logic, Enums etc).

Until now we're using a WebAPI application to share data with multiple endpoints.
So the data we're exchanging now are quite static at the moment. We create our DbContext and the API is using it for data reading and write operations.

Now there is customer request to also build a WebUI (Blazor). So we still want to use the WebAPI for data exchange in the UI, but further we need some more business logic elements from our data model (containing INotifyPropertyChanged event handling etc). We implemented the event handles in the entity classes. So we intend to build a session object for each user/client which contains the DbContext instance. But how can handover an instantiated DbContext from the Web API to my UI Application.

Would be nice to get some input. Thx for any advice.

答:
You do not pass the DBContext object to "UI Application", such as a Blazor app.
You did not mention what flavor of Blazor you are using... However, the following may be applicable for both Blazor Server App and Blazor WebAssembly App... From what I've gather from your question you are exposing Web Api end points to retrieve data and save data. This is good. What is left for you to do is to create code in your Blazor that access those end points. You should use the HttpClient service to do this. If you use Blazor client side, this object is configured and made available for injection in your components and services. This type of HttpClient is based on the JavaScript Fetch Api.

If you are going to create a Balzor Server App, then you'll have to add the HttpClient service to the DI container and configure it accordingly, and only then you'd be able to inject it into your components and services. In this case you should use the IHttpClientFactory to provide the HttpClien onjects.

In principle, you have to query your Web Api methods via HttpClient.

Note that if you use Blazor Server App, you don't have to use Web Api. Instead you can create services that perform similar functionality to that provided by the Web Api.

Please, go to the docs and acquaint yourself how to use the HttpClient with Blazor apps.

Hope this helps...


问:
Setting the browser language in Cypress
Is it possible to tell Cypress to launch Chrome with a certain language (e.g. German) as I have an application which I need to test in multiple languages. I can't see this detailed anywhere in the documentation which suggests it is not possible at present.

I have tried adding the --lang argument when Chrome is launched but this does not seem to have any effect and Chrome still uses English. See the pluginsFile code below.

```<code>module.exports = (on, config) => {
  on('before:browser:launch', (browser = {}, args) => {
    if (browser.name === 'chrome') {
      args.push('--lang=de')
      return args
    }
  })
}
</code>```

I have also tried --lang=de-DE which also did not work.

答:
Besides adding command line options, you can also change browser preferences using Cypress' Browser Launch API (documentation). This allows you to override the Accept-Language header setting like this:

```<code>on('before:browser:launch', (browser, launchOptions) => {
  if (browser.family === 'chromium' && browser.name !== 'electron') {
    launchOptions.preferences.default.intl = { accept_languages: "nl" }
    return launchOptions
  }
}
</code>```

Note that the launchOptions.preferences.default object may be empty, so trying to assign to launchOptions.preferences.default.intl.accept_languages directly may fail.

For one of our projects, this was enough to get the site we were testing to appear in the right language. If you need more, there are more language settings you can try altering (see Chrome's source code and look for "intl").

On a side note, it looks like the --lang command line option only works on Windows, according to Chrome's documentation. On Mac, you are required to change your system preferences, and on Linux, you can use the LANGUAGE environment variable.

Title: Setting the browser language in Cypress

Body:
Is it possible to tell Cypress to launch Chrome with a certain language (e.g. German) as I have an application which I need to test in multiple languages. I can't see this detailed anywhere in the documentation which suggests it is not possible at present.

I have tried adding the --lang argument when Chrome is launched but this does not seem to have any effect and Chrome still uses English. See the pluginsFile code below.

module.exports = (on, config) => {
  on('before:browser:launch', (browser = {}, args) => {
    if (browser.name === 'chrome') {
      args.push('--lang=de')
      return args
    }
  })
}

I have also tried --lang=de-DE which also did not work.

Body:
Besides adding command line options, you can also change browser preferences using Cypress' Browser Launch API (documentation). This allows you to override the Accept-Language header setting like this:

on('before:browser:launch', (browser, launchOptions) => {
  if (browser.family === 'chromium' && browser.name !== 'electron') {
    launchOptions.preferences.default.intl = { accept_languages: "nl" }
    return launchOptions
  }
}

Note that the launchOptions.preferences.default object may be empty, so trying to assign to launchOptions.preferences.default.intl.accept_languages directly may fail.

For one of our projects, this was enough to get the site we were testing to appear in the right language. If you need more, there are more language settings you can try altering (see Chrome's source code and look for "intl").

On a side note, it looks like the --lang command line option only works on Windows, according to Chrome's documentation. On Mac, you are required to change your system preferences, and on Linux, you can use the LANGUAGE environment variable.


问:
How to change color of bootstrap glyphicon?
I want to change bootstrap glyphicon color to "yellow" because current color is showing in white that looks like Delete button. How can i change color of glyphicon-folder-close or use any other glyphicon that display folder image better ?

main.html

```<code><button type="button" class="btn btn-info btn-lg" ng-click="serverFiles()" style="margin-left: 10px"><span class="glyphicon glyphicon-folder-close"></span></button>
</code>```

答:
You can change color of the icon by directly specifying color name, however this will only apply to targeted icon.</p>

```<code><a href="#" class="glyphicon glyphicon-exclamation-sign"  style="color: red; font-size: 20px"></a>
</code>```

Body:
I want to change bootstrap glyphicon color to "yellow" because current color is showing in white that looks like Delete button. How can i change color of glyphicon-folder-close or use any other glyphicon that display folder image better ?

main.html

<button type="button" class="btn btn-info btn-lg" ng-click="serverFiles()" style="margin-left: 10px"></button>

Body:
You can change color of the icon by directly specifying color name, however this will only apply to targeted icon.

<a href="#" class="glyphicon glyphicon-exclamation-sign"  style="color: red; font-size: 20px"></a>


问:
how to POST jsonobject with volley
I am developing a chatroom and have a this request to get jsonArray from my db, and i want to do a POST jsonObject request to insert msg in db:

```<code>public void getMsg(){
    String url = "http://192.168.1.57/android/leggi.php";
    final TextView chatView =(TextView) findViewById(R.id.chat);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
                String msg = "";
                String mittente = "";
                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i<response.length(); i++) {
                        try {
                            mittente = response.getJSONObject(i).get("mittente").toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        try {
                            msg += (response.getJSONObject(i).get("mittente").toString() + ":\n" + response.getJSONObject(i).get("testo").toString() + "\n");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    chatView.setText(msg);
                    //chatView.setGravity(Gravity.RIGHT);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error

                }
            });

    MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest);

}
</code>```

can i use the same volley request??? or the request must have different params??? need help :P

答:
This depens on what your servers response is when POSTing the JSONObject.

If the server responses with an JSONArray, you can build your response the same way:

```<code>JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, INSERT_HERE, new Response.Listener<JSONArray>()
    ...
{
</code>```

And insert the JSON Object you want to post at the INSERT_HERE position.
If your response differs you need to change the type of Response.Listener<JSONArray>

Title: how to POST jsonobject with volley

Body:
I am developing a chatroom and have a this request to get jsonArray from my db, and i want to do a POST jsonObject request to insert msg in db:

public void getMsg(){
    String url = "http://192.168.1.57/android/leggi.php";
    final TextView chatView =(TextView) findViewById(R.id.chat);
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
                String msg = "";
                String mittente = "";
                @Override
                public void onResponse(JSONArray response) {

                    for (int i = 0; i<response.length(); i++) {
                        try {
                            mittente = response.getJSONObject(i).get("mittente").toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        try {
                            msg += (response.getJSONObject(i).get("mittente").toString() + ":\n" + response.getJSONObject(i).get("testo").toString() + "\n");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    chatView.setText(msg);
                    //chatView.setGravity(Gravity.RIGHT);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error

                }
            });

    MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest);

}

can i use the same volley request??? or the request must have different params??? need help :P

Body:
This depens on what your servers response is when POSTing the JSONObject.

If the server responses with an JSONArray, you can build your response the same way:

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
            (Request.Method.POST, url, INSERT_HERE, new Response.Listener<JSONArray>()
    ...
{

And insert the JSON Object you want to post at the INSERT_HERE position.
If your response differs you need to change the type of Response.Listener<JSONArray>


问:
Need suggestion to use suitable design pattern to create JAVA objects
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

```<code>public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }
</code>```

I am using getters and setters to create objects with new instance of each object.

```<code>  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);
</code>```

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

答:
You can create a constructor for classes Job and Step and inside them initialize the list like below:

```<code>public class Job {
    private  List<Jobparam> jobparam;
    private  List<Step> step;

    public Job() {
        this.jobparam = new ArrayList<Jobparam>();
        this.step = new ArrayList<Stepparam>();
    }
}
</code>```

For classes Stepparam and Jobparam you can create a base class and extends it, but it seems me that a Map<String, String> jobparam and a Map<String, String> step could be more appropriate of List<Jobparam> jobparam and List<Step> step, so you should not have to define the classes Stepparam and Jobparam. You can check map documentation at Map.

Body:
I am currently having below parent child relation java objects
JCL > JOB > steps > step > dd

Class looks like below

public class Jcl {
Private  Job job;
}

public class Job {

private  String jobname;
//Below is direct property of job object
 private  List<Jobparam> jobparam;
//Below is child object of the job object
 private  List<Step> step;

}

public class Step {
private  String stepname;
//Below is direct property of step object
 private  List<Stepparam> stepparam;
//Below is child object of the step object
 private  List<Ddstatement> ddstatement;
 }

public class Stepparam {
private  String name;
private  String value;
}

public class Jobparam{
private  String name;
private  String value;
 }

I am using getters and setters to create objects with new instance of each object.

  Job job = new Job();
    ArrayList<Jobparam> myList = new ArrayList<Jobparam>();

    job.getJobparam().addAll(myList);

   Step step = new Step();
    ArrayList<Stepparam> myList = new ArrayList<Stepparam>();

   jcl.getJob().getStep().add(step);

And also jobparam and stepparam have same property.(I want to reuse but donno how)
I feel I am creating each new object every time and this long coding can be avoided by java design pattern.
Any suggestion  how should I proceed to make simple code would be helpful.

Body:
You can create a constructor for classes Job and Step and inside them initialize the list like below:

public class Job {
    private  List<Jobparam> jobparam;
    private  List<Step> step;

    public Job() {
        this.jobparam = new ArrayList<Jobparam>();
        this.step = new ArrayList<Stepparam>();
    }
}

For classes Stepparam and Jobparam you can create a base class and extends it, but it seems me that a Map<String, String> jobparam and a Map<String, String> step could be more appropriate of List<Jobparam> jobparam and List<Step> step, so you should not have to define the classes Stepparam and Jobparam. You can check map documentation at Map.


问:
How to chrome web store validate manifest.json
I interest in developer dashboard of chrome web store
when I try to upload text file name manifest.json but inner file doesn't json format
I know that google uses any means to check the file structure
thank for suggest</p>

答:
Before uploading your extension to the webstore, it is really better to test by loading your extension as an "unpacked extension", which you can do by visiting chrome://extensions, expanding "Developer Mode" if it isn't already expanded, and then clicking "Load unpacked extension..."

Loading your extension will allow you to test it and discover issues, long before publishing it to test accounts or to other users. The Chrome extension developers' guide - manifest format documents what is permissible in the manifest. It is also necessary for the manifest to be standard JSON.

Also, I should point out that the Chrome webstore may disallow well-formatted code if it violates the terms (e.g. violating the branding guidelines or seeming to represent a  website you don't own).


问:
JpaSystemException when trying to fetch null values from Database
for some cases the master Id is null in DB and when I am fetching it it is giving me JPA system exception
So is there any annotation that would help to ignore the null values.
Method threw 'org.springframework.orm.jpa.JpaSystemException' exception.
got it when trying to fetch details from the database.

```<code>package com.merchant.orderDahsBoard.controller;

@RestController
@RequestMapping(value = "Dashboard")
public class OrderDashboardController {

@Autowired
private DashBoardService service;

ObjectMapper mapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

@PostMapping(value = "/getOrderDetails")
public OrderResponse getOrder(@PathParam(value = "id") Long id) {
    OrderResponse response = new OrderResponse();
    List<OrderMapping> orderMapping;
    Sale sale= new Sale();

    Purchase purchase = new Purchase();
    long saleId = 0;
    long purchaseId = 0;
    try{
        orderMapping = service.getOrderMapping(id);
        response.setOrderMapping(orderMapping);
        if (orderMapping != null) {
            for (OrderMapping order : orderMapping) {
                switch (order.getORDERTYPE()) {
                    case CART:
                        break;
                    case SALE:
                        saleId = order.getORDERID();
                        break;
                    case PURCHASE:
                        purchaseId = order.getORDERID();
                        break;

                }
            }

            if(saleId!=0){
                sale = service.getSale(saleId);
                response.setSale(sale);
            }

        }
    }
    catch(Exception e){
        log.error("Exception occured "+e);
    }
    return response;
}

}
</code>```

below is the @Entity Class used in my project

```<code>@Entity
@Table(name = "ORDERMAPPING")
@Getter
@Setter
@ToString
public class OrderMapping {
@Id
@Column(name = "ORDERMAPPINGID")
private long ORDERMAPPINGID;

@Column(name = "MASTERID")
private long MASTERID;

@Column(name = "ORDERID")
private long ORDERID;

@Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;

@Column(name = "ADDEDDATE")
private String ADDEDDATE;

@Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;

@Column(name = "CARTID")
private long CARTID;

@Column(name = "PCARTID")
private long PCARTID;

}
</code>```

答:
Instead of primitive data types try using the wrapper classes for the same. The following code can help you better.

Use Long isntead of long

```<code>@Entity
@Table(name = "ORDERMAPPING")
@Getter
@Setter
@ToString
public class OrderMapping {
@Id
@Column(name = "ORDERMAPPINGID")
private Long ORDERMAPPINGID;

@Column(name = "MASTERID")
private Long MASTERID;

@Column(name = "ORDERID")
private Long ORDERID;

@Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;

@Column(name = "ADDEDDATE")
private String ADDEDDATE;

@Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;

@Column(name = "CARTID")
private Long CARTID;

@Column(name = "PCARTID")
private Long PCARTID;

}
</code>```

Body:
for some cases the master Id is null in DB and when I am fetching it it is giving me JPA system exception
So is there any annotation that would help to ignore the null values.
Method threw 'org.springframework.orm.jpa.JpaSystemException' exception.
got it when trying to fetch details from the database.

package com.merchant.orderDahsBoard.controller;

@RestController
@RequestMapping(value = "Dashboard")
public class OrderDashboardController {

@Autowired
private DashBoardService service;

ObjectMapper mapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

@PostMapping(value = "/getOrderDetails")
public OrderResponse getOrder(@PathParam(value = "id") Long id) {
    OrderResponse response = new OrderResponse();
    List<OrderMapping> orderMapping;
    Sale sale= new Sale();

    Purchase purchase = new Purchase();
    long saleId = 0;
    long purchaseId = 0;
    try{
        orderMapping = service.getOrderMapping(id);
        response.setOrderMapping(orderMapping);
        if (orderMapping != null) {
            for (OrderMapping order : orderMapping) {
                switch (order.getORDERTYPE()) {
                    case CART:
                        break;
                    case SALE:
                        saleId = order.getORDERID();
                        break;
                    case PURCHASE:
                        purchaseId = order.getORDERID();
                        break;

                }
            }

            if(saleId!=0){
                sale = service.getSale(saleId);
                response.setSale(sale);
            }

        }
    }
    catch(Exception e){
        log.error("Exception occured "+e);
    }
    return response;
}

}

below is the @Entity Class used in my project

@Entity
@Table(name = "ORDERMAPPING")
@Getter
@Setter
@ToString
public class OrderMapping {
@Id
@Column(name = "ORDERMAPPINGID")
private long ORDERMAPPINGID;

@Column(name = "MASTERID")
private long MASTERID;

@Column(name = "ORDERID")
private long ORDERID;

@Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;

@Column(name = "ADDEDDATE")
private String ADDEDDATE;

@Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;

@Column(name = "CARTID")
private long CARTID;

@Column(name = "PCARTID")
private long PCARTID;

}

Body:
Instead of primitive data types try using the wrapper classes for the same. The following code can help you better.

Use Long isntead of long

@Entity
@Table(name = "ORDERMAPPING")
@Getter
@Setter
@ToString
public class OrderMapping {
@Id
@Column(name = "ORDERMAPPINGID")
private Long ORDERMAPPINGID;

@Column(name = "MASTERID")
private Long MASTERID;

@Column(name = "ORDERID")
private Long ORDERID;

@Enumerated(EnumType.ORDINAL)
private OrderTypeEnum ORDERTYPE;

@Column(name = "ADDEDDATE")
private String ADDEDDATE;

@Column(name = "LASTUPDATEDDATE")
private String LASTUPDATEDDATE;

@Column(name = "CARTID")
private Long CARTID;

@Column(name = "PCARTID")
private Long PCARTID;

}


问:
State information corrupted after dynamically adding control
In my asp .net form, I refresh a control using Ajax through the AjaxPro library. However, after doing so...causing any "normal" postback results in a yellow screen (Complete error after the message)

I've set the following Page properties in web.config without any luck

```<code><pages enableSessionState="true" enableViewState="false" enableEventValidation="false" enableViewStateMac="false">
</code>```

I've also tried generating a machine key as some solutions suggested online. But that doesn't help either.

Any suggestions?

*******************Contents of ASP .NET yellow screen************************************

```<code>Server Error in '/' Application.
The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.

Source Error:

[No relevant source lines]

Source File: c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\c89baa89\d92b83c5\App_Web_tahnujzf.4.cs    Line: 0

Stack Trace:

[FormatException: Invalid character in a Base-64 string.]
   System.Convert.FromBase64String(String s) +0
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +72
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
   System.Web.UI.HiddenFieldPageStatePersister.Load() +113

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port: 49736
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
    ViewState: /wEPDwULLTE0OTczNDQ1NjdkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYGBSljdGwwMCR1c3JTaG9wcGluZ0xpc3QkdXNyU2hvcHBpbmdMaXN0X3duZAUaY3RsMDAkdXNyU2hvcHBpbmdMaXN0JF9tZ3IFVGN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAwJGNieEFsbAVcY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kY3RsMDAkXyRycHRMaW5lSXRlbXMkY3RsMDEkaW1nQnRuQ2F0ZWdvcnkFWmN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAxJGNieFNlbGVjdGlvbgVoY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kdXNyUHJvZHVjdFF1aWNrVmlld1BvcHVwJHVzclByb2R1Y3RRdWlja1ZpZXdQb3B1cF93bmQFG2N0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMA8XAgULQ3VycmVudFZpZXcFCFZpZXdDYXJ0BQ1BY3RpdmVWaWV3U2V0Z2Q=,/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgMFIWN0bDAxJF8kc...]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]
</code>```

答:
Regular Expression for replace the viewstate:
returnvalue = Regex.Replace(html, @"<[/]?(form|[ovwxp]:\w+)[^>]*?>", "", RegexOptions.IgnoreCase);</p>

Body:
In my asp .net form, I refresh a control using Ajax through the AjaxPro library. However, after doing so...causing any "normal" postback results in a yellow screen (Complete error after the message)

I've set the following Page properties in web.config without any luck

<pages enableSessionState="true" enableViewState="false" enableEventValidation="false" enableViewStateMac="false">

I've also tried generating a machine key as some solutions suggested online. But that doesn't help either.

Any suggestions?

*******************Contents of ASP .NET yellow screen************************************

Server Error in '/' Application.
The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.

Source Error:

[No relevant source lines]

Source File: c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\c89baa89\d92b83c5\App_Web_tahnujzf.4.cs    Line: 0

Stack Trace:

[FormatException: Invalid character in a Base-64 string.]
   System.Convert.FromBase64String(String s) +0
   System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +72
   System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
   System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37
   System.Web.UI.HiddenFieldPageStatePersister.Load() +113

[ViewStateException: Invalid viewstate.
    Client IP: 127.0.0.1
    Port: 49736
    User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)
    ViewState: /wEPDwULLTE0OTczNDQ1NjdkGAIFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYGBSljdGwwMCR1c3JTaG9wcGluZ0xpc3QkdXNyU2hvcHBpbmdMaXN0X3duZAUaY3RsMDAkdXNyU2hvcHBpbmdMaXN0JF9tZ3IFVGN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAwJGNieEFsbAVcY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kY3RsMDAkXyRycHRMaW5lSXRlbXMkY3RsMDEkaW1nQnRuQ2F0ZWdvcnkFWmN0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMCRfJHVzclZpZXdDYXJ0Q29udHJvbCRfJGN0bDAwJF8kcnB0TGluZUl0ZW1zJGN0bDAxJGNieFNlbGVjdGlvbgVoY3RsMDAkUGxhY2VIb2xkZXJNYWluJGN0bDAwJF8kdXNyVmlld0NhcnRDb250cm9sJF8kdXNyUHJvZHVjdFF1aWNrVmlld1BvcHVwJHVzclByb2R1Y3RRdWlja1ZpZXdQb3B1cF93bmQFG2N0bDAwJFBsYWNlSG9sZGVyTWFpbiRjdGwwMA8XAgULQ3VycmVudFZpZXcFCFZpZXdDYXJ0BQ1BY3RpdmVWaWV3U2V0Z2Q=,/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgMFIWN0bDAxJF8kc...]

[HttpException (0x80004005): The state information is invalid for this page and might be corrupted.]


问:
Linker can't find symbols for static field accessed in virtual class c++
I was improving my visitor pattern code in c++ which originally looked like the code right below, in order to get rid of the unnecessary part where the visitor needs to pass itself to the accept void.

I came up with a simple solution which "turns" the parameter into a static field so I can initialise the field right before I ever use accept.

Forgive me but I need to do this even if it will be very ugly.

Old Code:

class A_Child;
class B_Child;

class Father {
    public:
    virtual ~Father() = default;
    class Visitor {
        public:
        virtual void visitChildA(A_Child * child) = 0;
        virtual void visitChildB(B_Child * child) = 0;
    };
    virtual void accept(Visitor * visitor) = 0;
};

class A_Child: public Father {
    public: /* A Child Stuff */
    void accept(Visitor * visitor) override;
};

class B_Child: public Father {
    public: /* B Child Stuff */
    void accept(Visitor * visitor) override;
};

A_Child::accept(Visitor * visitor) { visitor -> visitChildA(this); }
B_Child::accept(Visitor * visitor) { visitor -> visitChildB(this); }

```

<p><strong>New Code:</strong></p>

<pre class="lang-cpp prettyprint-override"><code>class Father {
    public:
    virtual ~Father() = default;
    class Visitor {
        public:
        virtual void visitChildA(A_Child * child) = 0;
        virtual void visitChildB(B_Child * child) = 0;
    };
    static Visitor * visitor;
    virtual void accept() = 0;
};

// Outside, (assuming NewVisitor: public Father::Visitor):

void NewVisitor::DoStuff(Father * child) {
    Father::visitor = this;
    child -> accept();
}

</code>```

Linker Complaints:

My linker is not happy about it and it gives me the following output:

```<code>Undefined symbols for architecture x86_64:
  "Father::visitor", referenced from:
      Child_A::accept() in Father.o
      Child_B::accept() in Father.o
ld: symbol(s) not found for architecture x86_64
</code>```

Does anyone know why is this happening?
Am I breaking some mysterious OOP rule?

答:
You have to define the variable some where. A line like

```<code>Visitor* Father::visitor = nullptr;
</code>```

in your .cpp file at global scope should do.

Body:
I was improving my visitor pattern code in c++ which originally looked like the code right below, in order to get rid of the unnecessary part where the visitor needs to pass itself to the accept void.

I came up with a simple solution which "turns" the parameter into a static field so I can initialise the field right before I ever use accept.

Forgive me but I need to do this even if it will be very ugly.

Old Code:

class A_Child;
class B_Child;

class Father {
    public:
    virtual ~Father() = default;
    class Visitor {
        public:
        virtual void visitChildA(A_Child * child) = 0;
        virtual void visitChildB(B_Child * child) = 0;
    };
    virtual void accept(Visitor * visitor) = 0;
};

class A_Child: public Father {
    public: /* A Child Stuff */
    void accept(Visitor * visitor) override;
};

class B_Child: public Father {
    public: /* B Child Stuff */
    void accept(Visitor * visitor) override;
};

A_Child::accept(Visitor * visitor) { visitor -> visitChildA(this); }
B_Child::accept(Visitor * visitor) { visitor -> visitChildB(this); }

New Code:

class Father {
    public:
    virtual ~Father() = default;
    class Visitor {
        public:
        virtual void visitChildA(A_Child * child) = 0;
        virtual void visitChildB(B_Child * child) = 0;
    };
    static Visitor * visitor;
    virtual void accept() = 0;
};

// Outside, (assuming NewVisitor: public Father::Visitor):

void NewVisitor::DoStuff(Father * child) {
    Father::visitor = this;
    child -> accept();
}

Linker Complaints:

My linker is not happy about it and it gives me the following output:

Undefined symbols for architecture x86_64:
  "Father::visitor", referenced from:
      Child_A::accept() in Father.o
      Child_B::accept() in Father.o
ld: symbol(s) not found for architecture x86_64

Does anyone know why is this happening?
Am I breaking some mysterious OOP rule?

Body:
You have to define the variable some where. A line like

Visitor* Father::visitor = nullptr;

in your .cpp file at global scope should do.


问:
Ask about char in array
example

```<code>char names[2][5] = {"john","boy"};
</code>```

I want to ask about char 2 dimension array in c, in [2] i mean, it's explaining about total element of array, and [5] i mean, it's explaining about length of character in array

So, is it true how to use array 2 dimension in c ?

Sorry for my bad english

Title: Ask about char in array

Body:
example

char names[2][5] = {"john","boy"};

I want to ask about char 2 dimension array in c, in [2] i mean, it's explaining about total element of array, and [5] i mean, it's explaining about length of character in array

So, is it true how to use array 2 dimension in c ?

Sorry for my bad english

Body:
char names[2][5] = {"john","boy"};

names is a multi-dimensional char array with the height of 2 and the width 5:

 __________________________________________________________________
│    j      │    o       │    h       │    n        │     \0       │  // 5 char elements, 1.dimension
│names[0][0]│ names[0][1]│ names[0][2]│ names[0][3] │ names[0][4]  │
│___________│____________│____________│_____________│______________│
│    b      │    o       │    y       │    \0       │     \0       │  // 5 char elements, 2.dimension
│names[1][0]│ names[1][1]│ names[1][2]│ names[1][3] │ names[1][4]  │
│___________│____________│____________│_____________│______________│

Sorry, for the simple example but this might help you.


问:
Emgucv ver 4.2 on Azure Function
I want to use EmguCv ver 4.2 in an Azure Function V3

I have created an Azure Function v3(.Net Core) application

Installed Emgu.Cv ver 4.2.0.3636 from Nuget

Installed Emgu.CV.Runtime.windows ver 4.2.0.3636 also from Nuget

```<code>[FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            SetPathOfEmgu();
            var image = new Image<Bgr, byte>(256, 256);
        }
        catch (Exception ee)
        {
            return (ActionResult)new BadRequestObjectResult(ee.Message);
            throw;
        }

        return (ActionResult)new OkObjectResult($"All is well");
    }

    public static void SetPathOfEmgu()
    {
        string pathValue = System.Environment.GetEnvironmentVariable("PATH");
        string emguPath = @"D:\home\site\wwwroot\x64";
        var paths = pathValue.Split(';').Where(o => o != "").ToList();
        paths.Add(emguPath);
        pathValue = string.Join(";", paths.Distinct().ToArray()) + ";";

        System.Environment.SetEnvironmentVariable("PATH", pathValue);
    }
</code>```

Running in Debug i get:"All is well"

Running on Azure i get:"Unable to load DLL 'cvextern' or one of its dependencies: The specified module could not be found. (0x8007007E)"
at line "var image = new Image(256, 256);"

Question: How do I run Emgucv from Azure Function V3?

@Stuard:
From:Emgu 42 Function V3.deps.json

```<code>{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v3.0",
    "signature": ""
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v3.0": {
      "Emgu 42 Function V3/1.0.0": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636",
          "Emgu.CV.runtime.windows": "4.2.0.3636",
          "Microsoft.NET.Sdk.Functions": "3.0.1"
        },
        "runtime": {
          "Emgu 42 Function V3.dll": {}
        }
      },
      "Emgu.CV/4.2.0.3636": {
        "runtime": {
          "lib/netstandard2.0/Emgu.CV.World.NetStandard.dll": {
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          }
        }
      },
      "Emgu.CV.runtime.windows/4.2.0.3636": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636"
        }
      },
</code>```

答:
With the new version of emgucv 4.2.0.3662 there has been an update to handle the problem described above.
Install Nuget Emgu.CV (V.4.2.0.3662 or above)
Install Nuget Emgu.cv.runtime.windows 4.2.0.3662

And it all works!

Title: Emgucv ver 4.2 on Azure Function

Body:
I want to use EmguCv ver 4.2 in an Azure Function V3

I have created an Azure Function v3(.Net Core) application

Installed Emgu.Cv ver 4.2.0.3636 from Nuget

Installed Emgu.CV.Runtime.windows ver 4.2.0.3636 also from Nuget

[FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            SetPathOfEmgu();
            var image = new Image<Bgr, byte>(256, 256);
        }
        catch (Exception ee)
        {
            return (ActionResult)new BadRequestObjectResult(ee.Message);
            throw;
        }

        return (ActionResult)new OkObjectResult($"All is well");
    }

    public static void SetPathOfEmgu()
    {
        string pathValue = System.Environment.GetEnvironmentVariable("PATH");
        string emguPath = @"D:\home\site\wwwroot\x64";
        var paths = pathValue.Split(';').Where(o => o != "").ToList();
        paths.Add(emguPath);
        pathValue = string.Join(";", paths.Distinct().ToArray()) + ";";

        System.Environment.SetEnvironmentVariable("PATH", pathValue);
    }

Running in Debug i get:"All is well"

Running on Azure i get:"Unable to load DLL 'cvextern' or one of its dependencies: The specified module could not be found. (0x8007007E)"
at line "var image = new Image(256, 256);"

Question: How do I run Emgucv from Azure Function V3?

@Stuard:
From:Emgu 42 Function V3.deps.json

{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v3.0",
    "signature": ""
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v3.0": {
      "Emgu 42 Function V3/1.0.0": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636",
          "Emgu.CV.runtime.windows": "4.2.0.3636",
          "Microsoft.NET.Sdk.Functions": "3.0.1"
        },
        "runtime": {
          "Emgu 42 Function V3.dll": {}
        }
      },
      "Emgu.CV/4.2.0.3636": {
        "runtime": {
          "lib/netstandard2.0/Emgu.CV.World.NetStandard.dll": {
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          }
        }
      },
      "Emgu.CV.runtime.windows/4.2.0.3636": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636"
        }
      },


问:
jQuery focus on input text with name same as div id
I have several links. When I click a link I want jQuery to give focus to the corresponding input.

Links:

```<code><a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_38">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_39">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_34">Focus</a>
</code>```

Input fields:

```<code><input type="text" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />
</code>```

jQuery (not working):

```<code><script>
$(function() {
    $('.copy_go_to_input_field').click(function() {
        var field = $(this).data('divid');
                $('[name=""+ field + ""]').focus();

        return false;
        });
});
</script>
</code>```

答:
The first thing that pops up is that it seems you misused the quotes in the name selector.

```<code><script>
$(function() {
    $('.copy_go_to_input_field').on('click', function() {
        var field = $(this).data('divid');
        $('[name="'+ field + '"]').focus();

        return false;
    });
});
</script>
</code>```

Also, you should try to use .on('click', function(){}) instead of the .click(function(){}). You can see why here: Difference between .on('click') vs .click()

You can check the solution posted by @BenM which is much cleaner than mine. The one I posted provides a fix for your JS. But for the functionality you need it's much cleaner to use what @BenM did.

Body:
I have several links. When I click a link I want jQuery to give focus to the corresponding input.

Links:

Focus
Focus
Focus

Input fields:

<input type="text" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />

jQuery (not working):

Body:
The first thing that pops up is that it seems you misused the quotes in the name selector.

<script>
$(function() {
    $('.copy_go_to_input_field').on('click', function() {
        var field = $(this).data('divid');
        $('[name="'+ field + '"]').focus();

        return false;
    });
});
</script>

Also, you should try to use .on('click', function(){}) instead of the .click(function(){}). You can see why here: Difference between .on('click') vs .click()

You can check the solution posted by @BenM which is much cleaner than mine. The one I posted provides a fix for your JS. But for the functionality you need it's much cleaner to use what @BenM did.


问:
How to acces all UI elements from CarPlay with Xcode UI Recording?
Why can the UI recording from Xcode accces elements like the status bar from CarPlay but not the other elements like the buttons on the map or buttons in an navigation alert? </p>

答:
XCTest built-in recorder is not designed to record interactions with CarPlay display properly.

You should probably inspect elements with an Accessibility Inspector or app.debugDescription


问:
How to use lambda if else in map() on list in python?
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

```<code>l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])
</code>```

it seems that it should work but its giving syntax error

What is the issue here?

答:
You probably need filter here and use lambda x : x == "apple".

Ex:

```<code>l = list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))
print(l)
</code>```

Body:
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

it seems that it should work but its giving syntax error

What is the issue here?

Body:
You probably need filter here and use lambda x : x == "apple".

Ex:

l = list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))
print(l)


问:
How to wait until file is uploaded using Axios
I'm working on a Reactjs project where I can upload and download files.

But when I upload a file, the request PUT from Axios is completed before the file is fully uploaded to my database.
I use the onUploadProgress from Axios and it shows directly 100% after I click on the upload button whereas the file is not uploaded yet.

It even seems that the upload of the file on the back side is only starts once the progress bar reaches 100%.
I don't know how to correctly synchronize the progress bar with the file uploading.

My code

Front

```<code>  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .put("http://localhost:5000/api/files/upload", data, {
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }
</code>```

Back

```<code>export const uploadFile = (req, res) => {
  const myFile = (Array.isArray(req.files.file)
    ? req.files.file
    : [req.files.file]
  ).filter(e => e);
  // upload file(s) to directory
  for (let i = 0; i < myFile.length; i++) {
    myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
    });
    // save file(s) to database
    Upload.create({
      type: myFile[i].mimetype,
      name: myFile[i].name,
      data: myFile[i].data
    });
  }
  res.send("file uploaded !");
};
</code>```

By the way I'm using https://www.npmjs.com/package/express-fileupload for file upload

EDIT

```<code>  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        },
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }
</code>```

答:
You are setting state as soon as you're hitting the API, the reason you're getting 100% as soon as the API hits. I would suggest you to pass "status = success" or "status = 201" from server side So that you can wait for a response in client side. i.e :-

```<code>onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        }
      })
      .then(res => {
        if(res.status === 'success') {
              onUploadProgress: ProgressEvent => {
               this.setState({
                 loaded: Math.round(
                (ProgressEvent.loaded * 100) / ProgressEvent.total
              )
           });
         }
        }
        console.log("File(s) uploaded", res);
      });
  }
</code>```

Body:
I'm working on a Reactjs project where I can upload and download files.

But when I upload a file, the request PUT from Axios is completed before the file is fully uploaded to my database.
I use the onUploadProgress from Axios and it shows directly 100% after I click on the upload button whereas the file is not uploaded yet.

It even seems that the upload of the file on the back side is only starts once the progress bar reaches 100%.
I don't know how to correctly synchronize the progress bar with the file uploading.

My code

Front

  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .put("http://localhost:5000/api/files/upload", data, {
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }

Back

export const uploadFile = (req, res) => {
  const myFile = (Array.isArray(req.files.file)
    ? req.files.file
    : [req.files.file]
  ).filter(e => e);
  // upload file(s) to directory
  for (let i = 0; i < myFile.length; i++) {
    myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
      if (err) {
        return res.status(500).send(err);
      }
    });
    // save file(s) to database
    Upload.create({
      type: myFile[i].mimetype,
      name: myFile[i].name,
      data: myFile[i].data
    });
  }
  res.send("file uploaded !");
};

By the way I'm using https://www.npmjs.com/package/express-fileupload for file upload

EDIT

  onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        },
        onUploadProgress: ProgressEvent => {
          this.setState({
            loaded: Math.round(
              (ProgressEvent.loaded * 100) / ProgressEvent.total
            )
          });
        }
      })
      .then(res => {
        console.log("File(s) uploaded", res);
      });
  }

Body:
You are setting state as soon as you're hitting the API, the reason you're getting 100% as soon as the API hits. I would suggest you to pass "status = success" or "status = 201" from server side So that you can wait for a response in client side. i.e :-

onUpload() {
    const data = new FormData();
    for (var i = 0; i < this.state.selectedFile.length; i++) {
      data.append("file", this.state.selectedFile[i]);
    }
    axios
      .post("http://localhost:5000/api/files/upload", data, {
        headers: {
          "Content-type": "multipart/form-data"
        }
      })
      .then(res => {
        if(res.status === 'success') {
              onUploadProgress: ProgressEvent => {
               this.setState({
                 loaded: Math.round(
                (ProgressEvent.loaded * 100) / ProgressEvent.total
              )
           });
         }
        }
        console.log("File(s) uploaded", res);
      });
  }


问:
Programmatically scrolling to and coloring a UITableViewCell at runtime
I have UITableViewController which contains a list of items. Now, I want the list to be automatically scrolled to a item (index = bestOne ) once the view appears. Meanwhile I want the item to be colored into red and be labeled as Marked.

My code roughly achieves what I want. But, I actually see more than one red items iterating: every 10 items, there is a red item.

I am quite new to iphone development, I figure it might have something to do with reusable cells. But I am not exactly sure why. Can anybody suggest one way to solve this issue? Thanks in advance.

```<code>(void)viewDidAppear:(BOOL)animated
{
    if (self.bestOne != -1)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0];
        [self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == self.bestOne)
    {
        cell.detailTextLabel.text = @"Marked";
        cell.textLabel.textColor = [UIColor redColor];
    }
    return cell;
}
</code>```

答:
You are right about the reusable cells part.

Your code should be something like –

```<code>cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
if (indexPath.row == self.bestOne)
{
    cell.detailTextLabel.text = @"Marked";
    cell.textLabel.textColor = [UIColor redColor];
}
else
{
    cell.detailTextLabel.text = @"";
}
</code>```

On reuse, you get the exact cell that you had set before. While other cells are undistinguishable, the marked cell stands out with its specifically set detailTextLabel. You need to reset it before you can use it as an unmarked cell.

Body:
I have UITableViewController which contains a list of items. Now, I want the list to be automatically scrolled to a item (index = bestOne ) once the view appears. Meanwhile I want the item to be colored into red and be labeled as Marked.

My code roughly achieves what I want. But, I actually see more than one red items iterating: every 10 items, there is a red item.

I am quite new to iphone development, I figure it might have something to do with reusable cells. But I am not exactly sure why. Can anybody suggest one way to solve this issue? Thanks in advance.

(void)viewDidAppear:(BOOL)animated
{
    if (self.bestOne != -1)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.bestOne inSection:0];
        [self.tableView scrollToRowAtIndexPath: atScrollPosition: animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
    if (indexPath.row == self.bestOne)
    {
        cell.detailTextLabel.text = @"Marked";
        cell.textLabel.textColor = [UIColor redColor];
    }
    return cell;
}

Body:
You are right about the reusable cells part.

Your code should be something like –

cell.textLabel.text = [self.array objectAtIndex:indexPath.row];
if (indexPath.row == self.bestOne)
{
    cell.detailTextLabel.text = @"Marked";
    cell.textLabel.textColor = [UIColor redColor];
}
else
{
    cell.detailTextLabel.text = @"";
}

On reuse, you get the exact cell that you had set before. While other cells are undistinguishable, the marked cell stands out with its specifically set detailTextLabel. You need to reset it before you can use it as an unmarked cell.


问:
Recursive function return None
I have a function that runs over an API output and should return the path to specific key.
Here is the function:

```<code>def find_path(obj, val, path=''):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            return find_path(v, val, path + f'[{k!r}]')
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            return find_path(v, val, path + f'[{i!r}]')
</code>```

API output Example:

```<code>ex = {'Resources': [{'uschemas': {'emailSelfUpdateAllowed': True,
                                  'emailVerificationDays': 30,
                                  'approvers': {'manager': False,
                                                'secondLevelManager': False,
                                                'owner': False,
                                                'workGroup': 'workgroup'}}}]}
</code>```

When I run the function I get None:

```<code>bla = find_path(ex, 'approvers')
print(bla)
>>> None
</code>```

I expect to get:

```<code>['Resources'][0]['uschemas']['approvers']
</code>```

I can only get the expected output when I am using the function with print instead of return.

Can someone help me to understand why? and how can I make it work with returns and not prints because I need to use its output.

Thank you.

答:
You need to return value after the for loop is done, this is the value returns from the recursion, if you don't have anything it will return None

```<code>def find_path(obj, val, path=''):
    p = []
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            p = find_path(v, val, path + f'[{k!r}]')
        return p
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            p = find_path(v, val, path + f'[{i!r}]')
        return p

bla = find_path(ex, 'approvers')
print(bla) # ['Resources'][0]['uschemas']['approvers']
</code>```

Title: Recursive function return None

Body:
I have a function that runs over an API output and should return the path to specific key.
Here is the function:

def find_path(obj, val, path=''):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            return find_path(v, val, path + f'[{k!r}]')
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            return find_path(v, val, path + f'[{i!r}]')

API output Example:

ex = {'Resources': [{'uschemas': {'emailSelfUpdateAllowed': True,
                                  'emailVerificationDays': 30,
                                  'approvers': {'manager': False,
                                                'secondLevelManager': False,
                                                'owner': False,
                                                'workGroup': 'workgroup'}}}]}

When I run the function I get None:

bla = find_path(ex, 'approvers')
print(bla)
>>> None

I expect to get:

['Resources'][0]['uschemas']['approvers']

I can only get the expected output when I am using the function with print instead of return.

Can someone help me to understand why? and how can I make it work with returns and not prints because I need to use its output.

Thank you.

Body:
You need to return value after the for loop is done, this is the value returns from the recursion, if you don't have anything it will return None

def find_path(obj, val, path=''):
    p = []
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k == val:
                return f'{path}[{k!r}]'
            p = find_path(v, val, path + f'[{k!r}]')
        return p
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            if v == val:
                return f'{path}[{i!r}]'
            p = find_path(v, val, path + f'[{i!r}]')
        return p

bla = find_path(ex, 'approvers')
print(bla) # ['Resources'][0]['uschemas']['approvers']


问:
Expected behavior of Jenkin's Node Label Plugin - Not running on all nodes
I am trying to use the plugin Node label plugin, adding a Label parameter and selecting the Run on all nodes matching label in a pipeline job.
But this only runs on  one of the nodes even though nodes are discover-able by Show nodes in the build page.

I have also tried using the All Nodes for Label Factory option the same plugin provides, but this fails when I want more than one label in the jobs, as described here: https://issues.jenkins-ci.org/browse/JENKINS-59431  (including latest comment)

After many hours spent on google I have come to believe that when I use Label with run in all all of the nodes will run concurrently, the only difference with other examples I've seen online is the fact that they are not pipeline jobs, so concurrent jobs is a selectable option, compared to the Do not allow concurrent builds option in pipeline (which is not selected)

答:
In case anyone had this problem, I decided to answer this question.

I made the trigger job a pipeline, where I build the downstream job with 2 parameters inside a loop through all the nodes with label:

```<code>def nodeArray = nodesByLabel label:"${params.labeled}", offline: false
for(item in nodeArray) {
    build job:"DownstreamJob", parameters:[
            [$class: 'LabelParameterValue', name: 'node', label: "${item}"],
            string(name:"nodeToRunIn", value:"${item}")
        ], propagate: false, wait:false
}
</code>```

And in the DownstreamJob I start with:

```<code>node (params.nodeToRunIn) {
</code>```

May not be the nicest solution, as that would have been to have the plugin work as expected, but this is currently working.

Body:
In case anyone had this problem, I decided to answer this question.

I made the trigger job a pipeline, where I build the downstream job with 2 parameters inside a loop through all the nodes with label:

def nodeArray = nodesByLabel label:"${params.labeled}", offline: false
for(item in nodeArray) {
    build job:"DownstreamJob", parameters:[
            [$class: 'LabelParameterValue', name: 'node', label: "${item}"],
            string(name:"nodeToRunIn", value:"${item}")
        ], propagate: false, wait:false
}

And in the DownstreamJob I start with:

node (params.nodeToRunIn) {

May not be the nicest solution, as that would have been to have the plugin work as expected, but this is currently working.


问:
What is MediaMetadataRetriever.BitmapParams params in getFramesAtIndex()?
I am trying to retrieve all the frames from a video. For that I am using getFramesAtIndex() in MediaMetadataRetriever.

I am not sure about the third parameter in the function, which is MediaMetadataRetriever.BitmapParams params.
Can you explain the third parameter with an example. I tried to look in Android documentation, but there are no examples.

答:
As per the docs for MediaMetadataRetriever#getFramesAtIndex:

This method retrieves a consecutive set of video frames starting at
  the specified index. It should only be called after
  setDataSource(Context, Uri). If the caller intends to retrieve more
  than one consecutive video frames, this method is preferred over
  getFrameAtIndex(int,
  android.media.MediaMetadataRetriever.BitmapParams) for efficiency.
  After the bitmaps are returned, you can query the actual parameters
  that were used to create the bitmaps from the BitmapParams argument,
  for instance to query the bitmap config used for the bitmaps with
  BitmapParams#getActualConfig.

The bitmap params allows you to specify a preferred bitmap config to be returned.

Example:

```<code>val bitmapParams = MediaMetadataRetriever.BitmapParams()

// Set your preferred bitmap config e.g.
bitmapParams.preferredConfig = Bitmap.Config.RGB_565

val frameIndex = 0
val numFrames = 10
val frames = mediaMetadataRetriever.getFramesAtIndex(frameIndex, numFrames, bitmapParams)

// Can now query actual config of bitmap frames returned
bitmapParams.actualConfig
</code>```

Body:
As per the docs for MediaMetadataRetriever#getFramesAtIndex:

This method retrieves a consecutive set of video frames starting at
  the specified index. It should only be called after
  setDataSource(Context, Uri). If the caller intends to retrieve more
  than one consecutive video frames, this method is preferred over
  getFrameAtIndex(int,
  android.media.MediaMetadataRetriever.BitmapParams) for efficiency.
  After the bitmaps are returned, you can query the actual parameters
  that were used to create the bitmaps from the BitmapParams argument,
  for instance to query the bitmap config used for the bitmaps with
  BitmapParams#getActualConfig.

The bitmap params allows you to specify a preferred bitmap config to be returned.

Example:

val bitmapParams = MediaMetadataRetriever.BitmapParams()

// Set your preferred bitmap config e.g.
bitmapParams.preferredConfig = Bitmap.Config.RGB_565

val frameIndex = 0
val numFrames = 10
val frames = mediaMetadataRetriever.getFramesAtIndex(frameIndex, numFrames, bitmapParams)

// Can now query actual config of bitmap frames returned
bitmapParams.actualConfig


答:
pass is not a value, so you can't use it in an expression. You could use None, but then you end up with ['apple', None, None] rather than just ['apple'], so you have to filter the Nones like this:

```<code>l = filter(lambda x: x is not None, map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry']))
</code>```

A cleaner solution would be to use list comprehension:

```<code>l = [ x for x in ['apple', 'banana', 'cherry'] if x == 'apple' ]
</code>```

Title: How to use lambda if else in map() on list in python?

Body:
pass is not a value, so you can't use it in an expression. You could use None, but then you end up with ['apple', None, None] rather than just ['apple'], so you have to filter the Nones like this:

l = filter(lambda x: x is not None, map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry']))

A cleaner solution would be to use list comprehension:

l = [ x for x in ['apple', 'banana', 'cherry'] if x == 'apple' ]