问:
what is the purpose of using this parameter, int (*cmp) (void*, void*)
in my homework ı couldn't understand this parameter ;

```<code>set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))
</code>```

can anybody explain this using?

thank you for helping.

答:
It is a pointer to a function taking two pointer arguments and returning an int.  Judging from its name, the semantics of the function are that it compares the two objects pointed to and returns a value <0, 0 or >0 indicating the relative order of the two object according to some ordering criteria.

The purpose of such a parameter is to allow the function (set_maker() in this case) to operate on objects of arbitrary type and ordering rules.  For example if you were operating in int objects, you might have a function:

```<code>int icompare(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}
</code>```

Then you could call set_maker() thus:

```<code>set_maker( istack, icompare ) ;
</code>```

so that set_maker() can operate on a LINKEDSTACK of ints. (I'm making a somewhat reasoned guess here since you have provided no details of set_maker() or LINKEDSTACK).

Equally the comparison function could operate on struct objects with more complex comparison rules involving multiple members.  So its purpose is to make set_maker() flexible enough to handle any data type without duplicating a great deal of code by providing the rules for handling each data type in the provided function.

A standard library example of such a function is qsort(), although you will notice there that the parameters are of type const void* which is best practice for functions that are not intended to modify the objects referenced.

Body:
in my homework ı couldn't understand this parameter ;

set_maker(LINKEDSTACK stack, int (*cmp) (void*, void*))

can anybody explain this using?

thank you for helping.

Body:
It is a pointer to a function taking two pointer arguments and returning an int.  Judging from its name, the semantics of the function are that it compares the two objects pointed to and returns a value <0, 0 or >0 indicating the relative order of the two object according to some ordering criteria.

The purpose of such a parameter is to allow the function (set_maker() in this case) to operate on objects of arbitrary type and ordering rules.  For example if you were operating in int objects, you might have a function:

int icompare(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

Then you could call set_maker() thus:

set_maker( istack, icompare ) ;

so that set_maker() can operate on a LINKEDSTACK of ints. (I'm making a somewhat reasoned guess here since you have provided no details of set_maker() or LINKEDSTACK).

Equally the comparison function could operate on struct objects with more complex comparison rules involving multiple members.  So its purpose is to make set_maker() flexible enough to handle any data type without duplicating a great deal of code by providing the rules for handling each data type in the provided function.

A standard library example of such a function is qsort(), although you will notice there that the parameters are of type const void* which is best practice for functions that are not intended to modify the objects referenced.


来源: stackexchange

问:
Powershell IIS Audit Scripting
I'm in the early stages of learning powershell, and I'm trying to put together a script that remotely gathers information from our IIS servers, but I'm encountering several issues.

The first one is that the IP Address and OU columns remain empty in the output file.
The second one is that I'm not able to format the Administrator group column to have 1 group per line, or delimited by commas.

This is the current version of the code:

```<code>$computers = Get-Content "C:\servers.txt"

#Running the invoke-command on remote machine to run the iisreset

$output = foreach ($computer in $computers)
{
       Write-Host "Details from server $computer..."

    try{
           Invoke-command  -ComputerName $computer -ErrorAction Stop -ScriptBlock{

           # Ensure to import the WebAdministration and AD module

                Import-Module WebAdministration
                Import-Module ActiveDirectory

                $webapps = Get-WebApplication
                $list = @()
                foreach ($webapp in get-childitem IIS:\AppPools\)
                {
                    $name = "IIS:\AppPools\" + $webapp.name
                    $item = @{}
                    $item.server = $env:computername
                    $item.WebAppName = $webapp.name
                    $item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
                    $item.State = (Get-WebAppPoolState -Name $webapp.name).Value
                    $item.UserIdentityType = $webapp.processModel.identityType
                    $item.Username = $webapp.processModel.userName
                    $item.Password = $webapp.processModel.password
                    $item.OU = (Get-ADComputer $_ | select DistinguishedNAme)
                    $item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4)
                    $item.Administrators = (Get-LocalGroupMember -Group "Administrators")

                    $obj = New-Object PSObject -Property $item
                    $list += $obj
                }

                $list | select -Property "Server","WebAppName", "Version", "State", "UserIdentityType", "Username", "Password", "OU", "Ip Address", "Administrators"

        }

    } catch {
        Add-Content .\failedservers.txt -Force -Value $computer
    }
}

$output | Export-Csv -Path .\output.csv
#Stop-Transcript
</code>```

I'd really appreciate any input on how to get it to work properly or improve on the code itself.
Thanks in advance!

答:
For the OU property, you'll want to reference $env:COMPUTERNAME instead of $_:

```<code>$item.OU = (Get-ADComputer $env:COMPUTERNAME |Select -Expand DistinguishedName)
</code>```

For the IPAddress and Administrators fields you'll want to use -join to create comma-separated lists of the relevant values:

```<code>$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4).IPAddress -join ','
$item.Administrators = (Get-LocalGroupMember -Group "Administrators").Name -join ','
</code>```

ContentLicense: CC BY-SA 4.0

Title: Powershell IIS Audit Scripting

Body:
I'm in the early stages of learning powershell, and I'm trying to put together a script that remotely gathers information from our IIS servers, but I'm encountering several issues.

The first one is that the IP Address and OU columns remain empty in the output file.
The second one is that I'm not able to format the Administrator group column to have 1 group per line, or delimited by commas.

This is the current version of the code:

$computers = Get-Content "C:\servers.txt"

#Running the invoke-command on remote machine to run the iisreset

$output = foreach ($computer in $computers)
{
       Write-Host "Details from server $computer..."

    try{
           Invoke-command  -ComputerName $computer -ErrorAction Stop -ScriptBlock{

           # Ensure to import the WebAdministration and AD module

                Import-Module WebAdministration
                Import-Module ActiveDirectory

                $webapps = Get-WebApplication
                $list = @()
                foreach ($webapp in get-childitem IIS:\AppPools\)
                {
                    $name = "IIS:\AppPools\" + $webapp.name
                    $item = @{}
                    $item.server = $env:computername
                    $item.WebAppName = $webapp.name
                    $item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
                    $item.State = (Get-WebAppPoolState -Name $webapp.name).Value
                    $item.UserIdentityType = $webapp.processModel.identityType
                    $item.Username = $webapp.processModel.userName
                    $item.Password = $webapp.processModel.password
                    $item.OU = (Get-ADComputer $_ | select DistinguishedNAme)
                    $item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4)
                    $item.Administrators = (Get-LocalGroupMember -Group "Administrators")

                    $obj = New-Object PSObject -Property $item
                    $list += $obj
                }

                $list | select -Property "Server","WebAppName", "Version", "State", "UserIdentityType", "Username", "Password", "OU", "Ip Address", "Administrators"

        }

    } catch {
        Add-Content .\failedservers.txt -Force -Value $computer
    }
}

$output | Export-Csv -Path .\output.csv
#Stop-Transcript

I'd really appreciate any input on how to get it to work properly or improve on the code itself.
Thanks in advance!

Body:
For the OU property, you'll want to reference $env:COMPUTERNAME instead of $_:

$item.OU = (Get-ADComputer $env:COMPUTERNAME |Select -Expand DistinguishedName)

For the IPAddress and Administrators fields you'll want to use -join to create comma-separated lists of the relevant values:

$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4).IPAddress -join ','
$item.Administrators = (Get-LocalGroupMember -Group "Administrators").Name -join ','


问:
PHP/SQL problem: Data from sql wont display
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

```<code>elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details<hr>";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="<table>";
                    $anoSulod.="    <tr><td>Name of employee : </td><td>".accessDatabase::hinoEmployee($empID)."</td></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="            <td>For the month ending : </td>";
                    $anoSulod.="            <td>";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            </td>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="    <tr><td>Basic Salary : PhP</td><td><input type='text' name='bs'></td></tr>";
                    $anoSulod.="    <tr><td>PERA/ACA : PhP</td><td><input type='text' name='pa'></td></tr>";
                    $anoSulod.="    <tr><td>PAIC : PhP</td><td><input type='text' name='pc'></td></tr>";
                    $anoSulod.="    <tr><td>REL : PhP</td><td><input type='text' name='rl'></td></tr>";
                    $anoSulod.="    <tr><td>GSIS Premium/Loans : PhP</td><td><input type='text' name='gs'></td></tr>";
                    $anoSulod.="    <tr><td>HDMF Premium/Loans : PhP</td><td><input type='text' name='hd'></td></tr>";
                    $anoSulod.="    <tr><td>Coop Loans : PhP</td><td><input type='text' name='cl'></td></tr>";
                    $anoSulod.="    <tr><td>Union Dues : PhP</td><td><input type='text' name='ud'></td></tr>";
                    $anoSulod.="    <tr><td>Withholding Tax : PhP</td><td><input type='text' name='tx'></td></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr><td colspan='2'><input type='submit' value='Save'></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="     <td colspan='2'>";
                    $anoSulod.="     <table border='1'>";

                    $anoSulod.="     <caption>Payroll Details</caption>";
                    $anoSulod.="     <tr>";
                    $anoSulod.="     <td> </td>";
                    $anoSulod.="     <td>Pay period</td>";
                    $anoSulod.="     <td>Basic Salary</td>";
                    $anoSulod.="     <td>PERA/ACA</td>";
                    $anoSulod.="     <td>PAIC</td>";
                    $anoSulod.="     <td>REL</td>";
                    $anoSulod.="     <td>GSIS Premium/Loans</td>";
                    $anoSulod.="     <td>HDMF Premium/Loans</td>";
                    $anoSulod.="     <td>Coop Loans</td>";
                    $anoSulod.="     <td>Union Dues</td>";
                    $anoSulod.="     <td>Withholding Tax</td>";
                    $anoSulod.="     </tr>";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="    <tr>";
                            $anoSulod.="     <td><input type='radio' name='payID' value='".$akonRows["payID"]."'></td>";
                            $anoSulod.="     <td>".$akonRows["date"]."</td>";
                            $anoSulod.="     <td>".$akonRows["bs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pa"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pc"]."</td>";
                            $anoSulod.="     <td>".$akonRows["rl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["gs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["hd"]."</td>";
                            $anoSulod.="     <td>".$akonRows["cl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["ud"]."</td>";
                            $anoSulod.="     <td>".$akonRows["tx"]."</td>";
                            $anoSulod.="    </tr>";
                        }
                    }
                    else
                    {
                        $anoSulod.="    <tr>";
                        $anoSulod.="     <td colspan='11' align='center'>No records found</td>";
                        $anoSulod.="    </tr>";
                    }

                    $anoSulod.="     </table>";

                    $anoSulod.="     </td>";
                    $anoSulod.="    </tr>";
                    $anoSulod.="</table>";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}
</code>```

Please help. I really can't figure out what went wrong. Please do... Thanks so much!

答:
UPDATE: (removing my previous answer as it's not correct)

Try printing the query, and run in manually. Then post the result back here so we can tell you more.

ContentLicense: CC BY-SA 3.0

Body:
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details
";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="
";
                    $anoSulod.="
Name of employee : 	".accessDatabase::hinoEmployee($empID)."
";
                    $anoSulod.="
";
                    $anoSulod.="            For the month ending : 	";
                    $anoSulod.="            ";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            	";
                    $anoSulod.="
";
                    $anoSulod.="
Basic Salary : PhP	<input type='text' name='bs'>
";
                    $anoSulod.="
PERA/ACA : PhP	<input type='text' name='pa'>
";
                    $anoSulod.="
PAIC : PhP	<input type='text' name='pc'>
";
                    $anoSulod.="
REL : PhP	<input type='text' name='rl'>
";
                    $anoSulod.="
GSIS Premium/Loans : PhP	<input type='text' name='gs'>
";
                    $anoSulod.="
HDMF Premium/Loans : PhP	<input type='text' name='hd'>
";
                    $anoSulod.="
Coop Loans : PhP	<input type='text' name='cl'>
";
                    $anoSulod.="
Union Dues : PhP	<input type='text' name='ud'>
";
                    $anoSulod.="
Withholding Tax : PhP	<input type='text' name='tx'>
";
                    $anoSulod.="

";
                    $anoSulod.="
<input type='submit' value='Save'>
";
                    $anoSulod.="

";
                    $anoSulod.="
";
                    $anoSulod.="     ";
                    $anoSulod.="
";

                    $anoSulod.="
Payroll Details
";
                    $anoSulod.="
";
                    $anoSulod.="      	";
                    $anoSulod.="     Pay period	";
                    $anoSulod.="     Basic Salary	";
                    $anoSulod.="     PERA/ACA	";
                    $anoSulod.="     PAIC	";
                    $anoSulod.="     REL	";
                    $anoSulod.="     GSIS Premium/Loans	";
                    $anoSulod.="     HDMF Premium/Loans	";
                    $anoSulod.="     Coop Loans	";
                    $anoSulod.="     Union Dues	";
                    $anoSulod.="     Withholding Tax	";
                    $anoSulod.="
";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="
";
                            $anoSulod.="     <input type='radio' name='payID' value='".$akonRows["payID"]."'>	";
                            $anoSulod.="     ".$akonRows["date"]."	";
                            $anoSulod.="     ".$akonRows["bs"]."	";
                            $anoSulod.="     ".$akonRows["pa"]."	";
                            $anoSulod.="     ".$akonRows["pc"]."	";
                            $anoSulod.="     ".$akonRows["rl"]."	";
                            $anoSulod.="     ".$akonRows["gs"]."	";
                            $anoSulod.="     ".$akonRows["hd"]."	";
                            $anoSulod.="     ".$akonRows["cl"]."	";
                            $anoSulod.="     ".$akonRows["ud"]."	";
                            $anoSulod.="     ".$akonRows["tx"]."	";
                            $anoSulod.="
";
                        }
                    }
                    else
                    {
                        $anoSulod.="
";
                        $anoSulod.="     No records found	";
                        $anoSulod.="
";
                    }

                    $anoSulod.="
";

                    $anoSulod.="     	";
                    $anoSulod.="
";
                    $anoSulod.="
";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}

Please help. I really can't figure out what went wrong. Please do... Thanks so much!


问:
TSQL to get missing records inside IN operator
I have a table like below in SQL Server:

```<code>create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');
</code>```

I'm writing a query with the IN operator as

```<code>SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')
</code>```

I can get the result, but I want to get the list of missing or not available records in the table like

```<code>|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+
</code>```

答:
For this, I would recommend using row constructor values() rather than in:

```<code>select c.city, case when a.city is null then 'Missing' else 'Available' end status
from values(('Rome'), ('Mumbai'), ('Dallas'), ('Delhi'), ('Moscow')) c(city)
left join address a on a.city = c.city
</code>```

If there are duplicates city in the address table, then exists is a better option:

```<code>select
    c.city,
    case when exists(select 1 from address a where a.city = c.city)
        then 'Available'
        else 'Missing'
end status
from values(('Rome'), ('Mumbai'), ('Dallas'), ('Delhi'), ('Moscow')) c(city)
</code>```

Body:
I have a table like below in SQL Server:

create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');

I'm writing a query with the IN operator as

SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')

I can get the result, but I want to get the list of missing or not available records in the table like

|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+

Body:
For this, I would recommend using row constructor values() rather than in:

select c.city, case when a.city is null then 'Missing' else 'Available' end status
from values(('Rome'), ('Mumbai'), ('Dallas'), ('Delhi'), ('Moscow')) c(city)
left join address a on a.city = c.city

If there are duplicates city in the address table, then exists is a better option:

select
    c.city,
    case when exists(select 1 from address a where a.city = c.city)
        then 'Available'
        else 'Missing'
end status
from values(('Rome'), ('Mumbai'), ('Dallas'), ('Delhi'), ('Moscow')) c(city)


问:
Change an object value inside a loop in JavaScript
I have an array of objects like this:

```<code>const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]
</code>```

I have to change each item name property to something like this :

```<code>...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}
</code>```

My attempt is to loop object like following :

```<code>data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})
</code>```

But this always console the original item and the name property value is not modified.

答:
try somthing like:

```<code>const newList = data.map(obj => {
return { _id: obj._id, name: { en: obj.name } }
});
</code>```

and the newList list is your new data list so you can do it:

```<code>data = newList;
</code>```

EDIT:

if you have more properties you can change the return line to:

```<code>return { ...obj, name: { en: obj.name } }
</code>```

what will happen here, it will deploy all the object properties as they are, and modify the name property, unfortunately, every property you want to modify, you have to re-write it.

Body:
I have an array of objects like this:

const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]

I have to change each item name property to something like this :

...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}

My attempt is to loop object like following :

data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})

But this always console the original item and the name property value is not modified.

Body:
try somthing like:

const newList = data.map(obj => {
return { _id: obj._id, name: { en: obj.name } }
});

and the newList list is your new data list so you can do it:

data = newList;

EDIT:

if you have more properties you can change the return line to:

return { ...obj, name: { en: obj.name } }

what will happen here, it will deploy all the object properties as they are, and modify the name property, unfortunately, every property you want to modify, you have to re-write it.


问:
C++: Rotating a vector around a certain point
I am trying to rotate a vector around a certain point on the vector(in C++):

```<code>1 2 3
4 5 6
7 8 9
</code>```

rotated around the point (1,1) (which is the "5")  90 degrees would result in:

```<code>7 4 1
8 5 2
9 6 3
</code>```

Right now I am using:

```<code>x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))
</code>```

But I don't want it rotated around (0,0)

答:
The solution is to translate the vector to a coordinate system in which the center of rotation is (0,0). Apply the rotation matrix and translate the vector back to the original coordinate system.</p>

```<code>dx = x of rotation center
dy = y of rotation center

V2 = V - [dx, dy, 0]
V3 = V2 * rotation matrix
Result = V3 + [dx, dy, 0]
</code>```

OwnerDisplayName: Erik Ahlswede

Body:
I am trying to rotate a vector around a certain point on the vector(in C++):

1 2 3
4 5 6
7 8 9

rotated around the point (1,1) (which is the "5")  90 degrees would result in:

7 4 1
8 5 2
9 6 3

Right now I am using:

x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))

But I don't want it rotated around (0,0)

Body:
The solution is to translate the vector to a coordinate system in which the center of rotation is (0,0). Apply the rotation matrix and translate the vector back to the original coordinate system.

dx = x of rotation center
dy = y of rotation center

V2 = V - [dx, dy, 0]
V3 = V2 * rotation matrix
Result = V3 + [dx, dy, 0]

OwnerDisplayName: Mehrdad Afshari


问:
.Net MVC3 Custom Model Binder - Initially Loading Model
I am creating a custom model binder to initially load a model from the database before updating the model with incoming values. (Inheriting from DefaultModelBinder)

Which method do I need to override to do this?

答:
You need to override the BindModel method of the DefaultModelBinder base class:</p>

```<code>    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(YourType))
        {
            var instanceOfYourType = ...;
            // load YourType from DB etc..

            var newBindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instanceOfYourType, typeof(YourType)),
                ModelState = bindingContext.ModelState,
                FallbackToEmptyPrefix = bindingContext.FallbackToEmptyPrefix,
                ModelName = bindingContext.FallbackToEmptyPrefix ? string.Empty : bindingContext.ModelName,
                ValueProvider = bindingContext.ValueProvider,
            };
            if (base.OnModelUpdating(controllerContext, newBindingContext)) // start loading..
            {
                // bind all properties:
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property1", false));
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property2", false));

                // trigger the validators:
                base.OnModelUpdated(controllerContext, newBindingContext);
            }

            return instanceOfYourType;
        }
        throw new InvalidOperationException("Supports only YourType objects");
    }
</code>```

Body:
You need to override the BindModel method of the DefaultModelBinder base class:

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(YourType))
        {
            var instanceOfYourType = ...;
            // load YourType from DB etc..

            var newBindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instanceOfYourType, typeof(YourType)),
                ModelState = bindingContext.ModelState,
                FallbackToEmptyPrefix = bindingContext.FallbackToEmptyPrefix,
                ModelName = bindingContext.FallbackToEmptyPrefix ? string.Empty : bindingContext.ModelName,
                ValueProvider = bindingContext.ValueProvider,
            };
            if (base.OnModelUpdating(controllerContext, newBindingContext)) // start loading..
            {
                // bind all properties:
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property1", false));
                base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property2", false));

                // trigger the validators:
                base.OnModelUpdated(controllerContext, newBindingContext);
            }

            return instanceOfYourType;
        }
        throw new InvalidOperationException("Supports only YourType objects");
    }


问:
BitBucket server Ctrl M character removal
We observed Ctrl+M character after the BitBucket migration from Perforce almost of the files. Do you have BitBucket-server level options/settings to remove the Ctrl+M chars in all the repository or from each repo/branch?
or else
Let us know if any other method this can be handled</p>

答:
The canonical way to store text files in Git is with LF endings, even if your project uses other endings, and to convert the line endings on checkout as necessary.  It sounds like your repository has CRLF line endings, and a CR character is also Ctrl-M (byte 13).

Servers do not get to modify data on clone because the integrity of data is verified by the hash, and consequently servers cannot change the line endings used.

If you wish to change the line endings for your repo, the easiest way to do that is to create a file called .gitattributes in the root of your repository with the following content, and then run git add --renormalize ., and commit that together:

```<code>* text=auto
</code>```

This will result in your files being checked in with LF endings and each user can control which line endings are used on their system.  By default, the platform's native line endings are used.

If you have patterns of files, such as shell scripts or PowerShell files, that must always use a given line ending, then you can add lines like this to .gitattributes:

```<code>*.sh eol=lf
*.ps1 eol=crlf
</code>```

You can read more about these options in the gitattributes manual page.

Body:
The canonical way to store text files in Git is with LF endings, even if your project uses other endings, and to convert the line endings on checkout as necessary.  It sounds like your repository has CRLF line endings, and a CR character is also Ctrl-M (byte 13).

Servers do not get to modify data on clone because the integrity of data is verified by the hash, and consequently servers cannot change the line endings used.

If you wish to change the line endings for your repo, the easiest way to do that is to create a file called .gitattributes in the root of your repository with the following content, and then run git add --renormalize ., and commit that together:

* text=auto

This will result in your files being checked in with LF endings and each user can control which line endings are used on their system.  By default, the platform's native line endings are used.

If you have patterns of files, such as shell scripts or PowerShell files, that must always use a given line ending, then you can add lines like this to .gitattributes:

*.sh eol=lf
*.ps1 eol=crlf

You can read more about these options in the gitattributes manual page.


问:
How to name Dockerfiles
I'm unsure of how to name Dockerfiles. Many on GitHub use Dockerfile without a file extension. Do I give them a name and extension; if so what? Or do I just call them Dockerfile?

答:
Dockerfile (custom name and folder):

```<code>   docker/app.Dockerfile
   docker/nginx.Dockerfile
</code>```

Build:

```<code>   docker build  -f ./docker/app.Dockerfile .
   docker build  -f ./docker/nginx.Dockerfile .
</code>```

Title: How to name Dockerfiles

Body:
Dockerfile (custom name and folder):

   docker/app.Dockerfile
   docker/nginx.Dockerfile

Build:

   docker build  -f ./docker/app.Dockerfile .
   docker build  -f ./docker/nginx.Dockerfile .


问:
is there any risk using std::addressof(std::cout) instead of &std::cout?
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

```<code>std::ostream *streamp;
streamp = &std::cout;
</code>```

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

```<code>std::ostream *streamp;
streamp = std::addressof(std::cout);
</code>```

答:
std::cout is an object, not a function, thus the rules forbidding taking the address of most standard functions don't apply.

std::addressof() is only needed where the address-operator might be overloaded (generally a bad thing to even consider), and thus is used in templates to avoid surprises. It is not needed for any standard types, and thus neither objects.

In conclusion, get the tool fixed or ignore that warning, your choice, but don't bend your code into a pretzel.

To expand on standard functions,  most functions in the standard library aren't designated "addressable".

Thus, taking their address might result in surprises, all the way from "working" by happenstance, over giving a function-pointer with an unexpected signature (more arguments, unexpected calling-convention, whatever), to failing to compile at all. And that might change with any change to the toolchain.

Body:
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

std::ostream *streamp;
streamp = &std::cout;

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

std::ostream *streamp;
streamp = std::addressof(std::cout);


问:
Why does one variable get the same value as another value
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

```<code>void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}

</code>```

答:
Your variable isn't initialised and will give undefined behaviour. This may include but not limited to -

Your program produces different results every time it is run.

Your program consistently produces the same result.

Your program works on some compilers but not others.

In your case, the uninitialised variable is probably pointing to the memory location storing the address of the initialised variable x. But atleast according to me, this wouldn't be the case everytime and would run in an undefined manner on different compilers or different machines.

Remember to Always initialise your variables

Body:
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
If there's any advantage, it's going to be in favor of the or. In reality, however, there's unlikely to be any difference on any reasonably modern CPU (or even anything but a really ancient one).

Basically, an or just sets the bit, and that's all. One two-input or gate is all that's needed, so you get exactly one gate of propagation delay.

An adder is a bit more complex: computing the current bit requires a three-input XOR. An XOR is normally composed to two levels of gates. In addition, it generates a carry, that has to be used as an input to the adder for the next bit. A "ripple carry adder", therefore, needs as many clock cycles as there are bits being added. There are cleverer ways of handling the problem where you handle carries separately from the rest of the addition, so you get a lower propagation delay, but in the worst case, even these don't help.

Most of that only matters if you're designing a CPU yourself though. If you're using a typical CPU, the gates in the functional units are running fast enough that it can/will do a full add in one clock cycle. Some reasonably recent ones can even do two adds per clock cycle in a single functional unit.

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
How to mock tls.PeerCertificate with Jest using Typescript?
I am able to mock getCertificate with jasmine like this:

```<code>const socket = new TLSSocket(new net.Socket())
socket.authorized = false
socket.authorizationError = Error('Invalid certificate')
//Mocking here
const spyOnGetCertificate = spyOn(socket, 'getCertificate').and.returnValue({'subject': {'CN': 'testing'}});
</code>```

However, when I try with jest:

```<code>const socket = new TLSSocket(new net.Socket())
socket.authorized = false
socket.authorizationError = Error('Invalid certificate')
//Mocking here
const spyOnGetCertificate = jest.spyOn(socket, 'getCertificate').mockImplementationOnce(() => {
  return {'subject': {'CN': 'testing'}}
})
socket.getCertificate = spyOnGetCertificate
</code>```

I get an error:

Type 'SpyInstance' is not assignable to type '() => object | PeerCertificate'.
    Type 'SpyInstance' provides no match for the signature '(): object | PeerCertificate'.ts(2322)

I still get the error when I have set all the PeerCertificate properties.

答:
Oops, don't need to do this ♂</p>

```<code>socket.getCertificate = spyOnGetCertificate
</code>```

Body:
I am able to mock getCertificate with jasmine like this:

const socket = new TLSSocket(new net.Socket())
socket.authorized = false
socket.authorizationError = Error('Invalid certificate')
//Mocking here
const spyOnGetCertificate = spyOn(socket, 'getCertificate').and.returnValue({'subject': {'CN': 'testing'}});

However, when I try with jest:

const socket = new TLSSocket(new net.Socket())
socket.authorized = false
socket.authorizationError = Error('Invalid certificate')
//Mocking here
const spyOnGetCertificate = jest.spyOn(socket, 'getCertificate').mockImplementationOnce(() => {
  return {'subject': {'CN': 'testing'}}
})
socket.getCertificate = spyOnGetCertificate

I get an error:

Type 'SpyInstance' is not assignable to type '() => object | PeerCertificate'.
    Type 'SpyInstance' provides no match for the signature '(): object | PeerCertificate'.ts(2322)

I still get the error when I have set all the PeerCertificate properties.

Body:
Oops, don't need to do this ♂

socket.getCertificate = spyOnGetCertificate


问:
How to find seg fault which doesn't occur when using tools
I ask this because the seg fault doesn't occur in my C++ program if I run it with Valgrind or GDB. But it's easily reproducible once I run it stand-alone as it will seg fault without fail. I have commented out sections of code to the point of making it run, but I have still been unable to find the exact cause. I fear it's happening earlier on and just showing up late.

Update:
   To clarify, this is C++ 17 on Linux.

答:
Looks like a typical race condition to me. Are you using any thread in your code? If so, consider using std::mutex when you access some data that might be used in other thread.
I always could debug such things only using TONS of debug prints, but beware, they also can slow down your code a bit and remove race condition.


问:
Save DateTimePicker value
How can I fix this error? I can't save this value:

private void button1_Click(object sender, EventArgs e)
{
    string rut = textRut.Text;
    string nombres = textNombres.Text;
    string paterno = textPaterno.Text;
    string materno = textMaterno.Text;
    DateTimePicker nacimiento = dateTimePicker1;
    DateTimePicker muerte = dateTimePicker2;
    string causa = causaText.Text;
    int cliente = int.Parse(comboCliente.Text);
    int enterrador = int.Parse(comboEnterrador.Text);
    int derecho = int.Parse(comboDerecho.Text);

    difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento, muerte, causa, enterrador, cliente, derecho);
    this.difuntoTableAdapter1.FillBy(this.cementerioDataSet1.difunto);
}
```

The type of both nacimiento and muerte in DB is date. How can I save that type of data in DB from DateTimePicker?

答:
The correct way to save it is

```<code>difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento.Value, muerte.Value,causa,enterrador,cliente,derecho);
</code>```

But the error message implies that the AgregarDifunto is expecting a string parameter here, not a date. This is in disagreement with your claim that this parameter relates to a date in the database. To resolve this we need to see the table definition and the query behind the AgregarDifunto method, possibly also some screenshots of the tableadapter query and its parameter set

Title: Save DateTimePicker value

Body:
How can I fix this error? I can't save this value:

private void button1_Click(object sender, EventArgs e)
{
    string rut = textRut.Text;
    string nombres = textNombres.Text;
    string paterno = textPaterno.Text;
    string materno = textMaterno.Text;
    DateTimePicker nacimiento = dateTimePicker1;
    DateTimePicker muerte = dateTimePicker2;
    string causa = causaText.Text;
    int cliente = int.Parse(comboCliente.Text);
    int enterrador = int.Parse(comboEnterrador.Text);
    int derecho = int.Parse(comboDerecho.Text);

    difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento, muerte, causa, enterrador, cliente, derecho);
    this.difuntoTableAdapter1.FillBy(this.cementerioDataSet1.difunto);
}

The type of both nacimiento and muerte in DB is date. How can I save that type of data in DB from DateTimePicker?

Body:
The correct way to save it is

difuntoTableAdapter1.AgregarDifunto(rut, nombres, paterno, materno, nacimiento.Value, muerte.Value,causa,enterrador,cliente,derecho);

But the error message implies that the AgregarDifunto is expecting a string parameter here, not a date. This is in disagreement with your claim that this parameter relates to a date in the database. To resolve this we need to see the table definition and the query behind the AgregarDifunto method, possibly also some screenshots of the tableadapter query and its parameter set


问:
Console log json value
I'm working with Testcafe and I would like to ask how to display on the console a json value.
For example, I have this link "https://jsonplaceholder.typicode.com/users"
I want to console the first username or all usernames for example.
Best regards!</p>

答:
The code given is an array of objects. You can use an inbuilt javascript array method, forEach() to filter through each object in the array. The forEach() method takes a function as a parameter that you can specify what you want to happen for each item in the array, in your example, log the unsername of the object.

```<code>console.log(string.forEach(obj =>{
    console.log(obj.username);
 })
);
</code>```

You can read about this more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Cheers

Title: Console log json value

Body:
The code given is an array of objects. You can use an inbuilt javascript array method, forEach() to filter through each object in the array. The forEach() method takes a function as a parameter that you can specify what you want to happen for each item in the array, in your example, log the unsername of the object.

console.log(string.forEach(obj =>{
    console.log(obj.username);
 })
);

You can read about this more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Cheers


问:
algorithm to read a matrix diagonally (all diagonalls)
i need an algorith that can read a matrix diagonally (all diagonals).

Example of input and output:

input:

```<code>matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
 ]
</code>```

and the output have to be like this:

```<code>["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]
</code>```

thank you for your help.

答:
Best way to think about this problem is that each cell on a single diagonal must satisfy  x+y=d  where d is the index of the diagonal(from 0 to n+m-2 inclusive).

You can loop over d and for each d loop over x. Using the equation above we get: y=d-x. I suggest you grab a paper and pen and derive the constraints for x yourself.

Anyway here's the working code:

matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
 ]

n = len(matrix)
m = len(matrix[0])

res = []
for d in range(n+m-1):
    cur = ""
    for x in range(max(0, d-m+1),min(n, d+1)):
        print(x, d-x)
        cur = matrix[x][d-x] + cur
    print('---')
    res.append(cur)
print(res)

```

Body:
i need an algorith that can read a matrix diagonally (all diagonals).

Example of input and output:

input:

matrix = [
["a", "b", "c", "d"],
["e", "f", "g", "h"],
["i", "j", "k", "l"],
["m", "n", "o", "p"]
 ]

and the output have to be like this:

["a", "eb", "ifc", "mjgd", "nkh", "ol","p"]

thank you for your help.


答:
Use a derived table using VALUES for all the cities in question and a CASE expression with EXISTS that checks if an address with a city exists.

```<code>SELECT city.name city,
       CASE
         WHEN EXISTS (SELECT *
                             FROM address
                             WHERE address.city = city.name) THEN
           'Available'
         ELSE
           'Missing'
       END status
       FROM (VALUES ('Rome'),
                    ('Mumbai'),
                    ('Dallas'),
                    ('Delhi'),
                    ('Moscow')) city (name);
</code>```

db<>fiddle

Title: TSQL to get missing records inside IN operator

Body:
I have a table like below in SQL Server:

create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');

I'm writing a query with the IN operator as

SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')

I can get the result, but I want to get the list of missing or not available records in the table like

|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+

Body:
Use a derived table using VALUES for all the cities in question and a CASE expression with EXISTS that checks if an address with a city exists.

SELECT city.name city,
       CASE
         WHEN EXISTS (SELECT *
                             FROM address
                             WHERE address.city = city.name) THEN
           'Available'
         ELSE
           'Missing'
       END status
       FROM (VALUES ('Rome'),
                    ('Mumbai'),
                    ('Dallas'),
                    ('Delhi'),
                    ('Moscow')) city (name);

db<>fiddle


问:
Arranging Divs to minimize spaces
Here's my problem: I have a group of divs which have varying amounts of content. They're floated left and I want them to line up so there's no vertical space between them (apart from the 10px margin I added.

here's an example on  jsFiddle

it's a bit like this question but i couldn't quite follow the suggestions

1st, is this possible? CSS or jQuery? If you know how to do this, please explain it to me.

Thanks

Si-Fi

答:
That´s not possible just with css, although I saw a sort of a solution using css3 columns but that´s not very cross-browser compatible.

You´ll have to use javascript, for example the Masonry jquery plugin.

Title: Arranging Divs to minimize spaces


问:
How to let user define custom properties in XAML?
I want the user to be able to input a custom value for GradientStop.Color and GradientStop.Name? How would I do this?</p>

```<code>                <Style TargetType="Rectangle">
                    <Setter Property="Fill">
                        <Setter.Value>
                            <RadialGradientBrush>
                                <RadialGradientBrush.GradientOrigin>0.5,0.5</RadialGradientBrush.GradientOrigin>
                                <RadialGradientBrush.Center>0.5,0.5</RadialGradientBrush.Center>
                                <RadialGradientBrush.RadiusX>0.5</RadialGradientBrush.RadiusX>
                                <RadialGradientBrush.RadiusY>0.5</RadialGradientBrush.RadiusY>
                                <RadialGradientBrush.Opacity>0</RadialGradientBrush.Opacity>
                                <GradientStop>
                                    <GradientStop.Color>White</GradientStop.Color>
                                    <GradientStop.Offset>0</GradientStop.Offset>
                                </GradientStop>
                                <GradientStop>
                                    <GradientStop.Color>Blue</GradientStop.Color>
                                    <GradientStop.Offset>1.9</GradientStop.Offset>
                                </GradientStop>
                            </RadialGradientBrush>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Grid.Resources>```

</code>```

答:
Tom,

If I were to do this, I would avoid doing any of it from xaml and instead do it programmatically.  By that, I mean in the code-behind, once you receive the user's custom value for Color and Name, I would build a new Style, RadialGradientBrush, etc. (basically everything you're doing in the xaml right now).  Then set the existing Rectangle's Style to this new Style that you created.

Body:
I want the user to be able to input a custom value for GradientStop.Color and GradientStop.Name? How would I do this?

            </Grid.Resources>```


问:
Exclude the "No image url" using jsoup java
I have the following code which is working perfectly to get the image URL from a webpage and then download it. But at someplace the image is not found and it is storing a dummy png. I want that if "No Image Available" then it should not download the image and skip it.

```<code>        Document document = Jsoup.connect(webpageURL).userAgent("Mozilla/17.0").get();
        Elements elements = document.select("div.img-container.ratio-11-10");

        for (Element e : elements) {
            Element imageElement = e.getElementsByTag("img").first();

            String imageURL = imageElement.attr("abs:src");
            InputStream inputStream = new URL(imageURL).openStream();

            Files.copy(inputStream, Paths.get("src/main/resources/" + ID + ".jpg"));
         }

</code>```

Sample HTML code from where I am extracting imageURL

img src="https://www.bbcgoodfood.com/sites/default/files/styles/recipe/public/sites/all/themes/bbcw_goodfood/images/dummy-content/member-recipe-icon.png" alt="No image available" title="No image available">

How could I modify my code so that it skips if the "No image available" exist?
thanks

答:
After you get the imageElement check the attribute value and continue to the next element:

```<code>if(imageElement.attr("alt").equals("No image available")){
    continue;
}
</code>```

Body:
I have the following code which is working perfectly to get the image URL from a webpage and then download it. But at someplace the image is not found and it is storing a dummy png. I want that if "No Image Available" then it should not download the image and skip it.

        Document document = Jsoup.connect(webpageURL).userAgent("Mozilla/17.0").get();
        Elements elements = document.select("div.img-container.ratio-11-10");

        for (Element e : elements) {
            Element imageElement = e.getElementsByTag("img").first();

            String imageURL = imageElement.attr("abs:src");
            InputStream inputStream = new URL(imageURL).openStream();

            Files.copy(inputStream, Paths.get("src/main/resources/" + ID + ".jpg"));
         }

Sample HTML code from where I am extracting imageURL

img src="https://www.bbcgoodfood.com/sites/default/files/styles/recipe/public/sites/all/themes/bbcw_goodfood/images/dummy-content/member-recipe-icon.png" alt="No image available" title="No image available">

How could I modify my code so that it skips if the "No image available" exist?
thanks

Body:
After you get the imageElement check the attribute value and continue to the next element:

if(imageElement.attr("alt").equals("No image available")){
    continue;
}


问:
CompilingClassLoader fun, any ideas how child class loads from different classloader in this case?
createController on line 29 in the below stack trace has clazz.getClasslo

```<code>protected Object createController(Injector injector, String controllerClassFullName) {
    Class<?> clazz = classLoader.clazzForName(controllerClassFullName);
    return injector.getInstance(clazz); //line 29!!!!
}
</code>```

loadClass online 521 is loading a class of the constructor of the above 'clazz' variable BUT is not loading from CompilingClassLoader.  It somehow is skipping it.  There are THREE parameters to the constructor all loading from CompilingClassLoader except the last one :(

Here is the constructor I am talking about(you can see it calling getDeclaredConstructors in the stack trace)

```<code>@Inject
public CustomerController(
        HashCreator hashCreator,
        TokenGenerator tokenGenerator,
        DataClientProxy clientProxy
) {
    this.hashCreator = hashCreator;
    this.tokenGenerator = tokenGenerator;
    this.clientProxy = clientProxy;
}
</code>```

Finally here is the stack trace

```<code>loadClass:521, ClassLoader (java.lang)
getDeclaredConstructors0:-1, Class (java.lang)
privateGetDeclaredConstructors:3137, Class (java.lang)
getDeclaredConstructors:2357, Class (java.lang)
forConstructorOf:245, InjectionPoint (com.google.inject.spi)
create:115, ConstructorBindingImpl (com.google.inject.internal)
createUninitializedBinding:706, InjectorImpl (com.google.inject.internal)
createJustInTimeBinding:930, InjectorImpl (com.google.inject.internal)
createJustInTimeBindingRecursive:852, InjectorImpl (com.google.inject.internal)
getJustInTimeBinding:291, InjectorImpl (com.google.inject.internal)
getBindingOrThrow:222, InjectorImpl (com.google.inject.internal)
getProviderOrThrow:1040, InjectorImpl (com.google.inject.internal)
getProvider:1071, InjectorImpl (com.google.inject.internal)
getProvider:1034, InjectorImpl (com.google.inject.internal)
getInstance:1086, InjectorImpl (com.google.inject.internal)
createController:29, DevLoader (org.webpieces.devrouter.impl)
</code>```

How in the world are the first two parameters loaded from CompilingClassLoader and the 3rd constructor is loaded from a normal ClassLoader.  I thought any children classes should go through the same classloader as the parent to load?

(I am trying to fix this as for some reason, the CompilingClassLoader is missing loading that class causing a very fun like existence of TWO DataApi.class objects loaded by different classloaders).

Hmmm, As I dig more, I found out I can call clazz.getMethods() BUT when I call clazz.getDeclaredConstructors(), then I get a ClassCircularityError.  The real funny thing is CustomerController nor DataClientProxy extend anyone so it's really weird.

Dean

答: Nastiness.  So, the file had the wrong package name.  While eclipse doesn't allow this and intellij flags it as red, gradle and java let it compile just fine but when we look for source, we can't find the source so it ends up we can't load it via the CompilingClassLoader causing a very confusing issue.  I can't even throw an exception to this effect telling the developer the package is wrong because I only receve classnames and have no idea if the package name is wrong or not since all   classes go through this classloader.  ick.</p>

Body:
createController on line 29 in the below stack trace has clazz.getClasslo

protected Object createController(Injector injector, String controllerClassFullName) {
    Class<?> clazz = classLoader.clazzForName(controllerClassFullName);
    return injector.getInstance(clazz); //line 29!!!!
}

loadClass online 521 is loading a class of the constructor of the above 'clazz' variable BUT is not loading from CompilingClassLoader.  It somehow is skipping it.  There are THREE parameters to the constructor all loading from CompilingClassLoader except the last one :(

Here is the constructor I am talking about(you can see it calling getDeclaredConstructors in the stack trace)

@Inject
public CustomerController(
        HashCreator hashCreator,
        TokenGenerator tokenGenerator,
        DataClientProxy clientProxy
) {
    this.hashCreator = hashCreator;
    this.tokenGenerator = tokenGenerator;
    this.clientProxy = clientProxy;
}

Finally here is the stack trace

loadClass:521, ClassLoader (java.lang)
getDeclaredConstructors0:-1, Class (java.lang)
privateGetDeclaredConstructors:3137, Class (java.lang)
getDeclaredConstructors:2357, Class (java.lang)
forConstructorOf:245, InjectionPoint (com.google.inject.spi)
create:115, ConstructorBindingImpl (com.google.inject.internal)
createUninitializedBinding:706, InjectorImpl (com.google.inject.internal)
createJustInTimeBinding:930, InjectorImpl (com.google.inject.internal)
createJustInTimeBindingRecursive:852, InjectorImpl (com.google.inject.internal)
getJustInTimeBinding:291, InjectorImpl (com.google.inject.internal)
getBindingOrThrow:222, InjectorImpl (com.google.inject.internal)
getProviderOrThrow:1040, InjectorImpl (com.google.inject.internal)
getProvider:1071, InjectorImpl (com.google.inject.internal)
getProvider:1034, InjectorImpl (com.google.inject.internal)
getInstance:1086, InjectorImpl (com.google.inject.internal)
createController:29, DevLoader (org.webpieces.devrouter.impl)

How in the world are the first two parameters loaded from CompilingClassLoader and the 3rd constructor is loaded from a normal ClassLoader.  I thought any children classes should go through the same classloader as the parent to load?

(I am trying to fix this as for some reason, the CompilingClassLoader is missing loading that class causing a very fun like existence of TWO DataApi.class objects loaded by different classloaders).

Hmmm, As I dig more, I found out I can call clazz.getMethods() BUT when I call clazz.getDeclaredConstructors(), then I get a ClassCircularityError.  The real funny thing is CustomerController nor DataClientProxy extend anyone so it's really weird.

Dean


答:
try    with {}

```<code>fetch('https://jsonplaceholder.typicode.com/users')
 .then(resp => resp.json())
 .then(data => {
   console.log( JSON.stringify( data , 0, 2))
   })
</code>```

to only usernames

```<code>fetch('https://jsonplaceholder.typicode.com/users')
 .then(resp => resp.json())
 .then(data =>
  {
  data.forEach(el=>console.log(el.username) )
  })

</code>```

Title: Console log json value

Body:
I'm working with Testcafe and I would like to ask how to display on the console a json value.
For example, I have this link "https://jsonplaceholder.typicode.com/users"
I want to console the first username or all usernames for example.
Best regards!

Body:
try    with {}

fetch('https://jsonplaceholder.typicode.com/users')
 .then(resp => resp.json())
 .then(data => {
   console.log( JSON.stringify( data , 0, 2))
   })

to only usernames

fetch('https://jsonplaceholder.typicode.com/users')
 .then(resp => resp.json())
 .then(data =>
  {
  data.forEach(el=>console.log(el.username) )
  })


问:
Change an object value inside a loop in JavaScript
I have an array of objects like this:

```<code>const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]
</code>```

I have to change each item name property to something like this :

```<code>...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}
</code>```

My attempt is to loop object like following :

```<code>data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})
</code>```

But this always console the original item and the name property value is not modified.

答:
I created a library to express transformations like this very simply.

const { pipe, fork, get } = require('rubico')

const data =
    [ { _id: '49847444033', name: 'yoko'}
    , { _id: '49847433333', name: 'doira'}
    ]

const onData = pipe([
  fork({
    _id: get('_id'), // data => data._id
    name: fork({ en: get('name') }), // data => ({ en: data.name })
  }),
  console.log,
])

data.map(onData) /*
{ _id: '49847444033', name: { en: 'yoko' } }
{ _id: '49847433333', name: { en: 'doira' } }
*/
```

I've commented the code above, but to really understand rubico and get started using it, I recommend you read the intuition and then the docs

Body:
I have an array of objects like this:

const data = [{
  _id:"49847444033",
  name:"yoko"
},{
  _id:"49847433333",
  name:"doira"
}]

I have to change each item name property to something like this :

...
{
  _id:"49847433333",
  name:{
      en:"John"
    }
}

My attempt is to loop object like following :

data.forEach((item) => {
   item.name = {en:"john"}
   console.log(item)
})

But this always console the original item and the name property value is not modified.

Body:
I created a library to express transformations like this very simply.

const { pipe, fork, get } = require('rubico')

const data =
    [ { _id: '49847444033', name: 'yoko'}
    , { _id: '49847433333', name: 'doira'}
    ]

const onData = pipe([
  fork({
    _id: get('_id'), // data => data._id
    name: fork({ en: get('name') }), // data => ({ en: data.name })
  }),
  console.log,
])

data.map(onData) /*
{ _id: '49847444033', name: { en: 'yoko' } }
{ _id: '49847433333', name: { en: 'doira' } }
*/

I've commented the code above, but to really understand rubico and get started using it, I recommend you read the intuition and then the docs


问:
Unity - Why is my ball rolling in the opposite direction when a projectile hits it?
For some odd reason, whenever my  rigidbody ball is rolling AWAY from me, and I "shoot it" with a rigidbody projectile, the ball changes direction and moves toward me, as opposed to away from me. Physics are working fine otherwise (if the ball is rolling towards the playerobject when shot with the projectile, the impact of the projectile bounces/knocks the ball away in a correct direction/physics way.)

My bounce code is attached, I use it to bounce the ball off walls/etc and it is working perfectly. I suppose its because the ball is always moving towards a wall when it strikes it. I'm stumped though as to why when I shoot the ball as its rolling away from me it changes direction immediately. I've tried different mass, drags, physics materials, gravity - everything I can think of to no avail.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BounceBall : MonoBehaviour
{
    private Rigidbody rb;
    public float bounceForce = 6f;
    Vector3 lastVelocity;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void LateUpdate()
    {
        lastVelocity = rb.velocity;
    }

    private void OnCollisionEnter(Collision collision)
    {
        GameObject hitObject = collision.gameObject;

        if (hitObject.tag == "Pusher")
        {
            float speed = lastVelocity.magnitude;
            Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
            rb.velocity = direction * Mathf.Max(speed, bounceForce * 3.5f);
        }
        else if (hitObject.tag == "Untagged")
        {
            float speed = lastVelocity.magnitude;
            Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
            rb.velocity = direction * Mathf.Max(speed, bounceForce);
        }
    }
}
</code>```

And the projectile code (don't think this has anything to do with it)

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Projectile : MonoBehaviour
{
    public GameObject projectile;
    [SerializeField] float projVel = 50f;
    [SerializeField] float projLifeTime = 3.5f;
    [SerializeField] float projTimer;
    private Rigidbody rb;

    void Start()
    {
        rb = projectile.GetComponent<Rigidbody>();
        projTimer = projLifeTime;
        //rb.AddForce(0,projVel,0, ForceMode.Impulse);
        rb.AddForce(transform.forward * projVel, ForceMode.Impulse);
    }

    private void Update()
    {
        projTimer -= Time.deltaTime;
        if(projTimer <= 0f)
        {
            Destroy(gameObject);
        }
    }
</code>```

答:
The problem is the method Vector3.Reflect(). If you put in a backwards velocity it will output a forward velocity. The method Vector3.Reflect() is meant for an object bouncing off a surface or ricochets.

What you want to do is use Rigidbody.AddForce()

Here's the documentation: https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

Body:
For some odd reason, whenever my  rigidbody ball is rolling AWAY from me, and I "shoot it" with a rigidbody projectile, the ball changes direction and moves toward me, as opposed to away from me. Physics are working fine otherwise (if the ball is rolling towards the playerobject when shot with the projectile, the impact of the projectile bounces/knocks the ball away in a correct direction/physics way.)

My bounce code is attached, I use it to bounce the ball off walls/etc and it is working perfectly. I suppose its because the ball is always moving towards a wall when it strikes it. I'm stumped though as to why when I shoot the ball as its rolling away from me it changes direction immediately. I've tried different mass, drags, physics materials, gravity - everything I can think of to no avail.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BounceBall : MonoBehaviour
{
    private Rigidbody rb;
    public float bounceForce = 6f;
    Vector3 lastVelocity;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void LateUpdate()
    {
        lastVelocity = rb.velocity;
    }

    private void OnCollisionEnter(Collision collision)
    {
        GameObject hitObject = collision.gameObject;

        if (hitObject.tag == "Pusher")
        {
            float speed = lastVelocity.magnitude;
            Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
            rb.velocity = direction * Mathf.Max(speed, bounceForce * 3.5f);
        }
        else if (hitObject.tag == "Untagged")
        {
            float speed = lastVelocity.magnitude;
            Vector3 direction = Vector3.Reflect(lastVelocity.normalized, collision.contacts[0].normal);
            rb.velocity = direction * Mathf.Max(speed, bounceForce);
        }
    }
}

And the projectile code (don't think this has anything to do with it)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Projectile : MonoBehaviour
{
    public GameObject projectile;
    [SerializeField] float projVel = 50f;
    [SerializeField] float projLifeTime = 3.5f;
    [SerializeField] float projTimer;
    private Rigidbody rb;

    void Start()
    {
        rb = projectile.GetComponent<Rigidbody>();
        projTimer = projLifeTime;
        //rb.AddForce(0,projVel,0, ForceMode.Impulse);
        rb.AddForce(transform.forward * projVel, ForceMode.Impulse);
    }

    private void Update()
    {
        projTimer -= Time.deltaTime;
        if(projTimer <= 0f)
        {
            Destroy(gameObject);
        }
    }


问:
clang++ undefined reference to function even though it exists
I'm trying to create some simple binary to call an exported function from the shared object libQREngine.camera.samsung.so

This is the source code:

```<code>#include <iostream>

extern "C" int Java_com_samsung_android_qrengine_QRBarcodeDecoder_getRecogObjectCount();

int main()
{
int test=  Java_com_samsung_android_qrengine_QRBarcodeDecoder_getRecogObjectCount();
return 0;
}
</code>```

This is how I try to compile and link it:

```<code>aarch64-linux-android29-clang++ -o test test.cpp -L./lib64 -lQREngine.camera.samsung  -Wl,-rpath ./lib64
</code>```

And this is the error message I get:

```<code>./lib64/libandroid_runtime.so: undefined reference to `jniThrowException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowNullPointerException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetReferent@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferBaseArrayOffset@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationCreate@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowIOException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniLogException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferBaseArray@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetFDFromFileDescriptor@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationDestroy@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationInit@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowExceptionFmt@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JNI_CreateJavaVM@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowRuntimeException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniSetFileDescriptorOfFD@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniCreateFileDescriptor@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferPointer@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferFields@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniRegisterNativeMethods@LIBNATIVEHELPER_1'
</code>```

I do understand libandroid_runtime.so needs to import these functions from "libnativehelper.so".
It's also written as the dependency when looking with readelf -d ./lib64/libandroid_runtime.so

```<code>0x0000000000000001 (NEEDED)             Shared library: [libnativehelper.so]
</code>```

nm -D ./lib64/libnativehelper.so also shows these functions exist as in:

```<code>00000000000034f0 T jniThrowExceptionFmt
0000000000003570 T jniThrowNullPointerException
0000000000003f58 T jniGetReferent
0000000000003d18 T jniGetNioBufferBaseArrayOffset
00000000000050e8 T JniInvocationCreate
0000000000003590 T jniThrowIOException
0000000000003608 T jniLogException
0000000000003c30 T jniGetNioBufferBaseArray
</code>```

And so on, I left some out on purpose not to make this post larger.
Strace also shows libnativehelper.so is being opened and closed at some point before the error happens.

Now I don't understand why the linker wouldn't use these functions even though they exist inside libnativehelper.so and that file is inside ./lib64/

Edit: It seems like this has something to do with the symbol versioning of libnativehelper.so. As you can see above the function "jniThrowException" and "jniThrowException@LIBNATIVEHELPER_1" are quiet different which is probably the reason the linker doesnt want to link them.

答:
It was the symbol versioning which resulted in having 2 functions, one expected the "LIBNATIVEHELPER_1" version while the libnativehelper.so couldn't provide that version even though it had these functions.

All I had to do was to compile libnativehelper.so through Googles AOSP build system (make sure you compile it in arm64) and take the one which had that version (by grepping)

Body:
I'm trying to create some simple binary to call an exported function from the shared object libQREngine.camera.samsung.so

This is the source code:

#include <iostream>

extern "C" int Java_com_samsung_android_qrengine_QRBarcodeDecoder_getRecogObjectCount();

int main()
{
int test=  Java_com_samsung_android_qrengine_QRBarcodeDecoder_getRecogObjectCount();
return 0;
}

This is how I try to compile and link it:

aarch64-linux-android29-clang++ -o test test.cpp -L./lib64 -lQREngine.camera.samsung  -Wl,-rpath ./lib64

And this is the error message I get:

./lib64/libandroid_runtime.so: undefined reference to `jniThrowException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowNullPointerException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetReferent@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferBaseArrayOffset@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationCreate@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowIOException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniLogException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferBaseArray@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetFDFromFileDescriptor@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationDestroy@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JniInvocationInit@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowExceptionFmt@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `JNI_CreateJavaVM@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniThrowRuntimeException@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniSetFileDescriptorOfFD@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniCreateFileDescriptor@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferPointer@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniGetNioBufferFields@LIBNATIVEHELPER_1'
./lib64/libandroid_runtime.so: undefined reference to `jniRegisterNativeMethods@LIBNATIVEHELPER_1'

I do understand libandroid_runtime.so needs to import these functions from "libnativehelper.so".
It's also written as the dependency when looking with readelf -d ./lib64/libandroid_runtime.so

0x0000000000000001 (NEEDED)             Shared library: [libnativehelper.so]

nm -D ./lib64/libnativehelper.so also shows these functions exist as in:

00000000000034f0 T jniThrowExceptionFmt
0000000000003570 T jniThrowNullPointerException
0000000000003f58 T jniGetReferent
0000000000003d18 T jniGetNioBufferBaseArrayOffset
00000000000050e8 T JniInvocationCreate
0000000000003590 T jniThrowIOException
0000000000003608 T jniLogException
0000000000003c30 T jniGetNioBufferBaseArray

And so on, I left some out on purpose not to make this post larger.
Strace also shows libnativehelper.so is being opened and closed at some point before the error happens.

Now I don't understand why the linker wouldn't use these functions even though they exist inside libnativehelper.so and that file is inside ./lib64/

Edit: It seems like this has something to do with the symbol versioning of libnativehelper.so. As you can see above the function "jniThrowException" and "jniThrowException@LIBNATIVEHELPER_1" are quiet different which is probably the reason the linker doesnt want to link them.