问:
Angular Error : Type 'void' is not assignable to type 'AbstractControl'
I got an error when setting the default value of my FormControl, but it returns an error like this :

error TS2322: Type 'void' is not assignable to type 'AbstractControl'

This is my .ts file :

```<code>  profileForm  = new FormGroup({
    username   : new FormControl().setValue("a"),
    firstname  : new FormControl().setValue("a"),
    lastname   : new FormControl().setValue("a"),
    email      : new FormControl().setValue("a"),
    password   : new FormControl().setValue("a"),
  });
</code>```

Help me to solve this.

答:
FormControl.setValue() returns a void - which means it returns nothing.

You're effectively trying to create an object with the following signature:

```<code>{
  username: void,
  firstname: void,
  ...
}
</code>```

Which is both meaningless and invalid for constructing a FormGroup. FormGroup expects an object with the following signature in its constructor:

```<code>{
  [key: string]: FormControl
}
</code>```

So something more like:

```<code>{
  username: new FormControl(),
  firstname: new FormControl(),
  ...
}
</code>```

If you want to access the form controls programmatically, you could do this:

```<code>const formControls = {
  username: new FormControl('a'),
  firstname: new FormControl('a'),
  ...
};

// or this
formControls.username.setValue('a');
formControls.firstname.setValue('a');
// ... etc

profileForm = new FormGroup({
  username: formControls.username,
  firstname: formControls.firstname,
  ...
});
</code>```

Body:
I got an error when setting the default value of my FormControl, but it returns an error like this :

error TS2322: Type 'void' is not assignable to type 'AbstractControl'

This is my .ts file :

  profileForm  = new FormGroup({
    username   : new FormControl().setValue("a"),
    firstname  : new FormControl().setValue("a"),
    lastname   : new FormControl().setValue("a"),
    email      : new FormControl().setValue("a"),
    password   : new FormControl().setValue("a"),
  });

Help me to solve this.

Body:
FormControl.setValue() returns a void - which means it returns nothing.

You're effectively trying to create an object with the following signature:

{
  username: void,
  firstname: void,
  ...
}

Which is both meaningless and invalid for constructing a FormGroup. FormGroup expects an object with the following signature in its constructor:

{
  [key: string]: FormControl
}

So something more like:

{
  username: new FormControl(),
  firstname: new FormControl(),
  ...
}

If you want to access the form controls programmatically, you could do this:

const formControls = {
  username: new FormControl('a'),
  firstname: new FormControl('a'),
  ...
};

// or this
formControls.username.setValue('a');
formControls.firstname.setValue('a');
// ... etc

profileForm = new FormGroup({
  username: formControls.username,
  firstname: formControls.firstname,
  ...
});


来源: stackexchange

问:
accessing private members of a class in cuda kernel
I created a class and passed its object to a cuda kernel.

The kernel's code is:

```<code>__global__ void kernel(pt *p,int n)
{
int id=blockDim.x*blockIdx.x+threadIdx.x;
if(id<n)
{
    p[id]=p[id]*p[id];
}}
</code>```

And it gives the following error: error: ‘int pt::a’ is private

The Question is:
How can I access the private member of a class?

The program runs all right if there are no private members

```<code>class pt{
int a,b;
public:
pt(){}
pt(int x,int y)
{
    a=x;
    b=y;
}
friend ostream& operator<<(ostream &out,pt p)
{
    out<<"("<<p.a<<","<<p.b<<")\n";
    return out;
}
int get_a()
{
    return this->a;
}
int get_b()
{
    return this->b;
}
__host__ __device__ pt operator*(pt p)
{
    pt temp;
    temp.a=a*p.a;
    temp.b=b*p.b;
    return temp;
}
pt operator[](pt p)
{
    pt temp;
    temp.a=p.a;
    temp.b=p.b;
    return temp;
}
void set_a(int p)
{
    a=p;
}
void set_b(int p)
{
    b=p;
}};
</code>```

答: Private members of a class can only be accessed by its member functions and its friends.</p>

ContentLicense: CC BY-SA 3.0

Body:
I created a class and passed its object to a cuda kernel.

The kernel's code is:

__global__ void kernel(pt *p,int n)
{
int id=blockDim.x*blockIdx.x+threadIdx.x;
if(id<n)
{
    p[id]=p[id]*p[id];
}}

And it gives the following error: error: ‘int pt::a’ is private

The Question is:
How can I access the private member of a class?

The program runs all right if there are no private members

class pt{
int a,b;
public:
pt(){}
pt(int x,int y)
{
    a=x;
    b=y;
}
friend ostream& operator<<(ostream &out,pt p)
{
    out<<"("<<p.a<<","<<p.b<<")\n";
    return out;
}
int get_a()
{
    return this->a;
}
int get_b()
{
    return this->b;
}
__host__ __device__ pt operator*(pt p)
{
    pt temp;
    temp.a=a*p.a;
    temp.b=b*p.b;
    return temp;
}
pt operator[](pt p)
{
    pt temp;
    temp.a=p.a;
    temp.b=p.b;
    return temp;
}
void set_a(int p)
{
    a=p;
}
void set_b(int p)
{
    b=p;
}};


问:
Get element index of array of objects with the "highest" value for given key
Let's say I have the following array of objects:

```<code>[
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
]
</code>```

What would be the quickest method for extract the position (index) of the element of the object with the highest score value...so, in the above case, the value would be index 3...

N.B. Scores are dynamic, and the "winning" element is the highest value...

答:
Try this. Use javascript max and map function to get value of index

 var data = [
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 }
];

var maxValue =
Math.max.apply(Math, data.map(function(row,index) { return index; }))

console.log(maxValue)```
</div>
</div>
</p>

<p>2) I think this will also give you correct result</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [
   { name: 'april', score: 1 },
   { name: 'january', score: 3.02 },
   { name: 'february', score: 11.02 },
   { name: 'march', score: 2 }

];
var maxValue = Math.max.apply(Math, data.map(function(row) { return row.score; }))
var key = data.findIndex((row,index)=>{ if(row.score ===maxValue){return true}})

console.log(key)</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have the following array of objects:

[
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 },
]

What would be the quickest method for extract the position (index) of the element of the object with the highest score value...so, in the above case, the value would be index 3...

N.B. Scores are dynamic, and the "winning" element is the highest value...

Body:
Try this. Use javascript max and map function to get value of index

 var data = [
   { name: 'january', score: 3.02 },
   { name: 'february', score: 1.02 },
   { name: 'march', score: 0 },
   { name: 'april', score: 12 }
];

var maxValue =
Math.max.apply(Math, data.map(function(row,index) { return index; }))

console.log(maxValue)

2) I think this will also give you correct result

var data = [
   { name: 'april', score: 1 },
   { name: 'january', score: 3.02 },
   { name: 'february', score: 11.02 },
   { name: 'march', score: 2 }

];
var maxValue = Math.max.apply(Math, data.map(function(row) { return row.score; }))
var key = data.findIndex((row,index)=>{ if(row.score ===maxValue){return true}})

console.log(key)


问:
Bidirectional UDP tunnel
Consider a process A which performs a bidirectional UDP communication with some HOST on a PORT1. Both IP and PORT1 are configurable.  Moreover, process A binds to PORT1, I have no control over that.

Is it possible to create a UDP tunnel which routes the traffic of process A from localhost to HOST, i.e. so instead of the original

process A <-> HOST:PORT1 we have a

process A <-> localhost:PORT2 <-> tunnel <-> HOST:PORT1 type of communication?

The problem I'm facing is that both process A and tunnel bind to the same localhost:PORT2 resulting in an Address already in use error.

答:
Is it possible to create a UDP tunnel which routes the traffic of
  process A from localhost to HOST

Certainly, you can write (or find) a program that receives UDP packets from one location and sends a copy of them to a second location (and vice versa).

The problem I'm facing is that both process A and tunnel bind to the
  same localhost:PORT2 resulting in an Address already in use error.

Your tunnel needs to bind to the port that process A is sending packets to, not to the port that process A is receiving packets on.  (presumably they are different ports, since if process A was binding its UDP socket to the same port it was sending UDP packets to, then it could only send UDP packets to itself, which wouldn't be a very useful thing to do)

Note that your remote program will need to be smart enough to send its UDP packets to the port that your tunnel-program is bound on rather than to the port that process A is bound on; otherwise the packets from the remote program will go straight to process A rather than through your tunnel-program.

Title: Bidirectional UDP tunnel


问:
Curl returntransfer is empty, curl_getinfo "Error: 1"
I try to get a page with curl from an IIS-Server which demands user authentication.

The curl_exec returns nothing, CURLOPT_RETURNTRANSFER is true. If CURLOPT_RETURNTRANSFER is false the curl_exec returns true.

What's the problem? The page is neither after successfull nor after unsuccessful authentication empty.

```<code>$username = $_POST["acc"];
$password = $_POST["pw"];
$url = "https://secure.website.com/";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$page = curl_exec($ch);
echo "Error: " . print_r(curl_getinfo($ch)) . "<br>";
curl_close($ch);

echo "<br>Page:<br>" . $page  . "<br>---------------------------<br>";
</code>```

The script output looks like this:

```<code>Array ( [url] => https://secure.website.com/
        [content_type] => text/html
        [http_code] => 302
        [header_size] => 435
        [request_size] => 137
        [filetime] => -1
        [ssl_verify_result] => 20
        [redirect_count] => 0
        [total_time] => 0.187
        [namelookup_time] => 0
        [connect_time] => 0
        [pretransfer_time] => 0.046
        [size_upload] => 0
        [size_download] => 0
        [speed_download] => 0
        [speed_upload] => 0
        [download_content_length] => 0
        [upload_content_length] => 0
        [starttransfer_time] => 0.187
        [redirect_time] => 0
        [certinfo] => Array ( ) )
        Error: 1

Page:

---------------------------
</code>```

curl_error outputs no error. The "Error: 1" at the end of the curl_getinfo is kind of my only hint.
The script works on other websites.

答:
Note the status code, which is a 302 Found, meaning that the page is issuing a redirect. Try:

```<code>curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
</code>```

This will make cURL follow the redirects for you, and should fix this issue.

(Error: 1 is irrelevant, that's just because you're doing echo print_r().)

Body:
I try to get a page with curl from an IIS-Server which demands user authentication.

The curl_exec returns nothing, CURLOPT_RETURNTRANSFER is true. If CURLOPT_RETURNTRANSFER is false the curl_exec returns true.

What's the problem? The page is neither after successfull nor after unsuccessful authentication empty.

$username = $_POST["acc"];
$password = $_POST["pw"];
$url = "https://secure.website.com/";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$page = curl_exec($ch);
echo "Error: " . print_r(curl_getinfo($ch)) . "
";
curl_close($ch);

echo "
Page:
" . $page  . "
---------------------------
";

The script output looks like this:

Array ( [url] => https://secure.website.com/
        [content_type] => text/html
        [http_code] => 302
        [header_size] => 435
        [request_size] => 137
        [filetime] => -1
        [ssl_verify_result] => 20
        [redirect_count] => 0
        [total_time] => 0.187
        [namelookup_time] => 0
        [connect_time] => 0
        [pretransfer_time] => 0.046
        [size_upload] => 0
        [size_download] => 0
        [speed_download] => 0
        [speed_upload] => 0
        [download_content_length] => 0
        [upload_content_length] => 0
        [starttransfer_time] => 0.187
        [redirect_time] => 0
        [certinfo] => Array ( ) )
        Error: 1

Page:

---------------------------

curl_error outputs no error. The "Error: 1" at the end of the curl_getinfo is kind of my only hint.
The script works on other websites.

Body:
Note the status code, which is a 302 Found, meaning that the page is issuing a redirect. Try:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

This will make cURL follow the redirects for you, and should fix this issue.

(Error: 1 is irrelevant, that's just because you're doing echo print_r().)


问:
"No such module 'Firebase'" // framework not found FirebaseUI
I previously had Firebase connected to my app with the below pods (excluding pod 'Firebase/DynamicLinks) and it was working just fine. I was using the line 'import Firebase' at the top of each view controller to import the relevant frameworks.

However, today I went to add pod 'Firebase/DynamicLinks' and when I went to run pod install, it got stuck 'analyzing dependencies'. I read through other forums on stackoverflow to fix this issue. I ended up removing cocoapods from my project and reinstalling them. I now have reinstalled the pods, but when I open Xcode I get the message 'No such module 'Firebase'. It essentially wants me to import specific Firebase modules [import FirebaseDatabase, import FirebaseAnalytics, etc.] instead of just [import Firebase]. After updating the import on all of my view controllers, there is 1 issue remaining -> 'Framework not found FirebaseUI'.

Questions

Is going from 'import Firebase' to 'import FirebaseDatabase, etc.' recommended or is this a step backwards?

How can I resolve 'Framework not found FirebaseUI'? I have the pod installed already.

Other info that may help

When running pod install, I get a warning notification: [!] [Xcodeproj] Generated duplicate UUIDs

When trying to build project, I also get: ld: warning: directory not found for option '-F/Users/[myNameHere]/Library/Developer/Xcode/DerivedData/[AppName]-dtipemvgjzrgzvephbatansalrwu/Build/Products/Debug-iphonesimulator/Firebase'

As well as: ld: warning: directory not found for option '-F/Users/[myNameHere]/Library/Developer/Xcode/DerivedData/[AppName]-dtipemvgjzrgzvephbatansalrwu/Build/Products/Debug-iphonesimulator/FirebaseUI'

My podfile

pod 'FirebaseUI'

pod 'FirebaseUI/Auth'

pod 'Firebase/Core'

pod 'Firebase/Database'

pod 'Firebase/Messaging'

pod 'Firebase/Analytics'

pod 'Firebase/Storage'

pod 'Firebase/Auth'

pod 'FirebaseUI/Google'

pod 'FirebaseUI/Facebook'

pod 'Firebase/DynamicLinks' (new)

答:
After rereading the Firebase documentation, it turns out "You no longer need to add the iOS pod Firebase/Core. This SDK included the Firebase SDK for Google Analytics."

I ended up removing Core and the UI Cocoapods (using my own UI buttons instead) and the project now builds. I assume there may be an error installing the UI Framework with the FirebaseUI Cocoapod - idk.

Pods removed:
 - pod 'Firebase/Core'
 - pod 'FirebaseUI'
 - pod 'FirebaseUI/Auth'
 - pod 'FirebaseUI/Google'
 - pod 'FirebaseUI/Facebook'


问:
How to delete duplicates from one table, but keeping only one record?
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

```<code>DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

```<code>SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

答:
I found out the exact reason of issue I faced finally.
I referenced the comment of @Malakiyasanjay.
you can find that from here How to keep only one row of a table, removing duplicate rows?

I tried like this: (and it worked for me as well but it took a lot of time to run the query for 30,000 rows)

```<code>delete from myTable
where id not in
(select min(id) as min from (select * from myTable) as x group by title)
</code>```

The problem was I couldn't specify the 'myTable' table as a target table. so I used (select * from myTable) as x and figured it out.

I am sorry I can't explain more detail about that because I am not familiar with mysql query. But you should note that:

MySql does not allow the direct use of the target table inside a subquery like the one you use with NOT IN, but you can overcome this limitation by enclosing the subquery inside another one.
  (Please reference @forpas 's answer.)

But you have to notice this takes so long time... It might cause the time out error. I ran this query for table with about 600,000 rows but it didn't response for several days. So I conclude this idea is pretty fit to small database table.

I hope this is helpful for everyone! :)

Body:
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

Body:
I found out the exact reason of issue I faced finally.
I referenced the comment of @Malakiyasanjay.
you can find that from here How to keep only one row of a table, removing duplicate rows?

I tried like this: (and it worked for me as well but it took a lot of time to run the query for 30,000 rows)

delete from myTable
where id not in
(select min(id) as min from (select * from myTable) as x group by title)

The problem was I couldn't specify the 'myTable' table as a target table. so I used (select * from myTable) as x and figured it out.

I am sorry I can't explain more detail about that because I am not familiar with mysql query. But you should note that:

MySql does not allow the direct use of the target table inside a subquery like the one you use with NOT IN, but you can overcome this limitation by enclosing the subquery inside another one.
  (Please reference @forpas 's answer.)

But you have to notice this takes so long time... It might cause the time out error. I ran this query for table with about 600,000 rows but it didn't response for several days. So I conclude this idea is pretty fit to small database table.

I hope this is helpful for everyone! :)


问:
How to get the tool id for eclipse headless build
Eclipse has a headless build option and in the documentation they say we can add or replace tool options

Replace a tool option value:           -T          {toolid} {optionid=value}

Append to a tool option value:         -Ta         {toolid} {optionid=value}

Prepend to a tool option value:        -Tp         {toolid} {optionid=value}

Remove a tool option:                  -Tr         {toolid} {optionid=value}

How would someone find the {toolid} value for a build option?

I would like to change the command line arguments for this command

```<code>arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"
</code>```

to

```<code>arm-none-eabi-objcopy -O binary "KTV_Rear.elf"  "KTV_Rear.bin"
</code>```

I have not been able to find any documentation on how to get the tool id to pass to the -T command. Any help would be appreciated.

==================== UPDATE ========================

I tried to figure out what the tool ids were in the way that HighCommander4 suggested. Searching for "tool id" in the project gives

```<code><tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.1172133377" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.707543027" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1908892168" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.1903643389" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.270131667" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.1091026714" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1404415533" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.292770688" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
</code>```

The output of the build window for the command I need to modify is

```<code>Invoking: GNU ARM Cross Create Flash Image
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"
</code>```

It does not seem obvious which one of the tool ids might relate to arm-none-eabi-objcopy. I tried using the string for the tool id for the archiver with no luck.

I found this link that seems related

答:
At the .cproject file you can find the tool id (use the superClass field, without the number) and for each tool you can find a list of options ids. At the invocation line you need to specify the tool id, the option id and the value for the option, like in the following example (adding my_lib_location to the libraries search path):</p>

```<code>-Tp cdt.managedbuild.tool.gnu.c.linker.exe.release gnu.c.link.option.paths=my_lib_location
</code>```

Body:
Eclipse has a headless build option and in the documentation they say we can add or replace tool options

Replace a tool option value:           -T          {toolid} {optionid=value}

Append to a tool option value:         -Ta         {toolid} {optionid=value}

Prepend to a tool option value:        -Tp         {toolid} {optionid=value}

Remove a tool option:                  -Tr         {toolid} {optionid=value}

How would someone find the {toolid} value for a build option?

I would like to change the command line arguments for this command

arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"

to

arm-none-eabi-objcopy -O binary "KTV_Rear.elf"  "KTV_Rear.bin"

I have not been able to find any documentation on how to get the tool id to pass to the -T command. Any help would be appreciated.

==================== UPDATE ========================

I tried to figure out what the tool ids were in the way that HighCommander4 suggested. Searching for "tool id" in the project gives

<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.1172133377" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.707543027" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1908892168" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.1903643389" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler.270131667" name="GNU ARM Cross C++ Compiler" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.compiler"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker.1091026714" name="GNU ARM Cross C++ Linker" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.cpp.linker">
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver.1404415533" name="GNU ARM Cross Archiver" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.archiver"/>
<tool id="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting.292770688" name="GNU ARM Cross Create Listing" superClass="ilg.gnuarmeclipse.managedbuild.cross.tool.createlisting">

The output of the build window for the command I need to modify is

Invoking: GNU ARM Cross Create Flash Image
arm-none-eabi-objcopy -O ihex "KTV_Rear.elf"  "KTV_Rear.hex"

It does not seem obvious which one of the tool ids might relate to arm-none-eabi-objcopy. I tried using the string for the tool id for the archiver with no luck.

I found this link that seems related

Body:
At the .cproject file you can find the tool id (use the superClass field, without the number) and for each tool you can find a list of options ids. At the invocation line you need to specify the tool id, the option id and the value for the option, like in the following example (adding my_lib_location to the libraries search path):

-Tp cdt.managedbuild.tool.gnu.c.linker.exe.release gnu.c.link.option.paths=my_lib_location


问:
pandas series exact match with a list of lists
I have a dataframe of the form :

```<code>      ID   |   COL
       1        A
       1        B
       1        C
       1        D
       2        A
       2        C
       2        D
       3        A
       3        B
       3        C
</code>```

I also have a list of list containing sequences,for example seq = [[A,B,C],[A,C,D]].

I am trying to count the number of IDs in the dataframe where in COL  matchs exactly an entry in seq. I am currently doing it the following way :-

df.groupby('ID')['COL'].apply(lambda x: x.reset_index(drop = True).equals(pd.Series(vs))).reset_index()['COL'].count()

iterating over vs,where vs is a list from seq.

Expected Output :-

```<code>  ID | is_in_seq
   1    0
   2    1
   3    1

</code>```

Since the sequence in COL for ID 1 is ABCD, which is not a sequence in seq, the value against it is 0.

Questions:-

1.) Is there a vectorized way of doing this operation? The approach I've outlined above takes a lot of time even for a single entry from seq, seeing that there can be upto 30 - 40 values in col per ID and maintaining the order in COL is critical.

答:
IIUC, use groupby.sum
to get a string with the complete sequence. Then use map and ''.join with DataFrame.isin to check matches

```<code>new_df = (df.groupby('ID')['COL']
            .sum()
            .isin(map(''.join, seq))
           #.isin(list(map(''.join, seq))) #if neccesary list
            .astype(int)
            .reset_index(name = 'is_in_seq')
         )

print(new_df)
   ID  is_in_seq
0   1          0
1   2          1
2   3          1
</code>```

Detail

```<code>df.groupby('ID')['COL'].sum()
ID
1    ABCD
2     ACD
3     ABC
Name: COL, dtype: object
</code>```

Body:
I have a dataframe of the form :

      ID   |   COL
       1        A
       1        B
       1        C
       1        D
       2        A
       2        C
       2        D
       3        A
       3        B
       3        C

I also have a list of list containing sequences,for example seq = [[A,B,C],[A,C,D]].

I am trying to count the number of IDs in the dataframe where in COL  matchs exactly an entry in seq. I am currently doing it the following way :-

df.groupby('ID')['COL'].apply(lambda x: x.reset_index(drop = True).equals(pd.Series(vs))).reset_index()['COL'].count()

iterating over vs,where vs is a list from seq.

Expected Output :-

  ID | is_in_seq
   1    0
   2    1
   3    1

Since the sequence in COL for ID 1 is ABCD, which is not a sequence in seq, the value against it is 0.

Questions:-

1.) Is there a vectorized way of doing this operation? The approach I've outlined above takes a lot of time even for a single entry from seq, seeing that there can be upto 30 - 40 values in col per ID and maintaining the order in COL is critical.

Body:
IIUC, use groupby.sum
to get a string with the complete sequence. Then use map and ''.join with DataFrame.isin to check matches

new_df = (df.groupby('ID')['COL']
            .sum()
            .isin(map(''.join, seq))
           #.isin(list(map(''.join, seq))) #if neccesary list
            .astype(int)
            .reset_index(name = 'is_in_seq')
         )

print(new_df)
   ID  is_in_seq
0   1          0
1   2          1
2   3          1

Detail

df.groupby('ID')['COL'].sum()
ID
1    ABCD
2     ACD
3     ABC
Name: COL, dtype: object


问:
When I am using SendKeys to send the date in the field and when I am running the script its pasting the date twice in that field
```<code>        package debut.Ifinca.NewOrder;
        import org.openqa.selenium.By;
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.chrome.ChromeDriver;
        import org.openqa.selenium.support.ui.Select;

        public class NewIfincaOrder {
        public static void main(String[] args)

            {       System.setProperty("webdriver.chrome.driver","C:\\\\Users\\\\COMPUTER\\\\Desktop\\\\chromedriver_win32 (2)\\\\chromedriver.exe");
                WebDriver driver = new   ChromeDriver();
                driver.get("http://js-server.debutinfotech.com:3093/");

                driver.manage().window().maximize();
 //Here When I am sending this date its getting entered twice in this field.This field has Date picker format.
    driver.findElement(By.xpath(".//input[@id='exporter_delivery_date']")).sendKeys("02/18/2020");
        }
        }
</code>```

答:
Have you tried clearing the field first?</p>

```<code>driver.findElement(By.xpath(".//input[@id='exporter_delivery_date']")).clear();
driver.findElement(By.xpath(".//input[@id='exporter_delivery_date']")).sendKeys("02/18/2020");
</code>```

Body:
Have you tried clearing the field first?

driver.findElement(By.xpath(".//input[@id='exporter_delivery_date']")).clear();
driver.findElement(By.xpath(".//input[@id='exporter_delivery_date']")).sendKeys("02/18/2020");


问:
How to make IntelliJ understand annotations
I have recently switched from using Eclipse to IntelliJ, and am preferring the experience.

However, the IDE is not understanding any of the Annotations.  I am using Spring @Autowired annotation as well as some of the Spring-WS annotations and the IDE is telling me that they are unresolved.

When the project is built using Maven, it builds fine, and the Annotations are recognised in Eclipse.

Im sure this is a simple setup thing, but cannot find any information on how to set it up.

答:
For the record, in our project pom, we have the following dependencies:

```<code>    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>
</code>```

The former two have been present already before implementing a web service, so they may not be required strictly for web services.

Body:
For the record, in our project pom, we have the following dependencies:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-ws-core</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>

The former two have been present already before implementing a web service, so they may not be required strictly for web services.


问:
Change specific variables on AWX(ansible) in ansible.cfg
We are use AWX for configuration managment and our team has a lot of playbooks and 4 enviroment scopes (DEV, QA, STAGING, PRODUCTION). In our playbooks we are use some specific variable in ansible.cfg that allows us send notifications.

```<code>[some_section]
some_var = https://some-dev-url/service/job_complete?
</code>```

On dev env he looks like example above, on qa, we add qa in link, on prod, we add prod in link etc.
When we push code beetwen branches example: dev -> qa, we always have a confilct, because link in ansible.cfg doesnt match. What we are doing now, is the always change this link when we merged something.
What im trying to do, is the pass with ansible extra vars(in ansible.cfg) this link, when playbook runs, but unforthunatly, i dont have a success.
The only thing that happened was I pulled the variable out of the config, but I do not know what to do next.

```<code>    - name: SOME LINK
      debug:
      msg: "{{ lookup('ini', 'some_var section=some_section file=ansible.cfg') }}"

      OK: "msg": "https://some-dev-url/service/job_complete?"
</code>```

It only occurs to rewrite the config somehow with a bash script when the playbook is started.
If someone has a solution, please) (by the way, we tried to use git ignore on this file, it doesn’t work)

答:
As per Ansible manuals it is important to have environment specific inventories. You can associate this variable at inventory level rather than at job level. Here are my suggestions -

1. Make environment specific inventories - It is important to not change the state of a node part of any other environment, thus, helps to avoid surprises at runtime. https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#example-one-inventory-per-environment.

 2. Move env. specific info. out of playbooks into inventories - You can setup up env. specific variables at your inventory level along with magic variables. Magic variables are known to Ansible. For example -

ansible_connection, ansible_user, ansible_ssh_pass. Ansible understands ok, it has to login to machine over ssh using ansible_user, ansible_ssh_pass.

This way you don't have to mention credentials at AWX Job Template and happily leave the machine credentials option empty at template level. https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html#magic.

3. Variables and vault - Notice the credentials section contains values as variable. Obviously, we do not want to expose any credentials as plaintext. therefore, it is important to follow Ansible best practise to let Ansible finds the variables in the unencrypted file and all sensitive variables come from the encrypted file. https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html#variables-and-vaults.

I maintain a variable file i.e. config file along with vault to get rendered at runtime in playbooks. You can create a subdirectory say vars and map the variables mentioned as value in inventory variables to a vars/var.yml file. vars.yml can have key defined as -

```<code>ssh_secret_dev: "{{ vault_secret_pass }}"
ssh_user_dev: username
</code>```

And encrypted vault file can have the final value  -

```<code>vault_secret_pass: very_secret_password
</code>```

Why the big dance? Why not just define everything in vault and connect inventory variable with vault? This provides an extra layer of security where you can map secure credentials in variable file and extra confidential in vault. Obviously vault will be encrypted, so you need to mention vault credentials at Job template level. The credential section at Job Template level will only contain vault credentials.

4. Select prompt at launch for Inventory at Job Template level - As we are making WorkFlows environment specific not Job Templates, therefore, we can mention Inventory at WorkFlow level and select prompt on launch option at Job Template level to allow Inventory apply to all Job Templates that have prompt on launch option.

 5. Edit Playbooks to load those two variable files (vault.yml and vars.yml).

```<code>- hosts: localhost
  vars_files:
    - ./vars/vault.yml
    - ./vars/vars.yml
  gather_facts: no
  no_log: true
  tasks:
     - .....some tasks......
</code>```

You can also make use of any variable you defined at inventory (which is not special ansible variables) and use them in your playbooks whose values can be picked from variable files.

Body:
We are use AWX for configuration managment and our team has a lot of playbooks and 4 enviroment scopes (DEV, QA, STAGING, PRODUCTION). In our playbooks we are use some specific variable in ansible.cfg that allows us send notifications.

[some_section]
some_var = https://some-dev-url/service/job_complete?

On dev env he looks like example above, on qa, we add qa in link, on prod, we add prod in link etc.
When we push code beetwen branches example: dev -> qa, we always have a confilct, because link in ansible.cfg doesnt match. What we are doing now, is the always change this link when we merged something.
What im trying to do, is the pass with ansible extra vars(in ansible.cfg) this link, when playbook runs, but unforthunatly, i dont have a success.
The only thing that happened was I pulled the variable out of the config, but I do not know what to do next.

    - name: SOME LINK
      debug:
      msg: "{{ lookup('ini', 'some_var section=some_section file=ansible.cfg') }}"

      OK: "msg": "https://some-dev-url/service/job_complete?"

It only occurs to rewrite the config somehow with a bash script when the playbook is started.
If someone has a solution, please) (by the way, we tried to use git ignore on this file, it doesn’t work)

Body:
As per Ansible manuals it is important to have environment specific inventories. You can associate this variable at inventory level rather than at job level. Here are my suggestions -

1. Make environment specific inventories - It is important to not change the state of a node part of any other environment, thus, helps to avoid surprises at runtime. https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#example-one-inventory-per-environment.

 2. Move env. specific info. out of playbooks into inventories - You can setup up env. specific variables at your inventory level along with magic variables. Magic variables are known to Ansible. For example -

ansible_connection, ansible_user, ansible_ssh_pass. Ansible understands ok, it has to login to machine over ssh using ansible_user, ansible_ssh_pass.

This way you don't have to mention credentials at AWX Job Template and happily leave the machine credentials option empty at template level. https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html#magic.

3. Variables and vault - Notice the credentials section contains values as variable. Obviously, we do not want to expose any credentials as plaintext. therefore, it is important to follow Ansible best practise to let Ansible finds the variables in the unencrypted file and all sensitive variables come from the encrypted file. https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html#variables-and-vaults.

I maintain a variable file i.e. config file along with vault to get rendered at runtime in playbooks. You can create a subdirectory say vars and map the variables mentioned as value in inventory variables to a vars/var.yml file. vars.yml can have key defined as -

ssh_secret_dev: "{{ vault_secret_pass }}"
ssh_user_dev: username

And encrypted vault file can have the final value  -

vault_secret_pass: very_secret_password

Why the big dance? Why not just define everything in vault and connect inventory variable with vault? This provides an extra layer of security where you can map secure credentials in variable file and extra confidential in vault. Obviously vault will be encrypted, so you need to mention vault credentials at Job template level. The credential section at Job Template level will only contain vault credentials.

4. Select prompt at launch for Inventory at Job Template level - As we are making WorkFlows environment specific not Job Templates, therefore, we can mention Inventory at WorkFlow level and select prompt on launch option at Job Template level to allow Inventory apply to all Job Templates that have prompt on launch option.

 5. Edit Playbooks to load those two variable files (vault.yml and vars.yml).

- hosts: localhost
  vars_files:
    - ./vars/vault.yml
    - ./vars/vars.yml
  gather_facts: no
  no_log: true
  tasks:
     - .....some tasks......

You can also make use of any variable you defined at inventory (which is not special ansible variables) and use them in your playbooks whose values can be picked from variable files.


问:
Need help in extracting the object from nested JSON in pysaprk
My JSON column values are as below

[{"item":"54509485","id":"1234","rule":"9383","issue_type":[],"rule_message":"this is json data.","sample_attributes":["shicode","measurement"],"impacted":[["Child"],[]],"type_of_blocker":[]}]

I want to get only object "item", "rule", "sample_attributes" using pyspark code using dataframe

答:
If you got pyspark.sql.dataframe.DataFrame, you can do it by:

```<code>data.select(data.column_name.item, data.column_name.rule, data.column_name.sample_attributes)
</code>```

Where data is your dataframe, and column_name is name of your column.

Body:
If you got pyspark.sql.dataframe.DataFrame, you can do it by:

data.select(data.column_name.item, data.column_name.rule, data.column_name.sample_attributes)

Where data is your dataframe, and column_name is name of your column.


问:
limit query time in the client side of PostgreSQL
I'm trying to query the PostgreSQL database, but this is a public server and I really don't want to waste a lot of CPU for a long time.

So I wonder if there is some way to limit my query time for a specific duration, for example, 3/5/10 minutes.

I assume that there is syntax like limit but not for results amount but for query duration.

Thanks for any kind of help.

答:
Here is a potential catch with using LIMIT to control how long a query might run.  Rightfully, you ought to also be using ORDER BY with your query, to tell Postgres how exactly it should limit the size of the result set.  But the caveat here is that Postgres would typically have to materialize the entire result set when using LIMIT with ORDER BY, and then also possibly sort, which might take longer than just reading in the entire result set.

One workaround to this might be to just use LIMIT without ORDER BY.  If the execution plan does not include reading the entire table and sorting, it might be one way to do what you want.  However, keep in mind that if you go this route, Postgres would have free license to return any records from the table it wishes, in any order.  This is probably not what you want from a business or reporting point of view.

But, a much better approach here would be just tune your query using things like indices, and make it faster to the point where you don't need to resort to a LIMIT trick.


答:
IIUC:

You will only ever produce a zero or a one.  Because you'll be checking if the group as a whole (and there is only one whole) is in seq.  If seq is unique (I'm assuming it is) then you'll only ever have the group in seq or not.

First step is to make seq a set of tuples

```<code>seq = set(map(tuple, seq))
</code>```

Second step is to produces an aggregated pandas object that contains tuples

```<code>tups = df.groupby('ID')['COL'].agg(tuple)
tups

ID
1    (A, B, C, D)
2       (A, C, D)
3       (A, B, C)
Name: COL, dtype: object
</code>```

Step three, we can use isin

```<code>tups.isin(seq).astype(int).reset_index(name='is_in_seq')

   ID  is_in_seq
0   1          0
1   2          1
2   3          1
</code>```

Title: pandas series exact match with a list of lists

Body:
IIUC:

You will only ever produce a zero or a one.  Because you'll be checking if the group as a whole (and there is only one whole) is in seq.  If seq is unique (I'm assuming it is) then you'll only ever have the group in seq or not.

First step is to make seq a set of tuples

seq = set(map(tuple, seq))

Second step is to produces an aggregated pandas object that contains tuples

tups = df.groupby('ID')['COL'].agg(tuple)
tups

ID
1    (A, B, C, D)
2       (A, C, D)
3       (A, B, C)
Name: COL, dtype: object

Step three, we can use isin

tups.isin(seq).astype(int).reset_index(name='is_in_seq')

   ID  is_in_seq
0   1          0
1   2          1
2   3          1


问:
Select several rows into several variables - Oracle PL/SQL
I have one select statement that returns a query like this:

```<code>SELECT value FROM dummy WHERE condition = 1;

    ROW | value
   -----|-----
    1   | val1
    2   | val2
    3   | val3
    4   | val4
</code>```

I have 4 variables

```<code>r1, r2, r3, r4
</code>```

What is the cleanest way to assign those variables the values of my query?
Can I use a SELECT INTO statement?

答:
One method is:

```<code>SELECT p_v1 = MAX(CASE WHEN row = 1 THEN value end),
       p_v2 = MAX(CASE WHEN row = 2 THEN value end),
       p_v3 = MAX(CASE WHEN row = 3 THEN value end),
       p_v4 = MAX(CASE WHEN row = 4 THEN value end)
FROM dummy
WHERE condition = 1;
</code>```

This is an aggregation query that returns one row.  If a particular row is missing, then the value will be NULL.

Body:
I have one select statement that returns a query like this:

SELECT value FROM dummy WHERE condition = 1;

    ROW | value
   -----|-----
    1   | val1
    2   | val2
    3   | val3
    4   | val4

I have 4 variables

r1, r2, r3, r4

What is the cleanest way to assign those variables the values of my query?
Can I use a SELECT INTO statement?

Body:
One method is:

SELECT p_v1 = MAX(CASE WHEN row = 1 THEN value end),
       p_v2 = MAX(CASE WHEN row = 2 THEN value end),
       p_v3 = MAX(CASE WHEN row = 3 THEN value end),
       p_v4 = MAX(CASE WHEN row = 4 THEN value end)
FROM dummy
WHERE condition = 1;

This is an aggregation query that returns one row.  If a particular row is missing, then the value will be NULL.


问:
How to recreate form with dynamic fields for edit in react antd (rc-forms)
After using antd form component (which depends on rc-form) for creating a form, I need to avail an edit form as well, I can't find any resources on how to initialize the antd form with the form values I have (especially the dynamic fields)

I found that using form.setFieldsInitialValue(theEditValues); will correctly initialize some of the form fields with the data correctly (for example, the dropdown with multiple select), but not the normal dropdowns & most importantly, all the dynamic fields are not created, giving a warning that you can't set field data before creating a field

So is there a preferred way to handle the edit scenario? so that:

1- To recreate the dynamic fields based on the submitted data before

2- To sync the whole form with the submitted data

I have added a sandbox to show what I mean, mainly if I have form values & I want to initialize the form with the dynamic fields with the values given

Note:

We need to handle a generic case where the user entered any number of dynamic fields and we wanna avail an edit form page with the given info

Update:

I have updated the example in a new sandbox to show what is meant by handling the values dynamically, I don't know the dynamic input in the edit scenario, it can be one field or plenty, so after retreiving the data from the api, it should be injected in the form programtically using form.setFieldsValue (just like how it can be handled for the static fields)

答:
Here is updated code https://codesandbox.io/s/cocky-sun-e57dm?fontsize=14&hidenavigation=1&theme=dark

Here are things to do

You need to initialize id with 2 since you need 2 initial fields.

You need to initialize keys field value with two values in array instead of [] like

getFieldDecorator("keys", { initialValue: [0, 1] });```
</div>
</div>
</p>

<ol start="3">
<li>assign initial value to available fields using this</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>getFieldDecorator(`names[${k}]`, {
  validateTrigger: ["onChange", "onBlur"],
  initialValue: valueOfFormToEdit[k] || '',
  rules: [
    {
      required: true,
      whitespace: true,
      message: "Please input passenger's name or delete this field."
    }
  ]
})</code>```

Update

Updated sandbox for new requirements :D

https://codesandbox.io/s/friendly-kirch-9gq1b?fontsize=14&hidenavigation=1&theme=dark

Body:
Here is updated code https://codesandbox.io/s/cocky-sun-e57dm?fontsize=14&hidenavigation=1&theme=dark

Here are things to do

You need to initialize id with 2 since you need 2 initial fields.

You need to initialize keys field value with two values in array instead of [] like

getFieldDecorator("keys", { initialValue: [0, 1] });

assign initial value to available fields using this

getFieldDecorator(`names[${k}]`, {
  validateTrigger: ["onChange", "onBlur"],
  initialValue: valueOfFormToEdit[k] || '',
  rules: [
    {
      required: true,
      whitespace: true,
      message: "Please input passenger's name or delete this field."
    }
  ]
})

Update

Updated sandbox for new requirements :D

https://codesandbox.io/s/friendly-kirch-9gq1b?fontsize=14&hidenavigation=1&theme=dark


问:
Overriding named routes provided by Rails 3 Engines
I am working on a Ruby on Rails 3(.0) application that uses a Rails engine. However, in my local application, I want to override one of the routes provided by the Rails engine.

From the engine config/routes.rb:

```<code>match 'their_named_route' => 'controller#action', :as => 'the_route'
</code>```

From my application config/routes.rb:

```<code>match 'my_named_route' => 'controller#action', :as => 'the_route'
</code>```

However, when I inspect the routes, both seem to be active (and their route appears to "win", at least within the engine controllers)

```<code>$ rake routes
the_route  /my_named_route(.:format)    {:controller=>"controller", :action=>"action"}
the_route  /their_named_route(.:format) {:controller=>"controller", :action=>"action"}
</code>```

Is there a good way to force my local application's named route to take priority?

答:
You need add initializer hook to config/application.rb, like this:

```<code>class Application < Rails::Application

  config.encoding = "utf-8"

  ...

  initializer :add_routing_paths do |app|
    their_routes_path = app.routes_reloader.paths.select{|path| path =~ /DIR/}.first
    app.routes_reloader.paths.delete(their_routes_path)
    app.routes_reloader.paths.unshift(their_routes_path)
  end
end
</code>```

It's load roues.rb of you engine first and you can override their routes.

Body:
I am working on a Ruby on Rails 3(.0) application that uses a Rails engine. However, in my local application, I want to override one of the routes provided by the Rails engine.

From the engine config/routes.rb:

match 'their_named_route' => 'controller#action', :as => 'the_route'

From my application config/routes.rb:

match 'my_named_route' => 'controller#action', :as => 'the_route'

However, when I inspect the routes, both seem to be active (and their route appears to "win", at least within the engine controllers)

$ rake routes
the_route  /my_named_route(.:format)    {:controller=>"controller", :action=>"action"}
the_route  /their_named_route(.:format) {:controller=>"controller", :action=>"action"}

Is there a good way to force my local application's named route to take priority?

Body:
You need add initializer hook to config/application.rb, like this:

class Application < Rails::Application

  config.encoding = "utf-8"

  ...

  initializer :add_routing_paths do |app|
    their_routes_path = app.routes_reloader.paths.select{|path| path =~ /DIR/}.first
    app.routes_reloader.paths.delete(their_routes_path)
    app.routes_reloader.paths.unshift(their_routes_path)
  end
end

It's load roues.rb of you engine first and you can override their routes.


问:
How can overwrite objects that have the same key in updating State with state hooks
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

```<code> const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };
</code>```

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

```<code> const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };
</code>```

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!

答:
Storing your filter array label-value pairs by key in an object (i.e. a "Map" or "Dictionary"), not an array, allows you constant time (O(1)) lookup by key to update the value of the filter by key (copying and returning a new state value is OFC still O(n)).

Also, use a functional state update to correctly access previous state and queue up state updates.

```<code>const [filterValues, setFilterValues] = useState({ f1: ["l","v"] });

const handleChange = (filter, label, value) => {
  setFilterValues(prevFilterValues => ({
    ...prevFilterValues,  // copy previous state
    [filter]: [label, value], // set the value for filter key
  }));
};
</code>```

Example:

```<code>handleChange('f1', 'l1', 'v1');
// filterValues = { f1: ["l1", "v1"] }

handleChange('f2', 'l2', 'v2');
// filterValues = {
//   f1: ["l1", "v1"],
//   f2: ["l2", "v2"],
// }

handleChange('f1', 'l3', 'v3');
// filterValues = {
//   f1: ["l3", "v3"],
//   f2: ["l2", "v2"],
// }
</code>```

Demo:

//const [filterValues, setFilterValues] = useState({ f1: ["l","v"] });

// Manual mock for useState return values
let filterValues = { f1: ["l","v"] };
setFilterValues = stateUpdater => filterValues = stateUpdater(filterValues);

const handleChange = (filter, label, value) => {
  setFilterValues(prevFilterValues => ({
    ...prevFilterValues,  // copy previous state
    [filter]: [label, value], // set the value for filter key
  }));
};

// Start Demo
console.log('initial filterValues', filterValues); // { f1: ["l", "v"] }

handleChange('f1', 'l1', 'v1');
console.log('filterValues', filterValues); // { f1: ["l1", "v1"] }

handleChange('f2', 'l2', 'v2');
console.log('filterValues', filterValues); // { f1: ["l1", "v1"], f2: ["l2", "v2"] }

handleChange('f1', 'l3', 'v3');
console.log('filterValues', filterValues); // { f1: ["l3", "v3"], f2: ["l2", "v2"] }```

Body:
I want to update the state when new filters are selected. the initial state shows the object structure i am aiming for. for example, i add a filter selection (for example "f2"), the label is fixed per filter, so we can neglect it, but the value maybe "va". Thats works fine, but when i want to change the value for "f2" to "vb", i now have two entries in my state {"f2":"va"} and {"f2":"vb"}, while i would rather have the first one  overwritten by the second.

 const [filterValues, setFilterValues] = useState([{"f1":["l","v"]}]);

 const handleChange = (filter, label, value) => {
   setFilterValues([
     ...filterValues,
     {[filter]: [label, value]}
   ]);
 };

i tried callin setFilterValues twice (once with mapping the entries to my condition) to solve the problem, but then i didnt even update state at all:

 const handleChange = (filter, label, value) => {
    setFilterValues([
      ...filterValues,
      {[filter]: [label, value]}
    ]);
    let key = filter
    setFilterValues(
      filterValues.map(
        el => el.key == key?  { [key]: [label, value] } : el
      )
    )
  };

i am a little bit new to react, so maybe i dont get a fundamental thing with updating state in functional components. can anybody help me with this? thank you!

Body:
Storing your filter array label-value pairs by key in an object (i.e. a "Map" or "Dictionary"), not an array, allows you constant time (O(1)) lookup by key to update the value of the filter by key (copying and returning a new state value is OFC still O(n)).

Also, use a functional state update to correctly access previous state and queue up state updates.

const [filterValues, setFilterValues] = useState({ f1: ["l","v"] });

const handleChange = (filter, label, value) => {
  setFilterValues(prevFilterValues => ({
    ...prevFilterValues,  // copy previous state
    [filter]: [label, value], // set the value for filter key
  }));
};

Example:

handleChange('f1', 'l1', 'v1');
// filterValues = { f1: ["l1", "v1"] }

handleChange('f2', 'l2', 'v2');
// filterValues = {
//   f1: ["l1", "v1"],
//   f2: ["l2", "v2"],
// }

handleChange('f1', 'l3', 'v3');
// filterValues = {
//   f1: ["l3", "v3"],
//   f2: ["l2", "v2"],
// }

Demo:

//const [filterValues, setFilterValues] = useState({ f1: ["l","v"] });

// Manual mock for useState return values
let filterValues = { f1: ["l","v"] };
setFilterValues = stateUpdater => filterValues = stateUpdater(filterValues);

const handleChange = (filter, label, value) => {
  setFilterValues(prevFilterValues => ({
    ...prevFilterValues,  // copy previous state
    [filter]: [label, value], // set the value for filter key
  }));
};

// Start Demo
console.log('initial filterValues', filterValues); // { f1: ["l", "v"] }

handleChange('f1', 'l1', 'v1');
console.log('filterValues', filterValues); // { f1: ["l1", "v1"] }

handleChange('f2', 'l2', 'v2');
console.log('filterValues', filterValues); // { f1: ["l1", "v1"], f2: ["l2", "v2"] }

handleChange('f1', 'l3', 'v3');
console.log('filterValues', filterValues); // { f1: ["l3", "v3"], f2: ["l2", "v2"] }


问:
'No Data' view getting opens first and then Detail Page opens with the data in Fiori
I am developing a Master Detail application in which if the service URL doesn't return data, then a view called 'NoData' should open. But what actually is happening that first, the 'NoData' view opens and then the Detail Page with the data gets displayed. I don't know why and how that 'NoData' page is appearing first. Below is my code for Master Page :

Controller.js :

```<code>        onInit: function () {

        this.router = sap.ui.core.UIComponent.getRouterFor(this);
        this._custTemp = this.getView().byId("listItemTemp").clone();
        this.refreshFlag = true; // Flag to get new data or not for customers

        this.totalModel = sap.ui.getCore().getModel("totalModel");
        this.getView().setModel(this.totalModel, "totalModel");

        this.oDataModel = sap.ui.getCore().getModel("DataModel");
        this.getView().setModel(this.oDataModel, "DataModel");

        this.oInitialLoadFinishedDeferred = jQuery.Deferred();
        var oEventBus = sap.ui.getCore().getEventBus();

        this.getView().byId("listId").attachEvent("updateFinished", function () {
            this.oInitialLoadFinishedDeferred.resolve();
            oEventBus.publish("MasterPage", "InitialLoadFinished", {
                oListItem: this.getView().byId("listId").getItems()[0]
            });
            if (!sap.ui.Device.system.phone) {
                this._getFirstItem();
            }
        }, this);

        this.functionData = [];
    },
waitForInitialListLoading: function (fnToExecute) {
        jQuery.when(this.oInitialLoadFinishedDeferred).then(jQuery.proxy(fnToExecute, this));
    },

    _getFirstItem: function () {
        sap.ui.core.BusyIndicator.show();
        this.waitForInitialListLoading(function () {
            // On the empty hash select the first item
            var list = this.getView().byId("listId");
            var selectedItem = list.getItems()[0];
            if (selectedItem) {
                list.setSelectedItem(selectedItem, true);
                var data = list.getBinding("items").getContexts()[0];
                sap.ui.getCore().getModel("detailModel").setData(data.getObject());

                this.router.navTo('DetailPage', {
                    QueryNo: data.EICNO
                });
                sap.ui.core.BusyIndicator.hide();
            } else {
                this.router.navTo('NoData');
            }
        }, this);
    },

    onBeforeRendering: function () {
        this._fnGetData();
    },

    _fnGetData: function (oEvent) {

        var that = this;
        this.getView().setModel(this.totalModel, "totalModel");

        if (this.refreshFlag === true) {
            sap.ui.core.BusyIndicator.show(0);

            $.ajax({
                url: "/sap/opu/odata/sap/ZHR_V_CARE_SRV/EmpQueryInitSet('10002001')?$expand=QueryLoginToQueryList/QueryToLog",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    that.getView().getModel("totalModel").setData(data.d.QueryLoginToQueryList);

                    that.refreshFlag = false;
                    sap.ui.core.BusyIndicator.hide();
                    that.statusList();

                },
                error: function (err) {
                    sap.ui.core.BusyIndicator.hide();
                    MessageBox.information(err.responseText + "Please try again");
                }
            });

        }

    }
</code>```

答:
totalModel is a json model, right? You'll get two updateFinished events on app load. The first one is triggered once the list control is rendered and binding is done (when the model has no data), and the second comes after your $.ajax call updates data to totalModel.

I think you can solve it by moving your NoData navigation to both 'success' and 'error' callbacks of your $.ajax call. Doing so may cover other use cases e.g. if you are using URL navigation parameters and a user changes the entity ID in the URL to some random number, it'd navigate to your NoDatapage.

Body:
I am developing a Master Detail application in which if the service URL doesn't return data, then a view called 'NoData' should open. But what actually is happening that first, the 'NoData' view opens and then the Detail Page with the data gets displayed. I don't know why and how that 'NoData' page is appearing first. Below is my code for Master Page :

Controller.js :

        onInit: function () {

        this.router = sap.ui.core.UIComponent.getRouterFor(this);
        this._custTemp = this.getView().byId("listItemTemp").clone();
        this.refreshFlag = true; // Flag to get new data or not for customers

        this.totalModel = sap.ui.getCore().getModel("totalModel");
        this.getView().setModel(this.totalModel, "totalModel");

        this.oDataModel = sap.ui.getCore().getModel("DataModel");
        this.getView().setModel(this.oDataModel, "DataModel");

        this.oInitialLoadFinishedDeferred = jQuery.Deferred();
        var oEventBus = sap.ui.getCore().getEventBus();

        this.getView().byId("listId").attachEvent("updateFinished", function () {
            this.oInitialLoadFinishedDeferred.resolve();
            oEventBus.publish("MasterPage", "InitialLoadFinished", {
                oListItem: this.getView().byId("listId").getItems()[0]
            });
            if (!sap.ui.Device.system.phone) {
                this._getFirstItem();
            }
        }, this);

        this.functionData = [];
    },
waitForInitialListLoading: function (fnToExecute) {
        jQuery.when(this.oInitialLoadFinishedDeferred).then(jQuery.proxy(fnToExecute, this));
    },

    _getFirstItem: function () {
        sap.ui.core.BusyIndicator.show();
        this.waitForInitialListLoading(function () {
            // On the empty hash select the first item
            var list = this.getView().byId("listId");
            var selectedItem = list.getItems()[0];
            if (selectedItem) {
                list.setSelectedItem(selectedItem, true);
                var data = list.getBinding("items").getContexts()[0];
                sap.ui.getCore().getModel("detailModel").setData(data.getObject());

                this.router.navTo('DetailPage', {
                    QueryNo: data.EICNO
                });
                sap.ui.core.BusyIndicator.hide();
            } else {
                this.router.navTo('NoData');
            }
        }, this);
    },

    onBeforeRendering: function () {
        this._fnGetData();
    },

    _fnGetData: function (oEvent) {

        var that = this;
        this.getView().setModel(this.totalModel, "totalModel");

        if (this.refreshFlag === true) {
            sap.ui.core.BusyIndicator.show(0);

            $.ajax({
                url: "/sap/opu/odata/sap/ZHR_V_CARE_SRV/EmpQueryInitSet('10002001')?$expand=QueryLoginToQueryList/QueryToLog",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    that.getView().getModel("totalModel").setData(data.d.QueryLoginToQueryList);

                    that.refreshFlag = false;
                    sap.ui.core.BusyIndicator.hide();
                    that.statusList();

                },
                error: function (err) {
                    sap.ui.core.BusyIndicator.hide();
                    MessageBox.information(err.responseText + "Please try again");
                }
            });

        }

    }


问:
perl validate data structure syntax
i have configuration files for my scripts containing huge data structures, e.g:

```<code>foo  =>  'bar',
one  =>  'two',
bla  =>  [
           'something',
           'else',
         ],
bli  =>  {
           here  =>  {
                       'and'  => 'there',
                       'also' => 'here',
                     },
         },
etc.
</code>```

i'm loading these configuration files using a simple e.g. :

```<code>%hash = do 'config.file';
</code>```

my problem is : when users modify this configuration file, they can mess it up, forgetting a comma, bracket or anything else, it can have terrible impacts as the variables will appear empty afterwards in the script (i don't want to check for the presence of every variable..)

is there any way to "validate" the syntax of such a file/structure at loading time or right after loading it ? any module doing this ?

i suppose i could add a value at the bottom and check for the presence of this value but it's a bit dirty.

thank you !

答: Is this supposed to be readable with Perl? (then shouldn't there be a comma after the b1 entry?) Then the way to validate it is pass it to eval and then check the value of $@. The less insecure way is to format your configuration in another popular, readable, writeable, comprehendable data serialization format. The JSON format meets those criteria.

Title: perl validate data structure syntax

Body:
i have configuration files for my scripts containing huge data structures, e.g:

foo  =>  'bar',
one  =>  'two',
bla  =>  [
           'something',
           'else',
         ],
bli  =>  {
           here  =>  {
                       'and'  => 'there',
                       'also' => 'here',
                     },
         },
etc.

i'm loading these configuration files using a simple e.g. :

%hash = do 'config.file';

my problem is : when users modify this configuration file, they can mess it up, forgetting a comma, bracket or anything else, it can have terrible impacts as the variables will appear empty afterwards in the script (i don't want to check for the presence of every variable..)

is there any way to "validate" the syntax of such a file/structure at loading time or right after loading it ? any module doing this ?

i suppose i could add a value at the bottom and check for the presence of this value but it's a bit dirty.

thank you !


问:
Property 'getPickerData' does not exist on type 'RefObject>'
I am trying to implement this https://github.com/thegamenicorus/react-native-phone-input/blob/master/examples/CustomPicker/app.js with typescript but it has proven rather difficult. I also just started out with react native so I don't know if I made my ref correctly but this is what I currently have.

```<code>import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : string;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() {
    if (this.phoneInputRef)
      this.setState({pickerData: this.phoneInputRef.getPickerData()});
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef)
      this.phoneInputRef.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});
</code>```

But it throws an error on this.phoneInputRef.selectCountry(country.cca2.toLowerCase()); and this.setState({pickerData: this.phoneInputRef.getPickerData()}); saying

```<code>Property 'selectCountry' does not exist on type 'RefObject<ReactNativePhoneInput<typeof TextInput>>'
</code>```

I installed the types for react-native-phone-input and I navigated to the object and saw that it did implement it. How is this possible? I added the file I navigated to.

```<code>// Type definitions for react-native-phone-input 0.2
// Project: https://github.com/thegamenicorus/react-native-phone-input
// Definitions by: Matthew Elphick <https://github.com/maael>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.9

import * as React from 'react';
import { StyleProp, ViewStyle as ViewStyleRaw, TextStyle as TextStyleRaw, TextInput, ImageRequireSource } from 'react-native';

export type ViewStyle = StyleProp<ViewStyleRaw>;
export type TextStyle = StyleProp<TextStyleRaw>;

export interface CountriesListItem {
  name: string;
  iso2: string;
  dialCode: string;
  priority: number;
  areaCodes: ReadonlyArray<string> | null;
}

export interface PickerData {
  key: number;
  image: ImageRequireSource;
  label: CountriesListItem['name'];
  dialCode: CountriesListItem['dialCode'];
  iso2: CountriesListItem['iso2'];
}

export interface ReactNativePhoneInputProps<TextComponentType extends React.ComponentType = typeof TextInput> {
    /**
     * Initial selected country
     */
    initialCountry?: string;
    /**
     * Allow user input 0 after country code
     */
    allowZeroAfterCountryCode?: boolean;
    /**
     * If true, disable all interaction of this component
     */
    disabled?: boolean;
    /**
     * Initial phone number
     */
    value?: string;
    /**
     * Custom styles to be applied if supplied
     */
    style?: ViewStyle;
    /**
     * Custom styles for flag image eg. {{width: 50, height: 30, borderWidth:0}}
     */
    flagStyle?: ViewStyle;
    /**
     * Custom styles for phone number text input eg. {{fontSize: 14}}
     */
    textStyle?: TextStyle;
    /**
     * Properties for phone number text input eg. {{placeholder: 'Telephone number'}}
     */
    textProps?: React.ComponentProps<TextComponentType>;
    /**
     * The input component to use
     */
    textComponent?: TextComponentType;
    /**
     * Distance between flag and phone number
     */
    offset?: number;
    /**
     * Set button color of country picker
     */
    pickerButtonColor?: string;
    /**
     * Set background color of country picker
     */
    pickerBackgroundColor?: string;
    /**
     * Custom styles for text in country picker eg. {{fontSize: 14}}
     */
    pickerItemStyle?: ViewStyle;
    /**
     * Cancel word
     */
    cancelText?: string;
    /**
     * Confirm word
     */
    confirmText?: string;
    /**
     * Custom styles for country picker button
     */
    buttonTextStyle?: TextStyle;
    /**
     * Function to be invoked when phone number is changed
     */
    onChangePhoneNumber?: (number: number) => void;
    /**
     * Function to be invoked when country picker is selected
     */
    onSelectCountry?: (iso2: string) => void;
    /**
     * Function to be invoked when press on flag image
     */
    onPressFlag?: () => void;
    /**
     * Custom countries list
     */
    countriesList?: ReadonlyArray<CountriesListItem>;
    /**
     * Function to be invoked when cancelling country picker selection
     */
    onPressCancel?: () => void;
    /**
     * Function to be invoked when confirming country picker selection
     */
    onPressConfirm?: () => void;
}

export default class ReactNativePhoneInput<
                   TextComponentType extends React.ComponentType = typeof TextInput
               > extends React.Component<ReactNativePhoneInputProps<TextComponentType>> {
                   picker?: React.Ref<ThisType<ReactNativePhoneInput>>;
                   /**
                    * Return true if current phone number is valid
                    */
                   isValidNumber: () => boolean;
                   /**
                    * Return true type of current phone number
                    */
                   getNumberType: () => string;
                   /**
                    * Return current phone number
                    */
                   getValue: () => string;
                   /**
                    * Return flag image
                    */
                   getFlag: (iso2: string) => ImageRequireSource;
                   /**
                    * Return country object in country picker
                    */
                   getAllCountries: () => CountriesListItem;
                   /**
                    * Return country object with flag image
                    */
                   getPickerData: () => PickerData;
                   /**
                    * Focus the phone input
                    */
                   focus: () => void;
                   /**
                    * Blur the phone input
                    */
                   blur: () => void;
                   /**
                    * Set phone input to specific country
                    */
                   selectCountry: (iso2: string) => void;
                   /**
                    * Return country dial code of current phone number
                    */
                   getCountryCode: () => string;
                   /**
                    * Return country iso code of current phone number
                    */
                   getISOCode: () => string;
               }
</code>```

答:
You could access reference via current property. Try below

```<code>this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());

this.setState({pickerData: this.phoneInputRef.current.getPickerData()});
</code>```

Body:
I am trying to implement this https://github.com/thegamenicorus/react-native-phone-input/blob/master/examples/CustomPicker/app.js with typescript but it has proven rather difficult. I also just started out with react native so I don't know if I made my ref correctly but this is what I currently have.

import * as React from 'react';
import { StyleSheet, Text, View, } from 'react-native';
import {Button} from 'react-native-elements';

import PhoneInput from 'react-native-phone-input';
import ReactNativePhoneInput from 'react-native-phone-input';
// import CountryPicker from 'react-native-country-picker-modal';

export interface IRegisterScreenProps {

}

export interface IRegisterScreenState{
  cca2? : string;
  pickerData? : string;
}

export default class RegisterScreen extends React.Component<IRegisterScreenProps, IRegisterScreenState> {

  private phoneInputRef = React.createRef<ReactNativePhoneInput>();

  constructor(props:IRegisterScreenProps) {
    super(props);
    this.onPressFlag = this.onPressFlag.bind(this);
    this.selectCountry = this.selectCountry.bind(this);
    this.submitPhoneNumber = this.submitPhoneNumber.bind(this);
    this.state = {
      cca2: 'US',
    };
  }

  componentDidMount() {
    if (this.phoneInputRef)
      this.setState({pickerData: this.phoneInputRef.getPickerData()});
  }

  onPressFlag() {
    // this.countryPicker.openModal();
    console.log(this.phoneInputRef);
  }

  selectCountry(country:IRegisterScreenState) {
    if(this.phoneInputRef)
      this.phoneInputRef.selectCountry(country.cca2.toLowerCase());
    // this.setState({ cca2: country.cca2 });
  }

  public render(): JSX.Element
  {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tempp</Text>
        <PhoneInput ref={this.phoneInputRef} onPressFlag={this.onPressFlag}/>
        <Button title="Submit" onPress={this.submitPhoneNumber} containerStyle={styles.submitButton} />
      </View>
    );
  }

  private submitPhoneNumber() : void
  {
    console.log(this.phoneInputRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 50,
    margin: 30,
  },
  phoneNumberInput:{
    width: 300,
  },
  submitButton:{
    width: 150,
    margin: 25,
  },
});

But it throws an error on this.phoneInputRef.selectCountry(country.cca2.toLowerCase()); and this.setState({pickerData: this.phoneInputRef.getPickerData()}); saying

Property 'selectCountry' does not exist on type 'RefObject<ReactNativePhoneInput<typeof TextInput>>'

I installed the types for react-native-phone-input and I navigated to the object and saw that it did implement it. How is this possible? I added the file I navigated to.

// Type definitions for react-native-phone-input 0.2
// Project: https://github.com/thegamenicorus/react-native-phone-input
// Definitions by: Matthew Elphick <https://github.com/maael>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.9

import * as React from 'react';
import { StyleProp, ViewStyle as ViewStyleRaw, TextStyle as TextStyleRaw, TextInput, ImageRequireSource } from 'react-native';

export type ViewStyle = StyleProp<ViewStyleRaw>;
export type TextStyle = StyleProp<TextStyleRaw>;

export interface CountriesListItem {
  name: string;
  iso2: string;
  dialCode: string;
  priority: number;
  areaCodes: ReadonlyArray<string> | null;
}

export interface PickerData {
  key: number;
  image: ImageRequireSource;
  label: CountriesListItem['name'];
  dialCode: CountriesListItem['dialCode'];
  iso2: CountriesListItem['iso2'];
}

export interface ReactNativePhoneInputProps<TextComponentType extends React.ComponentType = typeof TextInput> {
    /**
     * Initial selected country
     */
    initialCountry?: string;
    /**
     * Allow user input 0 after country code
     */
    allowZeroAfterCountryCode?: boolean;
    /**
     * If true, disable all interaction of this component
     */
    disabled?: boolean;
    /**
     * Initial phone number
     */
    value?: string;
    /**
     * Custom styles to be applied if supplied
     */
    style?: ViewStyle;
    /**
     * Custom styles for flag image eg. {{width: 50, height: 30, borderWidth:0}}
     */
    flagStyle?: ViewStyle;
    /**
     * Custom styles for phone number text input eg. {{fontSize: 14}}
     */
    textStyle?: TextStyle;
    /**
     * Properties for phone number text input eg. {{placeholder: 'Telephone number'}}
     */
    textProps?: React.ComponentProps<TextComponentType>;
    /**
     * The input component to use
     */
    textComponent?: TextComponentType;
    /**
     * Distance between flag and phone number
     */
    offset?: number;
    /**
     * Set button color of country picker
     */
    pickerButtonColor?: string;
    /**
     * Set background color of country picker
     */
    pickerBackgroundColor?: string;
    /**
     * Custom styles for text in country picker eg. {{fontSize: 14}}
     */
    pickerItemStyle?: ViewStyle;
    /**
     * Cancel word
     */
    cancelText?: string;
    /**
     * Confirm word
     */
    confirmText?: string;
    /**
     * Custom styles for country picker button
     */
    buttonTextStyle?: TextStyle;
    /**
     * Function to be invoked when phone number is changed
     */
    onChangePhoneNumber?: (number: number) => void;
    /**
     * Function to be invoked when country picker is selected
     */
    onSelectCountry?: (iso2: string) => void;
    /**
     * Function to be invoked when press on flag image
     */
    onPressFlag?: () => void;
    /**
     * Custom countries list
     */
    countriesList?: ReadonlyArray<CountriesListItem>;
    /**
     * Function to be invoked when cancelling country picker selection
     */
    onPressCancel?: () => void;
    /**
     * Function to be invoked when confirming country picker selection
     */
    onPressConfirm?: () => void;
}

export default class ReactNativePhoneInput<
                   TextComponentType extends React.ComponentType = typeof TextInput
               > extends React.Component<ReactNativePhoneInputProps<TextComponentType>> {
                   picker?: React.Ref<ThisType<ReactNativePhoneInput>>;
                   /**
                    * Return true if current phone number is valid
                    */
                   isValidNumber: () => boolean;
                   /**
                    * Return true type of current phone number
                    */
                   getNumberType: () => string;
                   /**
                    * Return current phone number
                    */
                   getValue: () => string;
                   /**
                    * Return flag image
                    */
                   getFlag: (iso2: string) => ImageRequireSource;
                   /**
                    * Return country object in country picker
                    */
                   getAllCountries: () => CountriesListItem;
                   /**
                    * Return country object with flag image
                    */
                   getPickerData: () => PickerData;
                   /**
                    * Focus the phone input
                    */
                   focus: () => void;
                   /**
                    * Blur the phone input
                    */
                   blur: () => void;
                   /**
                    * Set phone input to specific country
                    */
                   selectCountry: (iso2: string) => void;
                   /**
                    * Return country dial code of current phone number
                    */
                   getCountryCode: () => string;
                   /**
                    * Return country iso code of current phone number
                    */
                   getISOCode: () => string;
               }

Body:
You could access reference via current property. Try below

this.phoneInputRef.current.selectCountry(country.cca2.toLowerCase());

this.setState({pickerData: this.phoneInputRef.current.getPickerData()});


问:
How to animate the height of a box depending to the content inside?
It should be simple, but I can't find how.
In this exemple, when adding or removing a new item, i would like to the the #app height change smoothly, instead of instantanly.

In pure css

Thanks for help.

https://codesandbox.io/s/sparkling-frog-qfy64

```<code><template>
  <div id="app">
    <button @click="addItem">Add</button>
    <button @click="removeItem">Remove</button>
    <div v-for="(item, i) in items" class="box" :key="i">BOX</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    items: [1, 1]
  }),
  methods: {
    addItem() {
      this.items.push(1);
    },
    removeItem() {
      this.items.pop();
    }
  }
};
</script>

<style>
#app {
  text-align: center;
  color: white;
  margin-top: 60px;
  background: blue;
  height: auto;
  transition: all 1.5s ease;
}

.box {
  padding: 15px;
}
</style>

</code>```

答:
You need a measurement unit for it to be animated. height: auto won't do it.

You will need to compute the items height in JS.

Body:
It should be simple, but I can't find how.
In this exemple, when adding or removing a new item, i would like to the the #app height change smoothly, instead of instantanly.

In pure css

Thanks for help.

https://codesandbox.io/s/sparkling-frog-qfy64

<template>

    <button @click="addItem">Add</button>
    <button @click="removeItem">Remove</button>

BOX

</template>


问:
Normalisation--2NF vs 3NF
We say 2NF is "the whole key" and 3NF "nothing but the key".

Referencing this answer by Smashery:

What are database normal forms and can you give examples?

The example used for 3NF is exactly the same as 2NF--it's a field which is dependent on only one key attribute. How is the example for 3NF different from the one for 2NF?

答:
Suppose that some relation satisifies a non-trivial functional dependency of the form A->B, where B is a nonprime attribute.

2NF is violated if A is not a superkey but is a proper subset of a candidate key

3NF is violated if A is not a superkey

You have spotted that the 3NF requirement is just a special case (but not really so special) of the 2NF requirement. 2NF in itself is not very important. The important issue is whether A is a superkey, not whether A just happens to be some part of a candidate key.

Title: Normalisation--2NF vs 3NF


问:
How to create model instances from csv file
There is a task to parse the csv file and create instances in the database based on the received data. On the backend - DRF and at the front - React.
The specific feature is that the file processing is not quite hidden. The logic is as follows:
There is a button to load the file. The file is loaded and validated, but nothing is created in the database at once. A window appears with a list of saved data (like a table) and in this window there is a new button to confirm by clicking on which the database is already requested.

What I just did:
1. Created a class to download the file (Upload button)

```<code>class FileUploadView(APIView):
    parser_classes = ( MultiPartParser, FormParser)
    renderer_classes = [JSONRenderer]

    def put(self, request, format=None):
        if 'file' not in request.data:
            raise ParseError("Empty content")
        f = request.data['file']
        filename = f.name
        if filename.endswith('.csv'):
            file = default_storage.save(filename, f)
            r = csv_file_parser(file)
            status = 204
        else:
            status = 406
            r = "File format error"
        return Response(r, status=status)
</code>```

In the class, the csv_file_parser function is called, the result of which is json containing all the saved data like this:

```<code>{
    "1": {
        "Vendor": "Firstvendortestname",
        "Country": "USA",
         ...
         ...
        "Modules": "Module1",
        " NDA date": "2019-12-24"
    },
    "2": {
        "Vendor": "Secondvendortestname",
        "Country": "Canada",
         ...
         ...
        "Modules": "Module1",
        " NDA date": "2019-12-24"
    }
}
</code>```

This data will be used to preview the fields from which the model instaces will be created in the base by clicking on the Confirm button.

csv_file_parser function

```<code>def csv_file_parser(file):
    result_dict = {}
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        line_count = 1
        for rows in reader:
            for key, value in rows.items():
                if not value:
                    raise ParseError('Missing value in file. Check the {} line'.format(line_count))
            result_dict[line_count] = rows
            line_count += 1

    return result_dict
</code>```

When the Confirm button is pressed, React passes this data as an argument to a class that works with the database using the POST method. With the implementation of this class, I have difficulties. How to correctly process the received data and record it in the database?

```<code>class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        for vendor in data:
            Vendors(
                vendor_name=vendor['Vendor'],
                country=vendor['Country']
            ).save()

        return Response({'received data': request.data})
</code>```

This code gives error

```<code>TypeError at /api/v1/vendors/from_csv_create/
string indices must be integers
</code>```

Printing of request.data output

```<code><QueryDict: {'{\n    "1": {\n        "Vendor": "Firstvendortestname",\n        "Country": "USA",\n        "Primary Contact Name": "Jack Jhonson",\n        "Primary Contact Email": "jack@gmail.com",\n        "Secondary Contact Name": "Jack2 Jhonson",\n        "Secondary Contact Email": "jack2@gmail.com",\n        "Modules": "Module1, Module2",\n        " NDA date": "2019-12-24"\n    },\n    "2": {\n        "Vendor": "Secondvendortestname",\n        "Country": "Canada",\n        "Primary Contact Name": "Sandra Bullock",\n        "Primary Contact Email": "sandra@gmail.com",\n        "Secondary Contact Name": "Sandra Bullock",\n        "Secondary Contact Email": "sandra@gmail.com",\n        "Modules": "Module1, Module2",\n        " NDA date": "2019-12-24"\n    }\n}': ['']}>
</code>```

Maybe I'm using the wrong data format?

And overall, I have a feeling that I'm doing the job the wrong way. I don't use serializers, do I need them here?

答:
First of all my suggestion is to use bulk create operation instead of creating them one by one. Please follow this documentation link https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-create.

Your problem is caused because you are following data incorrectly in your loop. My advice is to start searching for the problem from the errors. The error clearly says that the BUG is in the data structure.

Now let's look at the request.data, it is not a list containing dicts to loop them like you are doing there. Please see this StackOverflow page for more details: Extracting items out of a QueryDict

Body:
There is a task to parse the csv file and create instances in the database based on the received data. On the backend - DRF and at the front - React.
The specific feature is that the file processing is not quite hidden. The logic is as follows:
There is a button to load the file. The file is loaded and validated, but nothing is created in the database at once. A window appears with a list of saved data (like a table) and in this window there is a new button to confirm by clicking on which the database is already requested.

What I just did:
1. Created a class to download the file (Upload button)

class FileUploadView(APIView):
    parser_classes = ( MultiPartParser, FormParser)
    renderer_classes = [JSONRenderer]

    def put(self, request, format=None):
        if 'file' not in request.data:
            raise ParseError("Empty content")
        f = request.data['file']
        filename = f.name
        if filename.endswith('.csv'):
            file = default_storage.save(filename, f)
            r = csv_file_parser(file)
            status = 204
        else:
            status = 406
            r = "File format error"
        return Response(r, status=status)

In the class, the csv_file_parser function is called, the result of which is json containing all the saved data like this:

{
    "1": {
        "Vendor": "Firstvendortestname",
        "Country": "USA",
         ...
         ...
        "Modules": "Module1",
        " NDA date": "2019-12-24"
    },
    "2": {
        "Vendor": "Secondvendortestname",
        "Country": "Canada",
         ...
         ...
        "Modules": "Module1",
        " NDA date": "2019-12-24"
    }
}

This data will be used to preview the fields from which the model instaces will be created in the base by clicking on the Confirm button.

csv_file_parser function

def csv_file_parser(file):
    result_dict = {}
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        line_count = 1
        for rows in reader:
            for key, value in rows.items():
                if not value:
                    raise ParseError('Missing value in file. Check the {} line'.format(line_count))
            result_dict[line_count] = rows
            line_count += 1

    return result_dict

When the Confirm button is pressed, React passes this data as an argument to a class that works with the database using the POST method. With the implementation of this class, I have difficulties. How to correctly process the received data and record it in the database?

class CsvToDatabase(APIView):

    def post(self, request, format=None):
        data = request.data
        for vendor in data:
            Vendors(
                vendor_name=vendor['Vendor'],
                country=vendor['Country']
            ).save()

        return Response({'received data': request.data})

This code gives error

TypeError at /api/v1/vendors/from_csv_create/
string indices must be integers

Printing of request.data output

<QueryDict: {'{\n    "1": {\n        "Vendor": "Firstvendortestname",\n        "Country": "USA",\n        "Primary Contact Name": "Jack Jhonson",\n        "Primary Contact Email": "jack@gmail.com",\n        "Secondary Contact Name": "Jack2 Jhonson",\n        "Secondary Contact Email": "jack2@gmail.com",\n        "Modules": "Module1, Module2",\n        " NDA date": "2019-12-24"\n    },\n    "2": {\n        "Vendor": "Secondvendortestname",\n        "Country": "Canada",\n        "Primary Contact Name": "Sandra Bullock",\n        "Primary Contact Email": "sandra@gmail.com",\n        "Secondary Contact Name": "Sandra Bullock",\n        "Secondary Contact Email": "sandra@gmail.com",\n        "Modules": "Module1, Module2",\n        " NDA date": "2019-12-24"\n    }\n}': ['']}>

Maybe I'm using the wrong data format?

And overall, I have a feeling that I'm doing the job the wrong way. I don't use serializers, do I need them here?