问:
When making a list, how can I make the multi-line sentence be even with the start of the other sentences?
As you can see at the bullet points 3 and 5, the sentence goes onto the next line and doesn't match up

my code:

ul {
  list-style: none;
}

ul li:before {
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul></code>```

答:
You could use display: flex on list-items to vertically align the text

ul {
  list-style: none;
}

ul li {
   line-height: 1.5;
   display: flex;
   align-items: flex-start }

ul li:before {
  content: '✓';
  margin-right: .5em;
  color: #4ab847;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma <br />vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu <br />gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul></code>```

Body:
As you can see at the bullet points 3 and 5, the sentence goes onto the next line and doesn't match up

my code:

ul {
  list-style: none;
}

ul li:before {
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}

Tehniskā palīdzība 24/7

Neierobežots norbraukums

Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā

Civiltiesiskā atbildība

Apdrošināšana avāriju un tehnisku bojājumu gadījumiem

Apdrošināšana zādzību gadījumā

Body:
You could use display: flex on list-items to vertically align the text

ul {
  list-style: none;
}

ul li {
   line-height: 1.5;
   display: flex;
   align-items: flex-start }

ul li:before {
  content: '✓';
  margin-right: .5em;
  color: #4ab847;
  font-weight: bold;
}

<ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma <br />vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu <br />gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul>


来源: stackexchange

问:
Unicode std::string class replacement
I'm looking for suggestions regarding unicode aware std::string library replacements. I have a bunch of code that uses std::string, its iterators etc, and would like to now support unicode strings (free or open source implementations preferred, regex capabilities would be great!).

I'm not sure at this point if I require a complete rewrite or if I can get away with dropping in a new string library that supports all of the std::string interfaces. The unicode world seems very complex and I'm just wanting to enable it in my applications not have to learn every single aspect of it.

btw how does the index operator work when it has to pass back a reference to either a 1, 2,3 or 4 structure which could in theory change to either a 1,2,3 or 4 byte structure.  if a larger or smaller sized value is passed, does the shifting back and forth of the internal data representation occur insitu?

答: Depending on your needs, use std::wstring or the larger and more complex (but de facto standard) ICU: http://site.icu-project.org/</p>

ContentLicense: CC BY-SA 3.0

Title: Unicode std::string class replacement


问:
Masking each word in sentence except first and last letter with a fixed amount of asterisks
I want to mask except first and last letter of word in sentence in oracle.

My query is:

```<code>select regexp_replace('Hello World', '(?<!^.?).(?!.?$)','*') as str2
   from dual;
</code>```

result: Hello World

Expect Result: H***o W***d

答:
If you want words to have the same length and asterisk out each character except for the first and last then you cannot do it with a simple regular expression (as Oracle does not support look-ahead/behind in its regular expressions). But you can do it with a recursive sub-query factoring clause that recursively finds each word and performs the masking on that word and then considers the next word in the string:

WITH replacements ( value, before, word, pos ) AS (
  SELECT value,
         CASE REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 )
         WHEN 0
         THEN value
         ELSE SUBSTR(
                value,
                1,
                REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 ) - 1
              )
         END,
         SUBSTR(
           value,
           REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 ),
           REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 1 )
           - REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 )
         ),
         REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 1 )
  FROM   test_data
UNION ALL
  SELECT value,
         before
         || CASE
            WHEN LENGTH(word) < 3
            THEN word
            ELSE SUBSTR(word,1,1) || LPAD( SUBSTR(word,-1), LENGTH(word)-1, '*' )
            END
         || CASE REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 )
            WHEN 0
            THEN SUBSTR( value, pos )
            ELSE SUBSTR(
                   value,
                   pos,
                   REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 ) - pos
                 )
            END,
         SUBSTR(
           value,
           REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 ),
           REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 1 )
           - REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 )
         ),
         REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 1 )
  FROM   replacements
  WHERE  pos > 0
)
SELECT value,
       before AS replaced_value
FROM   replacements
WHERE  pos = 0
```

<p>So for the test data:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE test_data( value ) AS
SELECT 'Hello World' FROM DUAL UNION ALL
SELECT 'A short sentence, with a "quote".' FROM DUAL UNION ALL
SELECT 'Some numbers 1000, 2000' FROM DUAL UNION ALL
SELECT '==Hello==World==' FROM DUAL UNION ALL
SELECT 'Be in at 10' FROM DUAL UNION ALL
SELECT '"!!!!"' FROM DUAL
</code>```

This outputs:

```
VALUE                             | REPLACED_VALUE
:-------------------------------- | :--------------------------------
"!!!!"                            | "!!!!"
Hello World                       | H***o W***d
==Hello==World==                  | ==H***o==W***d==
Some numbers 1000, 2000           | S**e n*****s 1**0, 2**0
Be in at 10                       | Be in at 10
A short sentence, with a "quote". | A s***t s******e, w**h a "q***e".
```

db<>fiddle here

ContentLicense: CC BY-SA 4.0

Body:
I want to mask except first and last letter of word in sentence in oracle.

My query is:

select regexp_replace('Hello World', '(?<!^.?).(?!.?$)','*') as str2
   from dual;

result: Hello World

Expect Result: H***o W***d

Body:
If you want words to have the same length and asterisk out each character except for the first and last then you cannot do it with a simple regular expression (as Oracle does not support look-ahead/behind in its regular expressions). But you can do it with a recursive sub-query factoring clause that recursively finds each word and performs the masking on that word and then considers the next word in the string:

WITH replacements ( value, before, word, pos ) AS (
  SELECT value,
         CASE REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 )
         WHEN 0
         THEN value
         ELSE SUBSTR(
                value,
                1,
                REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 ) - 1
              )
         END,
         SUBSTR(
           value,
           REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 ),
           REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 1 )
           - REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 0 )
         ),
         REGEXP_INSTR( value, '[[:alnum:]]+', 1, 1, 1 )
  FROM   test_data
UNION ALL
  SELECT value,
         before
         || CASE
            WHEN LENGTH(word) < 3
            THEN word
            ELSE SUBSTR(word,1,1) || LPAD( SUBSTR(word,-1), LENGTH(word)-1, '*' )
            END
         || CASE REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 )
            WHEN 0
            THEN SUBSTR( value, pos )
            ELSE SUBSTR(
                   value,
                   pos,
                   REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 ) - pos
                 )
            END,
         SUBSTR(
           value,
           REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 ),
           REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 1 )
           - REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 0 )
         ),
         REGEXP_INSTR( value, '[[:alnum:]]+', pos, 1, 1 )
  FROM   replacements
  WHERE  pos > 0
)
SELECT value,
       before AS replaced_value
FROM   replacements
WHERE  pos = 0

So for the test data:

CREATE TABLE test_data( value ) AS
SELECT 'Hello World' FROM DUAL UNION ALL
SELECT 'A short sentence, with a "quote".' FROM DUAL UNION ALL
SELECT 'Some numbers 1000, 2000' FROM DUAL UNION ALL
SELECT '==Hello==World==' FROM DUAL UNION ALL
SELECT 'Be in at 10' FROM DUAL UNION ALL
SELECT '"!!!!"' FROM DUAL

This outputs:

VALUE                             | REPLACED_VALUE
:-------------------------------- | :--------------------------------
"!!!!"                            | "!!!!"
Hello World                       | H***o W***d
==Hello==World==                  | ==H***o==W***d==
Some numbers 1000, 2000           | S**e n*****s 1**0, 2**0
Be in at 10                       | Be in at 10
A short sentence, with a "quote". | A s***t s******e, w**h a "q***e".

db<>fiddle here


问:
Firefox storage API : basic data save not saving
I'm working on my first Firefox extension. I'm trying to save data in the local storage of my browser (which was easy enough using Window.localStorage, but I'm following official recommandations).

My class has a save method that looks like that.

```<code>static save(content) {
  const setCurrent = browser.storage.local.set({ current: content });

  setCurrent.then((result) => {
    console.log('saved')
  }, onError);
}
</code>```

When it's called I get the 'saved' console.log, but when I look in the 'storage' tab of Firefox developpers tools, I see that nothing is saved. I don't know how to debug that.

答:
Thanks to @evilpie I found the solution. The data was available in 'Extension storage' tab and not in the 'local storage' one. Which is present only in the about:debugging toolbox, and not on the classic developper toolbox.

I was misled by my first try. When you use the Window.localStorage API, you can find all the data in any tab, in 'local storage'.

Body:
I'm working on my first Firefox extension. I'm trying to save data in the local storage of my browser (which was easy enough using Window.localStorage, but I'm following official recommandations).

My class has a save method that looks like that.

static save(content) {
  const setCurrent = browser.storage.local.set({ current: content });

  setCurrent.then((result) => {
    console.log('saved')
  }, onError);
}

When it's called I get the 'saved' console.log, but when I look in the 'storage' tab of Firefox developpers tools, I see that nothing is saved. I don't know how to debug that.


答:
Here is one way you can solve this.

ul {
  list-style: none;
}
ul li {
  position: relative;
  padding-left: 20px;
}
ul li:before {
  position: absolute;
  top: 0;
  left: 0;
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul></code>```

Please let me know if this helps.

Title: When making a list, how can I make the multi-line sentence be even with the start of the other sentences?

Body:
Here is one way you can solve this.

ul {
  list-style: none;
}
ul li {
  position: relative;
  padding-left: 20px;
}
ul li:before {
  position: absolute;
  top: 0;
  left: 0;
  content: '✓';
  color: #4ab847;
  font-weight: bold;
  line-height: 1.5em;
}

<ul>
  <li>Tehniskā palīdzība 24/7</li>
  <li>Neierobežots norbraukums</li>
  <li>Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā Maiņas automašīna satiksmes negadījuma vai zādzības gadījumā</li>
  <li>Civiltiesiskā atbildība</li>
  <li>Apdrošināšana avāriju un tehnisku bojājumu gadījumiem</li>
  <li>Apdrošināšana zādzību gadījumā</li>
</ul>

Please let me know if this helps.


问:
How to get value for a certain key in multidimentionnal php array?
A certain php array give me this :

```<code>myarray{
    0=>array { "key_01"=>"value_01", "key_02"=>"value_02"..."key_0n"=>"value_0n"}
    1=>array { "key_11"=>"value_11", "key_12"=>"value_12"..."key_1n"=>"value_1n"}
    .
    .
    .
    n=>array { "key_n1"=>"value_n1", "key_n2"=>"value_n2"..."key_nn"=>"value_nn"}
}
</code>```

And i would like to get this one array:

```<code>$newarray = {value_01,value_11,value_n1......value_nn}
</code>```

答:
You can use array_map to get what you want on each item of your array :

```<code>$array = array_map(function ($item) { return current($item); }, $array);
</code>```

In your case, this seems to be the first value of the item, so you use current.

Reference : https://www.php.net/manual/function.array-map.php

Body:
A certain php array give me this :

myarray{
    0=>array { "key_01"=>"value_01", "key_02"=>"value_02"..."key_0n"=>"value_0n"}
    1=>array { "key_11"=>"value_11", "key_12"=>"value_12"..."key_1n"=>"value_1n"}
    .
    .
    .
    n=>array { "key_n1"=>"value_n1", "key_n2"=>"value_n2"..."key_nn"=>"value_nn"}
}

And i would like to get this one array:

$newarray = {value_01,value_11,value_n1......value_nn}

Body:
You can use array_map to get what you want on each item of your array :

$array = array_map(function ($item) { return current($item); }, $array);

In your case, this seems to be the first value of the item, so you use current.

Reference : https://www.php.net/manual/function.array-map.php


问:
Azure Automation Account - Runbook Error - Object reference not set to an instance of an object
Last week, I deployed a script to backup some disks using the New-AzSnapshot cmdlet.
I scheduled this script in the Azure Automation Account and for the first 2 days, the script worked very well!

Today, I analyzed the logs and saw that the script had the error below:

Connect-AzAccount : Object reference not set to an instance of an object. At line:12 char:25 + $connectionResult = Connect-AzAccount ` + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], NullReferenceException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

Does anyone have any idea what may be causing this error?

Below the script:

```<code>Param(
    [string]$resourceGroupName
)

$connection = Get-AutomationConnection -Name AzureRunAsConnection
while (!($connectionResult) -And ($logonAttempt -le 10)) {
    $LogonAttempt++
    # Logging in to Azure...
    $connectionResult = Connect-AzAccount `
        -ServicePrincipal `
        -Tenant $connection.TenantID `
        -ApplicationID $connection.ApplicationID `
        -CertificateThumbprint $connection.CertificateThumbprint

    Start-Sleep -Seconds 30
}

# Remove old snapshots
$snapshotnames = (Get-AzSnapshot -ResourceGroupName $resourceGroupName).name
foreach($snapname in $snapshotnames)
{
    Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10080))} | Remove-AzSnapshot -Force
}

foreach ($VMs in Get-AzVM -ResourceGroupName $resourceGroupName) {
    #Set local variables
    $location = $VMs.Location
    #$resourceGroupName = $vmInfo.ResourceGroupName
    $timestamp = Get-Date -f MM-dd-yyyy_HH_mm_ss

    #Snapshot name of OS data disk
    $snapshotName = "bkp-" + $VMs.Name + "-" + $timestamp

    #Create snapshot configuration
    $snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.OsDisk.ManagedDisk.Id -Location $location  -CreateOption copy

    #Take snapshot
    New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName

    if ($VMs.StorageProfile.DataDisks.Count -ge 1) {
        #Condition with more than one data disks
        for ($i = 0; $i -le $VMs.StorageProfile.DataDisks.Count - 1; $i++) {

            #Snapshot name of OS data disk
            $snapshotName = "bkp-" + $VMs.StorageProfile.DataDisks[$i].Name + "-" + $timestamp

            #Create snapshot configuration
            $snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.DataDisks[$i].ManagedDisk.Id -Location $location  -CreateOption copy

            #Take snapshot
            New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName

        }
    }
    else {
        Write-Host $VMs.Name + " doesn't have any additional data disk."
    }
}
</code>```

答:
You're having a nullreference exception, looking at the location inside the error message (At line:12 char:25). it shows that connection is null.

You need to declare connection first on the same page before you're able to use the variables inside.

See also: What is a NullReferenceException, and how do I fix it?

EDIT: At second notice, I think that you're already declaring the $connection at

```<code>$connection = Get-AutomationConnection -Name AzureRunAsConnection
</code>```

but it looks like that's returning null. In that case, you'll need to figure out why that's returning null, because it should return a filled $connection if connected.

For a safe check to avoid errors: you should check first if the $connection is not null before entering the while, (for example $connection != null could work for Javascript). That way you won't get errors, but keep in mind that you won't get a result through this.

Body:
Last week, I deployed a script to backup some disks using the New-AzSnapshot cmdlet.
I scheduled this script in the Azure Automation Account and for the first 2 days, the script worked very well!

Today, I analyzed the logs and saw that the script had the error below:

Connect-AzAccount : Object reference not set to an instance of an object. At line:12 char:25 + $connectionResult = Connect-AzAccount ` + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], NullReferenceException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

Does anyone have any idea what may be causing this error?

Below the script:

Param(
    [string]$resourceGroupName
)

$connection = Get-AutomationConnection -Name AzureRunAsConnection
while (!($connectionResult) -And ($logonAttempt -le 10)) {
    $LogonAttempt++
    # Logging in to Azure...
    $connectionResult = Connect-AzAccount `
        -ServicePrincipal `
        -Tenant $connection.TenantID `
        -ApplicationID $connection.ApplicationID `
        -CertificateThumbprint $connection.CertificateThumbprint

    Start-Sleep -Seconds 30
}

# Remove old snapshots
$snapshotnames = (Get-AzSnapshot -ResourceGroupName $resourceGroupName).name
foreach($snapname in $snapshotnames)
{
    Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10080))} | Remove-AzSnapshot -Force
}

foreach ($VMs in Get-AzVM -ResourceGroupName $resourceGroupName) {
    #Set local variables
    $location = $VMs.Location
    #$resourceGroupName = $vmInfo.ResourceGroupName
    $timestamp = Get-Date -f MM-dd-yyyy_HH_mm_ss

    #Snapshot name of OS data disk
    $snapshotName = "bkp-" + $VMs.Name + "-" + $timestamp

    #Create snapshot configuration
    $snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.OsDisk.ManagedDisk.Id -Location $location  -CreateOption copy

    #Take snapshot
    New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName

    if ($VMs.StorageProfile.DataDisks.Count -ge 1) {
        #Condition with more than one data disks
        for ($i = 0; $i -le $VMs.StorageProfile.DataDisks.Count - 1; $i++) {

            #Snapshot name of OS data disk
            $snapshotName = "bkp-" + $VMs.StorageProfile.DataDisks[$i].Name + "-" + $timestamp

            #Create snapshot configuration
            $snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.DataDisks[$i].ManagedDisk.Id -Location $location  -CreateOption copy

            #Take snapshot
            New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName

        }
    }
    else {
        Write-Host $VMs.Name + " doesn't have any additional data disk."
    }
}

Body:
You're having a nullreference exception, looking at the location inside the error message (At line:12 char:25). it shows that connection is null.

You need to declare connection first on the same page before you're able to use the variables inside.

See also: What is a NullReferenceException, and how do I fix it?

EDIT: At second notice, I think that you're already declaring the $connection at

$connection = Get-AutomationConnection -Name AzureRunAsConnection

but it looks like that's returning null. In that case, you'll need to figure out why that's returning null, because it should return a filled $connection if connected.

For a safe check to avoid errors: you should check first if the $connection is not null before entering the while, (for example $connection != null could work for Javascript). That way you won't get errors, but keep in mind that you won't get a result through this.


问:
CGAL compiler error: undefined reference to `CGAL::assertion_fail(char const*, char const*, int, char const*)'
I'm a newbie of CGAL and I'm using CGAL 4.7-4 on Ubuntu 16.04.
I'm trying to compile and run a very simple .cpp. Here is the code:

```<code>#include <iostream>
#include <CGAL/Cartesian.h>

int main()
{
 int p=2;
 std::cout << "hello " << p << std::endl;
 return 0;
}
</code>```

I added the line

```<code>#include <CGAL/Cartesian.h>
</code>```

because I want to see how to compile with more libraries. Then I wrote this line on the terminal

```<code>g++ -lCGAL -lgmp prova.cpp
</code>```

but I got this error:

/tmp/cc9DA7Ml.o: In function 'CGAL::Interval_nt::Test_runtime_rounding_modes::Test_runtime_rounding_modes()':

prova.cpp:(.text._ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC5Ev]+0xd2): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

prova.cpp:(.text._ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC5Ev]+0x180): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

/tmp/cc9DA7Ml.o: In function 'CGAL::Interval_nt::Test_runtime_rounding_modes::Test_runtime_rounding_modes()':

prova.cpp:(.text._ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC5Ev]+0xd2): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

prova.cpp:(.text._ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC5Ev]+0x180): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

collect2: error: ld returned 1 exit status

I got the same error even if I wrote anyone of these lines:

```<code>g++ -lCGAL -lmpfr -lgmp prova.cpp

g++ -I/opt/local/include -L/opt/local/lib -lCGAL -lgmp prova.cpp

g++ -I/opt/local/include -L/opt/local/lib/ -lCGAL -lgmp prova.cpp

g++ -I/usr/include -L/usr/bin -lCGAL -lgmp prova.cpp

g++ -I/usr/bin -L/usr/lib -lCGAL -lgmp prova.cpp
</code>```

If I wrote

```<code>g++ -lCartesian.a -lCGAL -lgmp prova.cpp
</code>```

or

```<code>g++ -lCartesian -lCGAL -lgmp prova.cpp
</code>```

I got this error on the terminal

/usr/bin/ld: cannot find -lCartesian.a

collect2: error: ld returned 1 exit status

And at the end if I wrote

```<code>g++ -I/usr/include/CGAL -L/usr/include/CGAL -lCGAL -lgmp prova.cpp
</code>```

I got a very long list of errors like these:

In file included from /usr/include/CGAL/gmpxx_coercion_traits.h:35:0,

```<code>             from /usr/include/CGAL/mpz_class.h:29,
             from /usr/include/CGAL/gmpxx.h:47,
             from /usr/include/CGAL/is_convertible.h:28,
             from /usr/include/CGAL/Rational_traits.h:31,
             from /usr/include/CGAL/number_type_basic.h:48,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:
</code>```

/usr/include/mpfr.h:181:3: error: ‘mp_limb_t’ does not name a type
     mp_limb_t   *_mpfr_d;

/usr/include/mpfr.h:279:1: error: ‘__GMP_DECLSPEC’ does not name a type
   __MPFR_DECLSPEC __gmp_const char * mpfr_get_version _MPFR_PROTO ((void));

[...]

In file included from /usr/include/CGAL/mpz_class.h:29:0,

```<code>             from /usr/include/CGAL/gmpxx.h:47,
             from /usr/include/CGAL/is_convertible.h:28,
             from /usr/include/CGAL/Rational_traits.h:31,
             from /usr/include/CGAL/number_type_basic.h:48,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:
</code>```

/usr/include/CGAL/gmpxx_coercion_traits.h:43:3: error: ‘::__gmp_expr’ has not been declared

::__gmp_expr< T , U>,::__gmp_expr< T , U>  >{

[...]

And the long list finishes like this:

In file included from /usr/include/CGAL/double.h:30:0,

```<code>             from /usr/include/CGAL/number_type_basic.h:60,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:
</code>```

/usr/include/CGAL/number_utils.h: In instantiation of ‘typename CGAL::Real_embeddable_traits::Is_finite::result_type CGAL::is_finite(const Real_embeddable&) [with Real_embeddable = double; typename CGAL::Real_embeddable_traits::Is_finite::result_type = CGAL::Null_tag]’:

/usr/include/CGAL/double.h:201:27:   required from here

/usr/include/CGAL/number_utils.h:263:75: error: no match for call to ‘(CGAL::INTERN_RET::Real_embeddable_traits_base >::Is_finite {aka CGAL::Null_functor}) (const double&)’

```<code>return typename Real_embeddable_traits< Real_embeddable >::Is_finite()( x );
</code>```

I've looked around on the web a lot and I've understand something is wrong with the linking part of the compilation (no problem with the core), but I really don't have any idea about the solution. Do you have any idea? Thanks in advance for helping.

答:
Simply, use C++ version 14.

If you are using Qt then change your C++ version by doing the following in the .pro file.

```<code>CONFIG += c++14
</code>```

Body:
I'm a newbie of CGAL and I'm using CGAL 4.7-4 on Ubuntu 16.04.
I'm trying to compile and run a very simple .cpp. Here is the code:

#include <iostream>
#include <CGAL/Cartesian.h>

int main()
{
 int p=2;
 std::cout << "hello " << p << std::endl;
 return 0;
}

I added the line

#include <CGAL/Cartesian.h>

because I want to see how to compile with more libraries. Then I wrote this line on the terminal

g++ -lCGAL -lgmp prova.cpp

but I got this error:

/tmp/cc9DA7Ml.o: In function 'CGAL::Interval_nt::Test_runtime_rounding_modes::Test_runtime_rounding_modes()':

prova.cpp:(.text._ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC5Ev]+0xd2): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

prova.cpp:(.text._ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb0EE27Test_runtime_rounding_modesC5Ev]+0x180): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

/tmp/cc9DA7Ml.o: In function 'CGAL::Interval_nt::Test_runtime_rounding_modes::Test_runtime_rounding_modes()':

prova.cpp:(.text._ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC5Ev]+0xd2): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

prova.cpp:(.text._ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC2Ev[_ZN4CGAL11Interval_ntILb1EE27Test_runtime_rounding_modesC5Ev]+0x180): undefined reference to 'CGAL::assertion_fail(char const*, char const*, int, char const*)'

collect2: error: ld returned 1 exit status

I got the same error even if I wrote anyone of these lines:

g++ -lCGAL -lmpfr -lgmp prova.cpp

g++ -I/opt/local/include -L/opt/local/lib -lCGAL -lgmp prova.cpp

g++ -I/opt/local/include -L/opt/local/lib/ -lCGAL -lgmp prova.cpp

g++ -I/usr/include -L/usr/bin -lCGAL -lgmp prova.cpp

g++ -I/usr/bin -L/usr/lib -lCGAL -lgmp prova.cpp

If I wrote

g++ -lCartesian.a -lCGAL -lgmp prova.cpp

or

g++ -lCartesian -lCGAL -lgmp prova.cpp

I got this error on the terminal

/usr/bin/ld: cannot find -lCartesian.a

collect2: error: ld returned 1 exit status

And at the end if I wrote

g++ -I/usr/include/CGAL -L/usr/include/CGAL -lCGAL -lgmp prova.cpp

I got a very long list of errors like these:

In file included from /usr/include/CGAL/gmpxx_coercion_traits.h:35:0,

             from /usr/include/CGAL/mpz_class.h:29,
             from /usr/include/CGAL/gmpxx.h:47,
             from /usr/include/CGAL/is_convertible.h:28,
             from /usr/include/CGAL/Rational_traits.h:31,
             from /usr/include/CGAL/number_type_basic.h:48,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:

/usr/include/mpfr.h:181:3: error: ‘mp_limb_t’ does not name a type
     mp_limb_t   *_mpfr_d;

/usr/include/mpfr.h:279:1: error: ‘__GMP_DECLSPEC’ does not name a type
   __MPFR_DECLSPEC __gmp_const char * mpfr_get_version _MPFR_PROTO ((void));

[...]

In file included from /usr/include/CGAL/mpz_class.h:29:0,

             from /usr/include/CGAL/gmpxx.h:47,
             from /usr/include/CGAL/is_convertible.h:28,
             from /usr/include/CGAL/Rational_traits.h:31,
             from /usr/include/CGAL/number_type_basic.h:48,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:

/usr/include/CGAL/gmpxx_coercion_traits.h:43:3: error: ‘::__gmp_expr’ has not been declared

::__gmp_expr< T , U>,::__gmp_expr< T , U>  >{

[...]

And the long list finishes like this:

In file included from /usr/include/CGAL/double.h:30:0,

             from /usr/include/CGAL/number_type_basic.h:60,
             from /usr/include/CGAL/basic.h:44,
             from /usr/include/CGAL/Cartesian/Cartesian_base.h:28,
             from /usr/include/CGAL/Cartesian.h:28,
             from prova.cpp:2:

/usr/include/CGAL/number_utils.h: In instantiation of ‘typename CGAL::Real_embeddable_traits::Is_finite::result_type CGAL::is_finite(const Real_embeddable&) [with Real_embeddable = double; typename CGAL::Real_embeddable_traits::Is_finite::result_type = CGAL::Null_tag]’:

/usr/include/CGAL/double.h:201:27:   required from here

/usr/include/CGAL/number_utils.h:263:75: error: no match for call to ‘(CGAL::INTERN_RET::Real_embeddable_traits_base >::Is_finite {aka CGAL::Null_functor}) (const double&)’

return typename Real_embeddable_traits< Real_embeddable >::Is_finite()( x );

I've looked around on the web a lot and I've understand something is wrong with the linking part of the compilation (no problem with the core), but I really don't have any idea about the solution. Do you have any idea? Thanks in advance for helping.

Body:
Simply, use C++ version 14.

If you are using Qt then change your C++ version by doing the following in the .pro file.

CONFIG += c++14


问:
what will the equivalent statement of line in main?
```<code>class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){   // Consider this as line A
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  // Consider this as line B

    return 0;
}
</code>```

when i cout while overloading int() it displays 5 and when i replace int() with float() in line A , program displays 5.5.
I want to know how it is automatically calling the int() typecaster or the float() in cout?

答:
Compiler is allowed to perform one user-defined conversion implicitly when searching for matching function overload. Since you provide conversion from B to int, compiler can use that and select operator <<(std::ostream, int) overload of the << operator for std::cout.

If you would add another conversion to a type that is accepted by operator << for std::ostream (e.g. float), compiler would say that it is ambiguous call and it cannot choose by itself.

```<code>class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){
        return floatVar;
    }
    operator float(){
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  //error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'B')

    cout << static_cast<int>(floatObj); //explicit conversion, compiles
    return 0;
}
</code>```

Body:
class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){   // Consider this as line A
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  // Consider this as line B

    return 0;
}

when i cout while overloading int() it displays 5 and when i replace int() with float() in line A , program displays 5.5.
I want to know how it is automatically calling the int() typecaster or the float() in cout?

Body:
Compiler is allowed to perform one user-defined conversion implicitly when searching for matching function overload. Since you provide conversion from B to int, compiler can use that and select operator <<(std::ostream, int) overload of the << operator for std::cout.

If you would add another conversion to a type that is accepted by operator << for std::ostream (e.g. float), compiler would say that it is ambiguous call and it cannot choose by itself.

class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){
        return floatVar;
    }
    operator float(){
        return floatVar;
    }
};

int main()
{
    B floatObj(5.5);
    cout << floatObj;  //error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'B')

    cout << static_cast<int>(floatObj); //explicit conversion, compiles
    return 0;
}


问:
Android: How to get values in under specific xml tags
I want to get values under specific tags of my xml file (accessed via url) which look like this:

```<code><SyncLoginResponse>
    <Videos>
    <Video>
        <name>27/flv</name>
        <title>scooter</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>

    </Video>
    <Video>
        <name>26/flv</name>
        <title>barsNtone</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
    </Video>

    </Videos>
    <Slideshows>
    <Slideshow>
        <name>44</name>
        <title>ProcessFlow</title>
        <pages>4</pages>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>

    </Slideshow>
    </Slideshows>
<SyncLoginResponse>
</code>```

As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.

So far, I have the following codes:

EngagiaSync.java:

```<code>package com.example.engagiasync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("...PARSE AND DOWNLOAD...");

         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
              url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              String currentFile;
              String currentFileURL;
              int x = 1;
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();

                   tv.append("\nName:> " + dataItem.getName());
                   tv.append("\nTitle:> " + dataItem.getTitle());
                   tv.append("\nPages:> " + dataItem.getPages());
                   tv.append("\nFile:> " + dataItem.getUrl());

                   /*
                   int NumPages = Integer.parseInt(dataItem.getPages());

                   while( x <= NumPages ){
                       currentFile = dataItem.getName() + "-" + x + ".jpg";
                       currentFileURL = dataItem.getUrl() + currentFile;

                       tv.append("\nName: " + dataItem.getName());
                       tv.append("\nTitle: " + dataItem.getTitle());
                       tv.append("\nPages: " + NumPages );
                       tv.append("\nFile: " + currentFile);

                       startDownload(currentFile, currentFileURL);
                       x++;
                   }
                   */

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(String currentFile, String currentFileURL ){
        new DownloadFileAsync().execute(currentFile, currentFileURL);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading files...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... strings) {

            try {
                String currentFile = strings[0];
                String currentFileURL = strings[1];

                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(currentFileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       }

    }

}
</code>```

ExampleHandler.java:

```<code>package com.example.engagiasync;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be called on opening tags like:
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("Slideshow")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Slideshow")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("name")) {
               mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
          }else if (localName.equals("title"))  {
              mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
          }else if(localName.equals("pages"))  {
              mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
          }else if(localName.equals("url")){
              mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}
</code>```

ParsedExampleDataSet.java:

```<code>package com.example.engagiasync;

public class ParsedExampleDataSet {
    private String name = null;
    private String title = null;
    private String pages = null;
    private String url = null;

    //name
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }

    //title
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }

    //pages
    public String getPages(){
        return pages;
    }
    public void setPages(String pages){
        this.pages = pages;
    }

    //url
    public String getUrl(){
        return url;
    }
    public void setUrl(String url){
        this.url = url;
    }

    /*
    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }
    */

}
</code>```

The codes above returns the following result in the UI:

```<code>...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/
</code>```

In which I expect it to be:

```<code>...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/
</code>```

答:
```<code>public class XMLHandler extends DefaultHandler
{
    boolean result;
boolean customresult;
    String temp;

    @Override
    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
    {

        else if (localName.equalsIgnoreCase("result"))
        {
            result = true;
        }
        else if(localName.equalsIgnoreCase("customresult"))
        {
            customresult =true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)throws SAXException {

        /** set value */
        if (localName.equalsIgnoreCase("name") && result == true)
        {
                  String name = temp; //which is nothing but your name from result tag

        }
        else if(localName.equalsIgnoreCase("name") && result == true)
        {
            String name = temp; //which is nothing but your name from customresult tag
        }
            else if(localName.equalsIgnoreCase("result"))
        {
                 result = false;
        }
            else if(localName.equalsIgnoreCase("customresult"))
        {
                 customresult = false;
        }
    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)throws SAXException
    {
        temp = new String(ch, start, length);
    }

}
</code>```

That is all my friend If you find it useful then dont forget to mark it as an answer.

Body:
I want to get values under specific tags of my xml file (accessed via url) which look like this:

<SyncLoginResponse>
    <Videos>
    <Video>
        <name>27/flv</name>
        <title>scooter</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>

    </Video>
    <Video>
        <name>26/flv</name>
        <title>barsNtone</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
    </Video>

    </Videos>
    <Slideshows>
    <Slideshow>
        <name>44</name>
        <title>ProcessFlow</title>
        <pages>4</pages>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>

    </Slideshow>
    </Slideshows>
<SyncLoginResponse>

As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.

So far, I have the following codes:

EngagiaSync.java:

package com.example.engagiasync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("...PARSE AND DOWNLOAD...");

         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
              url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              String currentFile;
              String currentFileURL;
              int x = 1;
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();

                   tv.append("\nName:> " + dataItem.getName());
                   tv.append("\nTitle:> " + dataItem.getTitle());
                   tv.append("\nPages:> " + dataItem.getPages());
                   tv.append("\nFile:> " + dataItem.getUrl());

                   /*
                   int NumPages = Integer.parseInt(dataItem.getPages());

                   while( x <= NumPages ){
                       currentFile = dataItem.getName() + "-" + x + ".jpg";
                       currentFileURL = dataItem.getUrl() + currentFile;

                       tv.append("\nName: " + dataItem.getName());
                       tv.append("\nTitle: " + dataItem.getTitle());
                       tv.append("\nPages: " + NumPages );
                       tv.append("\nFile: " + currentFile);

                       startDownload(currentFile, currentFileURL);
                       x++;
                   }
                   */

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(String currentFile, String currentFileURL ){
        new DownloadFileAsync().execute(currentFile, currentFileURL);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading files...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }

    class DownloadFileAsync extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... strings) {

            try {
                String currentFile = strings[0];
                String currentFileURL = strings[1];

                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(currentFileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       }

    }

}

ExampleHandler.java:

package com.example.engagiasync;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be called on opening tags like:
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("Slideshow")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Slideshow")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("name")) {
               mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
          }else if (localName.equals("title"))  {
              mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
          }else if(localName.equals("pages"))  {
              mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
          }else if(localName.equals("url")){
              mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}

ParsedExampleDataSet.java:

package com.example.engagiasync;

public class ParsedExampleDataSet {
    private String name = null;
    private String title = null;
    private String pages = null;
    private String url = null;

    //name
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }

    //title
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }

    //pages
    public String getPages(){
        return pages;
    }
    public void setPages(String pages){
        this.pages = pages;
    }

    //url
    public String getUrl(){
        return url;
    }
    public void setUrl(String url){
        this.url = url;
    }

    /*
    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }
    */

}

The codes above returns the following result in the UI:

...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/

In which I expect it to be:

...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/

Body:
public class XMLHandler extends DefaultHandler
{
    boolean result;
boolean customresult;
    String temp;

    @Override
    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
    {

        else if (localName.equalsIgnoreCase("result"))
        {
            result = true;
        }
        else if(localName.equalsIgnoreCase("customresult"))
        {
            customresult =true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)throws SAXException {

        /** set value */
        if (localName.equalsIgnoreCase("name") && result == true)
        {
                  String name = temp; //which is nothing but your name from result tag

        }
        else if(localName.equalsIgnoreCase("name") && result == true)
        {
            String name = temp; //which is nothing but your name from customresult tag
        }
            else if(localName.equalsIgnoreCase("result"))
        {
                 result = false;
        }
            else if(localName.equalsIgnoreCase("customresult"))
        {
                 customresult = false;
        }
    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)throws SAXException
    {
        temp = new String(ch, start, length);
    }

}

That is all my friend If you find it useful then dont forget to mark it as an answer.


问:
Google Vision AutoML > Datasets | Validation data in csv doesn't upload
I am using Google Vision Automl. In order to train a model the data needs to be uploaded. There are following two ways.

Upload directly from your computer

Upload to google bucket and make a csv which contains the paths to the image files.

See the following image

Since, i want to compare my locally pre-trained model with the model i will train on Google Automl, i want to ensure that the same data splits are used (train, test, validation). So #2 way is the best way

Issue:
I have made a the csv in the following format. But when i upload it, only train and test sets are loaded.

答:
I solved it by putting "Validation" instead of "Validate" in the set column.

So the issue was the language used on the upload form, where they have the following.

Optionally, you can specify the TRAIN, VALIDATE, or TEST split.

Which is misleading and they also did not show the sample row for Validation.

For more details:
https://cloud.google.com/vision/automl/docs/prepare#csv


问:
Admin Password(Log in with a one password to webiste)
I have procjet which will allow only admin to post and log in without username or registiration. So that I just used Password. But where I stack is, the issue that me and some of my friends which are involved to therese codings couldnt solve.
This is a page that I referenced the code and the issue is same:NodeJS-PassportJS Giving The Certain Password

I have been using passport.js, nodejs and express.js with pug template.

This is my user.js model:

```<code> const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
    password:{
        type: String,
        required: true
      }
});
const User = module.exports = mongoose.model('User', UserSchema);
</code>```

This is my passport.js

```<code>const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');

module.exports = function(passport){
  // Local Strategy
  passport.use(new LocalStrategy(function(password){

    let query = {password:password};
    User.findOne(query, function(err, user){
      if(err) throw err;
      if(!user){
        return done(null, false, {message: 'No user found'});
      }

      // Match Password
      bcrypt.compare(password, user.password, function(err, isMatch){
        if(err) throw err;
        if(isMatch){
          return done(null, user);
        } else {
          return done(null, false, {message: 'Wrong password'});
        }
      });
    });
  }));

  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });

  });
}
</code>```

This is my users.js

```<code>const express = require("express");
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');

let User = require('../models/user');

// Register Form
router.get('/login', function(req, res){
    const password = req.body.password;
    req.checkBody('password', 'Password is required').notEmpty();

    let errors = req.validationErrors();

    res.render('login');
  });

  router.post('/login', function(req, res, next){
    passport.authenticate('local', {
      successRedirect:'/',
      failureRedirect:'/users/login',
      failureFlash: true
    })(req, res, next);
  });

  // logout
  router.get('/logout', function(req, res){
    req.logout();
    req.flash('success', 'You are logged out');
    res.redirect('/login');
  });

  module.exports = router;
</code>```

Also in db I have cerated a collection called user", because when I tried to do it with my code I find out the user. Maybe the problem can be in user.js(Models) or passport.js
this is my comamnd line mongodb:

```<code>db.createCollection('users');
...
db.users.insert{(password:'123'});
...
</code>```

I need yout help, please it is my school homework and I have promised for that, I want to apply my promise. Please help to me. How can solve this.

答:
by default passport.js LocalStrategy gets function like this:

```<code>    function(username, password, done){//...}
</code>```

Or, if you set { passReqToCallback: true }:

```<code>    function(req, username, password, done){//...}
</code>```

So, if you pass only one argument it will be username.

I think that you can solve it so:

```<code>    function(username, password, done){
         // Here's your code where you can not use 'username' and everything will be fine
    }
</code>```

Body:
I have procjet which will allow only admin to post and log in without username or registiration. So that I just used Password. But where I stack is, the issue that me and some of my friends which are involved to therese codings couldnt solve.
This is a page that I referenced the code and the issue is same:NodeJS-PassportJS Giving The Certain Password

I have been using passport.js, nodejs and express.js with pug template.

This is my user.js model:

 const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
    password:{
        type: String,
        required: true
      }
});
const User = module.exports = mongoose.model('User', UserSchema);

This is my passport.js

const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
const config = require('../config/database');
const bcrypt = require('bcryptjs');

module.exports = function(passport){
  // Local Strategy
  passport.use(new LocalStrategy(function(password){

    let query = {password:password};
    User.findOne(query, function(err, user){
      if(err) throw err;
      if(!user){
        return done(null, false, {message: 'No user found'});
      }

      // Match Password
      bcrypt.compare(password, user.password, function(err, isMatch){
        if(err) throw err;
        if(isMatch){
          return done(null, user);
        } else {
          return done(null, false, {message: 'Wrong password'});
        }
      });
    });
  }));

  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });

  });
}

This is my users.js

const express = require("express");
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');

let User = require('../models/user');

// Register Form
router.get('/login', function(req, res){
    const password = req.body.password;
    req.checkBody('password', 'Password is required').notEmpty();

    let errors = req.validationErrors();

    res.render('login');
  });

  router.post('/login', function(req, res, next){
    passport.authenticate('local', {
      successRedirect:'/',
      failureRedirect:'/users/login',
      failureFlash: true
    })(req, res, next);
  });

  // logout
  router.get('/logout', function(req, res){
    req.logout();
    req.flash('success', 'You are logged out');
    res.redirect('/login');
  });

  module.exports = router;

Also in db I have cerated a collection called user", because when I tried to do it with my code I find out the user. Maybe the problem can be in user.js(Models) or passport.js
this is my comamnd line mongodb:

db.createCollection('users');
...
db.users.insert{(password:'123'});
...

I need yout help, please it is my school homework and I have promised for that, I want to apply my promise. Please help to me. How can solve this.

Body:
by default passport.js LocalStrategy gets function like this:

    function(username, password, done){//...}

Or, if you set { passReqToCallback: true }:

    function(req, username, password, done){//...}

So, if you pass only one argument it will be username.

I think that you can solve it so:

    function(username, password, done){
         // Here's your code where you can not use 'username' and everything will be fine
    }


问:
What is the swift way of converting this string into PGN notation?
I have the following string

```<code>let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
</code>```

and want to convert this to PGN notation so the final result should be

```<code>result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"
</code>```

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

答:
With a simple regex and a loop (just to propose an original solution):

```<code>let a = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"

extension String {
    var chessPGN : String {
        var result = self
        let regex = try! NSRegularExpression(pattern: "0+")

        while let match = regex.matches(in: result, range: .init(location: 0, length: result.count)).first {
            if let stringRange = Range(match.range , in: result) {
                result.replaceSubrange(stringRange, with: match.range.length.description)
            }
        }

        return result
    }
}

print(a.chessPGN) // r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/
</code>```

EDIT: A version calling only once the regex

```<code>extension String {
    var chessPGN : String {
        var result = self
        let regex = try! NSRegularExpression(pattern: "0+")

        for match in regex.matches(in: result, range: .init(location: 0, length: result.count)).sorted(by: { $0.range.location > $1.range.location }) {
            if let stringRange = Range(match.range , in: result) {
                result.replaceSubrange(stringRange, with: match.range.length.description)
            }
        }

        return result
    }
}
</code>```

Body:
I have the following string

let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"

and want to convert this to PGN notation so the final result should be

result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

Body:
With a simple regex and a loop (just to propose an original solution):

let a = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"

extension String {
    var chessPGN : String {
        var result = self
        let regex = try! NSRegularExpression(pattern: "0+")

        while let match = regex.matches(in: result, range: .init(location: 0, length: result.count)).first {
            if let stringRange = Range(match.range , in: result) {
                result.replaceSubrange(stringRange, with: match.range.length.description)
            }
        }

        return result
    }
}

print(a.chessPGN) // r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/

EDIT: A version calling only once the regex

extension String {
    var chessPGN : String {
        var result = self
        let regex = try! NSRegularExpression(pattern: "0+")

        for match in regex.matches(in: result, range: .init(location: 0, length: result.count)).sorted(by: { $0.range.location > $1.range.location }) {
            if let stringRange = Range(match.range , in: result) {
                result.replaceSubrange(stringRange, with: match.range.length.description)
            }
        }

        return result
    }
}


问:
filter object in a functional way python 3
I have a list of Note objects called notesList. I want to filter my list based on the property codeCours in a functional pattern using a lambda, where I only want to keep the objects having the same codeCours.

With a list of Note objects

```<code>notesList = [Note(numeroEtudiant=1, codeCours=11, note=14),
    Note(numeroEtudiant=2, codeCours=11, note=16),
    Note(numeroEtudiant=2, codeCours=13, note=16)]
</code>```

I want to get all notes with a value for codeCours of 11:

```<code>[Note(numeroEtudiant:1 codeCours:11  note:14,
 Note(numeroEtudiant:2 codeCours:11  note:16)]
</code>```

Note is constructed with

class Note:
    def __init__(self, numeroEtudiant, codeCours, note):
        self.numeroEtudiant = numeroEtudiant
        self.codeCours = codeCours
        self.note = note
```

答:
If you really want to use filter and lambda, you can:

```<code>new_list = list(filter((lambda note: note.codeCours == 1), notesList))
</code>```

Although I find a list comprehension much more readable:

```<code>new_list = [note for note in notesList if note.codeCours == 1]
</code>```

Body:
I have a list of Note objects called notesList. I want to filter my list based on the property codeCours in a functional pattern using a lambda, where I only want to keep the objects having the same codeCours.

With a list of Note objects

notesList = [Note(numeroEtudiant=1, codeCours=11, note=14),
    Note(numeroEtudiant=2, codeCours=11, note=16),
    Note(numeroEtudiant=2, codeCours=13, note=16)]

I want to get all notes with a value for codeCours of 11:

[Note(numeroEtudiant:1 codeCours:11  note:14,
 Note(numeroEtudiant:2 codeCours:11  note:16)]

Note is constructed with

class Note:
    def __init__(self, numeroEtudiant, codeCours, note):
        self.numeroEtudiant = numeroEtudiant
        self.codeCours = codeCours
        self.note = note

Body:
If you really want to use filter and lambda, you can:

new_list = list(filter((lambda note: note.codeCours == 1), notesList))

Although I find a list comprehension much more readable:

new_list = [note for note in notesList if note.codeCours == 1]


问:
using custom init method in iphone -identifying a leak
For one of my custom classes, I have defined a method called initialize to set some instance variables at the same time as the init. The code is below. The analyzer tool is reporting a leak in viewDidLoad on the line with [[Employee alloc]..
Since I am releasing the variable in the dealloc, I thought that this should be fine..what could be the issue? thanks in advance.</p>

```<code>@interface testViewController : UIViewController <UITextFieldDelegate>{
    Employee *employee;
}
- (void)viewDidLoad {
if(employee ==nil)
   employee = [[Employee alloc] initialize:@"John"];

if (![employee.entityName isEqualToString:@"Test"]) { //The leak is reported here for object allocated above
    ///...
}

}

- (void)viewDidUnload {
    [super viewDidUnload];
    employee = nil;
}

- (void)dealloc {
    [super dealloc];
  [employee release];

}

//In the Employee class
-(id) initialize:(NSString*) name{
    self = [super init];

    self.entityName = name;

    return self;
}
</code>```

答:
In your viewDidUnLoad you need to release employee before it gets set to nil.  Else in your dealloc, you are just releasing nil.

ie

```<code>- (void)viewDidUnload {
    [super viewDidUnload];
    [employee release];
    employee = nil;
}
</code>```

Body:
For one of my custom classes, I have defined a method called initialize to set some instance variables at the same time as the init. The code is below. The analyzer tool is reporting a leak in viewDidLoad on the line with [[Employee alloc]..
Since I am releasing the variable in the dealloc, I thought that this should be fine..what could be the issue? thanks in advance.

@interface testViewController : UIViewController <UITextFieldDelegate>{
    Employee *employee;
}
- (void)viewDidLoad {
if(employee ==nil)
   employee = [[Employee alloc] initialize:@"John"];

if (![employee.entityName isEqualToString:@"Test"]) { //The leak is reported here for object allocated above
    ///...
}

}

- (void)viewDidUnload {
    [super viewDidUnload];
    employee = nil;
}

- (void)dealloc {
    [super dealloc];
  [employee release];

}

//In the Employee class
-(id) initialize:(NSString*) name{
    self = [super init];

    self.entityName = name;

    return self;
}

Body:
In your viewDidUnLoad you need to release employee before it gets set to nil.  Else in your dealloc, you are just releasing nil.

ie

- (void)viewDidUnload {
    [super viewDidUnload];
    [employee release];
    employee = nil;
}


问:
undefined object when i load data from server in knockout
I load a list from server controller in knockout and receive that list correctly, also i print that, but when put this data in a multiple table html , there is an error that says "Uncaught TypeError: Cannot read property 'push' of undefined"...

But if i do that in a button function click, everything ok, but i need that without press any button.

```<code><!DOCTYPE html>
<html>
    <head>
        <tittle> <h1>Customers </h1></tittle>

    </head>

    <body>

        <button  data-bind="click: addItem">Add</button>
        <p>List Names:</p>
        <select multiple="multiple" height="8" data-bind="options:allItems"> </select>

        <script type="text/javascript" src="/lib/knockout-3.5.0.js"></script>
        <script src="/lib/jquery-3.4.1.js"></script>
        <script src="/js/prueba.js"></script>

    </body>

</html>
</code>```

this is the .js

```<code>function ViewModel(){

    this.allItems= ko.observableArray([]);
    var list=[];

    $.get("/customers", function(data) {

        for(var i=0; i<data.length; i++){
            list[i]={name:data[i].name, lastname:data[i].lastname};
            alert(list[i].name);
            alert(list[i].lastname);
        }

        console.log(this.allItems); // here "allItems" is undefined
        this.allItems.push(list[0].name); //error
    });

    this.addItem= function(){

            console.log(this.allItems); // here "allItems" is not undefined
            this.allItems.push(list[0].name); //ok

    };

};

ko.applyBindings(new ViewModel());
</code>```

so... i need push this list at the beginning , anybody help?

答: Because your this in get method is not this this you think. You can assign this to self like var self = this; before this.allItems = ko.observableArray([]); and in your get method use self.allItems instead this.allItems.

Body:
I load a list from server controller in knockout and receive that list correctly, also i print that, but when put this data in a multiple table html , there is an error that says "Uncaught TypeError: Cannot read property 'push' of undefined"...

But if i do that in a button function click, everything ok, but i need that without press any button.

<!DOCTYPE html>

        <tittle>
Customers
</tittle>

        <button  data-bind="click: addItem">Add</button>

List Names:

        <select multiple="multiple" height="8" data-bind="options:allItems"> </select>

this is the .js

function ViewModel(){

    this.allItems= ko.observableArray([]);
    var list=[];

    $.get("/customers", function(data) {

        for(var i=0; i<data.length; i++){
            list[i]={name:data[i].name, lastname:data[i].lastname};
            alert(list[i].name);
            alert(list[i].lastname);
        }

        console.log(this.allItems); // here "allItems" is undefined
        this.allItems.push(list[0].name); //error
    });

    this.addItem= function(){

            console.log(this.allItems); // here "allItems" is not undefined
            this.allItems.push(list[0].name); //ok

    };

};

ko.applyBindings(new ViewModel());

so... i need push this list at the beginning , anybody help?


问:
ASP.NET MVC checkbox always false
I made an asp.net website, but the checkbox is always false. Why is this so?

Model:

```<code> public string Username { get; set; }
 public string Password { get; set; }
 public bool Remember { get; set; }
</code>```

CSHTML:

```<code><div class="form-group">
    @Html.Label("Remember me?")
    @Html.CheckBoxFor(m => m.Remember)
 </div>
</code>```

The Remember property is always false, if the checkbox is checked then Rememberis still false.

答:
With Razor, I had the same problem. What worked for me was taking off the value="xxx" tag.  Then it functioned normally.

Does not work:

```<code> <input class="form-check-input" value="true" asp-for="Answer.aIsCorrect" />
</code>```

Works:

```<code> <input class="form-check-input" asp-for="Answer.aIsCorrect" />
</code>```

Title: ASP.NET MVC checkbox always false

Body:
I made an asp.net website, but the checkbox is always false. Why is this so?

Model:

 public string Username { get; set; }
 public string Password { get; set; }
 public bool Remember { get; set; }

CSHTML:

    @Html.Label("Remember me?")
    @Html.CheckBoxFor(m => m.Remember)

The Remember property is always false, if the checkbox is checked then Rememberis still false.

Body:
With Razor, I had the same problem. What worked for me was taking off the value="xxx" tag.  Then it functioned normally.

Does not work:

 <input class="form-check-input" value="true" asp-for="Answer.aIsCorrect" />

Works:

 <input class="form-check-input" asp-for="Answer.aIsCorrect" />


问:
FileReplacements vs Environment variables
I have the case that I have to be able to deploy my Angular 6 project for two different servers, each with a slightly different API, user handling ect.
For this reason I added different abstraction layers in form of services to keep the interface to the rest of the code equal.

Because the files will have completely different content, I would like to write separate services in separate files and set only one set of services "active" for example to fetch data, handle the user ect.

```<code>app/
├── core/
│   ├── Server1.user.service.ts
│   ├── Server2.user.service.ts
│   ├── Server1.data.service.ts
│   ├── Server2.data.service.ts
│   └── ...
├── components/
│   ├── ...
│   └── ...
└── ...
</code>```

What I want to avoid by that is having a lot of if (deployedForServer1) {...}  in my code, as this is hard to maintain and difficult to keep an overview.

Now I am unsure, what is the best way to implement this.

My first approach would be to do it by replacing the services with "fileReplacements" in the angular.json. This has the advantage that only the code I need will be deployed, but results in a rather complicated angular.json configuration.

Another way would be to handle it over environment variables, but here I am not sure if I can avoid having multiple if (deployedForServer1) {...}-like querys in my code.

I dont mean this question to be one to answer with opinions, but rather information if one of these approaches is fundamentaly wrong or has any severe downsides I don't see right now.

答:
The second implementation if(deployedForServer1) { ... } is wrong and will become absolute nightmare for maintenance. If something changes, for example new api address, or new port, you will need to change the code and deploy new production version. Additionally, it scales very bad. If you want to deploy the app in 5 other servers, you will need to add that in the code.

If only the host address is what is dynamic, then you want to follow the principle: build once, deploy everywhere.

You can create a service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AppConfigService {
    constructor(
        private http: HttpClient
    ) { }

    private appSettings: any = {};

    setAppConfig() {

        if(environment.production) {
            return this.http.get('config.json')
                .toPromise()
                .then(apiKeys => {
                    this.appSettings = apiKeys;
                })
                .catch(error => {
                    console.error(error)
                    return Promise.reject();
                })
        } else {
            this.appSettings = environment.configToApi;
            return Promise.resolve();
        }

    }

    getAppSettings() {
        return this.appSettings;
    }
}

```

<p>Then you will call the <code>setAppConfig()</code> function in your <code>app.module</code> using <code>APP_INITIALIZER</code>:</p>

<pre class="lang-js prettyprint-override"><code>{
          provide: APP_INITIALIZER,
          useFactory: (appConfig: AppConfigService) => {
              return () => {
                  return appConfig.setAppConfig();
              }
          },
          multi: true,
          deps: [AppConfigService]
}
</code>```

You see, the service reads a local file config.json, which will hold server specific configurations:

```<code>{
    "apiAddress": "...",
    "apiAddress2": "..."
}

</code>```

The configuration is stored in the appSettings object in the service, and you can access the configuration anytime by calling getAppSettings().

The advantages of this approach are:

You build only once, and you can deploy everywhere

The configuration is set during runtime, instead build time. This means that any server configuration can be changed without building/deploying a new version.

Body:
I have the case that I have to be able to deploy my Angular 6 project for two different servers, each with a slightly different API, user handling ect.
For this reason I added different abstraction layers in form of services to keep the interface to the rest of the code equal.

Because the files will have completely different content, I would like to write separate services in separate files and set only one set of services "active" for example to fetch data, handle the user ect.

app/
├── core/
│   ├── Server1.user.service.ts
│   ├── Server2.user.service.ts
│   ├── Server1.data.service.ts
│   ├── Server2.data.service.ts
│   └── ...
├── components/
│   ├── ...
│   └── ...
└── ...

What I want to avoid by that is having a lot of if (deployedForServer1) {...}  in my code, as this is hard to maintain and difficult to keep an overview.

Now I am unsure, what is the best way to implement this.

My first approach would be to do it by replacing the services with "fileReplacements" in the angular.json. This has the advantage that only the code I need will be deployed, but results in a rather complicated angular.json configuration.

Another way would be to handle it over environment variables, but here I am not sure if I can avoid having multiple if (deployedForServer1) {...}-like querys in my code.

I dont mean this question to be one to answer with opinions, but rather information if one of these approaches is fundamentaly wrong or has any severe downsides I don't see right now.

Body:
The second implementation if(deployedForServer1) { ... } is wrong and will become absolute nightmare for maintenance. If something changes, for example new api address, or new port, you will need to change the code and deploy new production version. Additionally, it scales very bad. If you want to deploy the app in 5 other servers, you will need to add that in the code.

If only the host address is what is dynamic, then you want to follow the principle: build once, deploy everywhere.

You can create a service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable({
    providedIn: 'root'
})
export class AppConfigService {
    constructor(
        private http: HttpClient
    ) { }

    private appSettings: any = {};

    setAppConfig() {

        if(environment.production) {
            return this.http.get('config.json')
                .toPromise()
                .then(apiKeys => {
                    this.appSettings = apiKeys;
                })
                .catch(error => {
                    console.error(error)
                    return Promise.reject();
                })
        } else {
            this.appSettings = environment.configToApi;
            return Promise.resolve();
        }

    }

    getAppSettings() {
        return this.appSettings;
    }
}

Then you will call the setAppConfig() function in your app.module using APP_INITIALIZER:

{
          provide: APP_INITIALIZER,
          useFactory: (appConfig: AppConfigService) => {
              return () => {
                  return appConfig.setAppConfig();
              }
          },
          multi: true,
          deps: [AppConfigService]
}

You see, the service reads a local file config.json, which will hold server specific configurations:

{
    "apiAddress": "...",
    "apiAddress2": "..."
}

The configuration is stored in the appSettings object in the service, and you can access the configuration anytime by calling getAppSettings().

The advantages of this approach are:

You build only once, and you can deploy everywhere

The configuration is set during runtime, instead build time. This means that any server configuration can be changed without building/deploying a new version.


问:
How does Springboot use a database instead of a application.properties
I want to achieve is that springboot gets the property values configured in the database to complete the automatic configuration. Just like using application.properties</p>

答:
It is possible to programatically override Spring properties at startup. This would be a good place to retrieve the properties from any database that you whish and set them.

Here is an example (copy/pasted from this answer) . You would have to add getting the configuration from the database

```<code>@SpringBootApplication
public class Demo40Application{
  public static void main(String[] args){
    SpringApplication application = new SpringApplication(Demo40Application.class);

    Properties properties = new Properties();
    properties.put("server.port", 9999);
    application.setDefaultProperties(properties);

    application.run(args);
 }
}
</code>```

Body:
It is possible to programatically override Spring properties at startup. This would be a good place to retrieve the properties from any database that you whish and set them.

Here is an example (copy/pasted from this answer) . You would have to add getting the configuration from the database

@SpringBootApplication
public class Demo40Application{
  public static void main(String[] args){
    SpringApplication application = new SpringApplication(Demo40Application.class);

    Properties properties = new Properties();
    properties.put("server.port", 9999);
    application.setDefaultProperties(properties);

    application.run(args);
 }
}


问:
Always Commit the same file with SVN
In my web application I have a file which hold the current revision number via $Rev$. This work fine except, if I don't make any changes to that file, it doesn't get committed.

Is there anyway I can force a single file to always get committed to the SVN server?

I'm using TortoiseSVN for Windows so any code or step-by-step instructions would be helpful.

答:
I think you may be not understanding how the $Rev$ flag works. The goal of the Rev flag is not to have this revision always committed into the subversion repository. The goal is that on an update, the Rev flag will always be what the revision is. You should not need to put code into subversion that contains the revision. Subversion is very good at keeping track of that information for you.

What you probably missed is that, you need to set a property on the file so that the Revision keyword will be properly processed.

```<code>svn propset svn:keywords "Revision" file.txt
</code>```

This will ensure that whenever you do an update, the $Rev: xxx$ flag will be updated with the current revision. You don't need to worry about how it is committed to the repository.

ContentLicense: CC BY-SA 2.5

Title: Always Commit the same file with SVN

Body:
I think you may be not understanding how the $Rev$ flag works. The goal of the Rev flag is not to have this revision always committed into the subversion repository. The goal is that on an update, the Rev flag will always be what the revision is. You should not need to put code into subversion that contains the revision. Subversion is very good at keeping track of that information for you.

What you probably missed is that, you need to set a property on the file so that the Revision keyword will be properly processed.

svn propset svn:keywords "Revision" file.txt

This will ensure that whenever you do an update, the $Rev: xxx$ flag will be updated with the current revision. You don't need to worry about how it is committed to the repository.

OwnerDisplayName: Chris Dail


问:
Align ImageView to top right corner
I have a RelativeLayout with images next to each other. The number of images will be variable.

```<code>    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>
</code>```

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

答: make a new relative layout as a root layout and put your image view after your original relative layout </p>

Title: Align ImageView to top right corner

Body:
I have a RelativeLayout with images next to each other. The number of images will be variable.

    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.