问:
Batch Replace and add 1 to a number between specific text in an xml file
Ok i'm trying to write a batch to "grab" a serial number for the user. The serial number comes from another system and we have to periodically manually input a serial number.  I would like the user to run the batch file which would add 1 and replace the old number and then echo "Your serial number is ##" where ## is the new number. I'm pretty sure i can work out the Echo part and the writing to a temp file and overwriting the old file but its the middle part that im struggling with.
The xml file is that is being edited is:

```<code><?xml version="1.0"?>
<BatchSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SerialFormat>{0:yyMMdd}{1:00}</SerialFormat>
  <LastSerialDate>2020-05-27T00:00:00-05:00</LastSerialDate>
  <LastSerialNumber>10</LastSerialNumber>
</BatchSettings>
</code>```

the number i need to change is the ## between "lastserialnumber" <LastSerialNumber>10</LastSerialNumber>.
I've tried a few different approaches and this first one is close but definitely no cigar.

```<code>@echo off
set /a "replace=10"
set /a "replaced=replace+1"

set "source=Test.txt"
set "target=Test2.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal
</code>```

The problem with that one is the number won't always be "10" and I also don't want to replace all the other instances of "10" in the file.

I've also tried

```<code>@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for /f "delims=" %%a in (%SrcFile%
    ) do for /f "tokens=2 delims=1234567890 " %%b in ("%%~a"
    ) do if not "%%b"==":"  (
        echo(%%~a
    ) else for /f "tokens=1 delims=  <LastSerialNumber>:" %%c in ("%%~a"
    ) do (
        set /a "n=%%c+1"
        setlocal enabledelayedexpansion
        echo(<LastSerialNumber>!n!:
        endlocal
    )) > %OutFile%
</code>```

but that doesn't increment the number and cuts off the remaining text.
and this one is just a hot mess that doesn't work at all.

```<code>@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

setlocal EnableDelayedExpansion

(for /F "delims=" %%a in ('findstr /I /L "<LastSerialNumber>" %SrcFile%') do (
   set "line=%%a
   set "line=!line:*<LastSerialNumber>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b+1
)) > %oldnumber%

set "newnumber=%oldnumber%+1"

(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %SrcFile%') do (
      set "line=%%b"
      if defined line set "line=!line:%oldnumber%=%newnumber%!"
        echo(!line!
   )
) > %OutFile%
endlocal
</code>```

答:
Okay, i've finally got the code to work how i need. Just have to set directories which i've left off here for obvious reasons.  Thank you very much to aschipfl for the help.
This code indexes the serial number by one, writes to temp file, then writes back and deletes temp file. Then displays the new serial number.</p>

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=BatchTest.xml" & rem // (input file; `%~1` is the first argument)
set "_TAG=<LastSerialNumber>" & rem // (opening tag)

rem // Loop over all (non-empty) lines of the input file:
(for /F "usebackq delims=" %%L in ("%_FILE%") do (
    rem // Store current line string:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid troubles with `!`:
    setlocal EnableDelayedExpansion
    rem // Split off opening tag from line string:
    set "TEST=!LINE:*%_TAG%=!"
    rem // Check whether opening tag has been found:
    if not "!TEST!"=="!LINE!" (
        rem // Opening tag found, hence split off closing tag:
        for /F "tokens=1* eol=< delims=< " %%S in ("!TEST!") do (
            rem // Get extracted number and increment it:
            set /A "NUM=%%S+1"
        rem // Return rebuild line with incremented number:
            echo(  !_TAG!!NUM!^<%%T
        )
    ) else (
        rem // Opening tag not found, hence return original line:
        echo(!LINE!
    )
    endlocal
))>BatchTestTmp.xml

copy /v /y "BatchTestTmp.xml" "BatchTest.xml" & cls

del "BatchTestTmp.xml"

set "LINE=4"
(for /f "usebackq delims=" %%a in (`more +%LINE% BatchTest.xml`) DO (
set result=%%a
setlocal EnableDelayedExpansion
echo Your Serial Number is !result:~20,2!
pause
goto :leave
))
:leave
endlocal

exit /B
</code>```

Body:
Ok i'm trying to write a batch to "grab" a serial number for the user. The serial number comes from another system and we have to periodically manually input a serial number.  I would like the user to run the batch file which would add 1 and replace the old number and then echo "Your serial number is ##" where ## is the new number. I'm pretty sure i can work out the Echo part and the writing to a temp file and overwriting the old file but its the middle part that im struggling with.
The xml file is that is being edited is:

<?xml version="1.0"?>
<BatchSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SerialFormat>{0:yyMMdd}{1:00}</SerialFormat>
  <LastSerialDate>2020-05-27T00:00:00-05:00</LastSerialDate>
  <LastSerialNumber>10</LastSerialNumber>
</BatchSettings>

the number i need to change is the ## between "lastserialnumber" <LastSerialNumber>10</LastSerialNumber>.
I've tried a few different approaches and this first one is close but definitely no cigar.

@echo off
set /a "replace=10"
set /a "replaced=replace+1"

set "source=Test.txt"
set "target=Test2.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal

The problem with that one is the number won't always be "10" and I also don't want to replace all the other instances of "10" in the file.

I've also tried

@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for /f "delims=" %%a in (%SrcFile%
    ) do for /f "tokens=2 delims=1234567890 " %%b in ("%%~a"
    ) do if not "%%b"==":"  (
        echo(%%~a
    ) else for /f "tokens=1 delims=  <LastSerialNumber>:" %%c in ("%%~a"
    ) do (
        set /a "n=%%c+1"
        setlocal enabledelayedexpansion
        echo(<LastSerialNumber>!n!:
        endlocal
    )) > %OutFile%

but that doesn't increment the number and cuts off the remaining text.
and this one is just a hot mess that doesn't work at all.

@Echo Off
Set "SrcFile=Test.txt"
Set "OutFile=Test2.txt"

setlocal EnableDelayedExpansion

(for /F "delims=" %%a in ('findstr /I /L "<LastSerialNumber>" %SrcFile%') do (
   set "line=%%a
   set "line=!line:*<LastSerialNumber>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b+1
)) > %oldnumber%

set "newnumber=%oldnumber%+1"

(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %SrcFile%') do (
      set "line=%%b"
      if defined line set "line=!line:%oldnumber%=%newnumber%!"
        echo(!line!
   )
) > %OutFile%
endlocal

Body:
Okay, i've finally got the code to work how i need. Just have to set directories which i've left off here for obvious reasons.  Thank you very much to aschipfl for the help.
This code indexes the serial number by one, writes to temp file, then writes back and deletes temp file. Then displays the new serial number.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=BatchTest.xml" & rem // (input file; `%~1` is the first argument)
set "_TAG=<LastSerialNumber>" & rem // (opening tag)

rem // Loop over all (non-empty) lines of the input file:
(for /F "usebackq delims=" %%L in ("%_FILE%") do (
    rem // Store current line string:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid troubles with `!`:
    setlocal EnableDelayedExpansion
    rem // Split off opening tag from line string:
    set "TEST=!LINE:*%_TAG%=!"
    rem // Check whether opening tag has been found:
    if not "!TEST!"=="!LINE!" (
        rem // Opening tag found, hence split off closing tag:
        for /F "tokens=1* eol=< delims=< " %%S in ("!TEST!") do (
            rem // Get extracted number and increment it:
            set /A "NUM=%%S+1"
        rem // Return rebuild line with incremented number:
            echo(  !_TAG!!NUM!^<%%T
        )
    ) else (
        rem // Opening tag not found, hence return original line:
        echo(!LINE!
    )
    endlocal
))>BatchTestTmp.xml

copy /v /y "BatchTestTmp.xml" "BatchTest.xml" & cls

del "BatchTestTmp.xml"

set "LINE=4"
(for /f "usebackq delims=" %%a in (`more +%LINE% BatchTest.xml`) DO (
set result=%%a
setlocal EnableDelayedExpansion
echo Your Serial Number is !result:~20,2!
pause
goto :leave
))
:leave
endlocal

exit /B


来源: stackexchange

问:
WPF Triggers WebBrowser Navigating/Navigated
My Question :

How can i trigger webbrowser events like navigating/navigated so that i can animate the whole browser ?

I can't find those 2 actions in Triggers panel in Blend 4

答:
EventTriggers only work with RoutedEvents, those events are not routed.

You can handle those events and animate in code.

Apart from that you can use Blend's Interactivity:

```<code>xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
</code>```

```<code><WebBrowser>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Navigated">
            <i:EventTrigger.Actions>
                <ei:ControlStoryboardAction>
                    <ei:ControlStoryboardAction.Storyboard>
                        <!-- Storyboard here -->
                    </ei:ControlStoryboardAction.Storyboard>
                </ei:ControlStoryboardAction>
            </i:EventTrigger.Actions>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</WebBrowser>
</code>```

I am surprised that their use is not integrated into Blend's trigger editing UI.

ContentLicense: CC BY-SA 3.0

Body:
EventTriggers only work with RoutedEvents, those events are not routed.

You can handle those events and animate in code.

Apart from that you can use Blend's Interactivity:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

<WebBrowser>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Navigated">
            <i:EventTrigger.Actions>
                <ei:ControlStoryboardAction>
                    <ei:ControlStoryboardAction.Storyboard>
                        <!-- Storyboard here -->
                    </ei:ControlStoryboardAction.Storyboard>
                </ei:ControlStoryboardAction>
            </i:EventTrigger.Actions>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</WebBrowser>

I am surprised that their use is not integrated into Blend's trigger editing UI.


问:
How to apply a .fillna() to a filtered dataframe?
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

```<code>df[(df["pos"] == "GK") & (df["goals"].isnull())]
</code>```

How can I apply:

```<code>fillna(0, inplace=True)
</code>```

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

```<code>df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)
</code>```

答:
You already masked using a boolean select. So just <code>.fillna(0)</code>    </p>

```<code>df[(df["pos"] == "GK") & (df["goals"].isnull())].fillna(0)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

df[(df["pos"] == "GK") & (df["goals"].isnull())]

How can I apply:

fillna(0, inplace=True)

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)

Body:
You already masked using a boolean select. So just .fillna(0)

df[(df["pos"] == "GK") & (df["goals"].isnull())].fillna(0)


问:
Why am I getting Error while updating the flutter sdk?

Waiting for 0 seconds, press CTRL+C to quit ... Checking Dart SDK
  version... 'PowerShell.exe' is not recognized as an internal or
  external command, operable program or batch file. Error: Unable to
  update Dart SDK.

答:
Type these commands in your terminal:

```<code>flutter channel stable
</code>```

```<code>flutter upgrade
</code>```

Visit https://github.com/flutter/flutter/wiki/Hotfixes-to-the-Stable-Channel

Body:
Type these commands in your terminal:

flutter channel stable

flutter upgrade

Visit https://github.com/flutter/flutter/wiki/Hotfixes-to-the-Stable-Channel


问:
Materialize CSS & Angular 5 - Sticky Footer
I am trying to get my footer to be stickied to the bottom when the page's content doesn't reach the end of the screen.

I am building an Angular 5 application.

I added the ,  and  tags to my app.component.html.

I tried adding the required css from Materialize everywhere. In the global css file, the app.component css file, even in the Materialize css. I just don't know what I'm doing wrong.

Here is my app.component.html:

```<code><header>
    <app-navbar></app-navbar>
</header>
<main>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</main>
<app-footer></app-footer>
</code>```

The app-footer starts with this:

```<code><footer class="page-footer blue darken-2">
</code>```

I'd like to know where to put the css required for my footer to go to the bottom of the page.

答:
David Ortiz's answer worked for me!

However
It should be noted that the chunk:

```<code>body > app-root {
    display: flex;
    min-height: 100vh;
    flex-direction: column;
}
main {
    flex: 1 0 auto;
}
</code>```

had to be placed in the sitewide styles.css file for it to work.

Body:
I am trying to get my footer to be stickied to the bottom when the page's content doesn't reach the end of the screen.

I am building an Angular 5 application.

I added the ,  and  tags to my app.component.html.

I tried adding the required css from Materialize everywhere. In the global css file, the app.component css file, even in the Materialize css. I just don't know what I'm doing wrong.

Here is my app.component.html:

    <app-navbar></app-navbar>

        <router-outlet></router-outlet>

<app-footer></app-footer>

The app-footer starts with this:

I'd like to know where to put the css required for my footer to go to the bottom of the page.

Body:
David Ortiz's answer worked for me!

However
It should be noted that the chunk:

body > app-root {
    display: flex;
    min-height: 100vh;
    flex-direction: column;
}
main {
    flex: 1 0 auto;
}

had to be placed in the sitewide styles.css file for it to work.


问:
Why doesn't "case" with "when > 2" work?
Why is this not working?</p>

```<code>case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end
</code>```

答:
Use 1.0 / 0.0 to get infinity, which fixes @mosch's code:

```<code>case ARGV.length
  when 0
    raise "Too few"
  when 3..(1.0/0.0)
    raise "Too many"
end
</code>```

You don't have to be Chuck Norris to divide by a floating point zero.

Body:
Why is this not working?

case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end

Body:
Use 1.0 / 0.0 to get infinity, which fixes @mosch's code:

case ARGV.length
  when 0
    raise "Too few"
  when 3..(1.0/0.0)
    raise "Too many"
end

You don't have to be Chuck Norris to divide by a floating point zero.


问:
How do I upload DATETIME data with DolphinDB Python API
I was trying to upload some DATETIME data with DolphinDB Python API. I tried the following code.

```<code>from datetime import datetime
import dolphindb as ddb

sess = ddb.session('localhost', 8848)
sess.upload({'t': datetime(2020, 2, 2)})
</code>```

But I got the following exception.

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError: unrecognized Python type:

So how do I correctly upload the datetime data?

答:
I believe DolphinDB Python API only supports numpy.datetime64. Try the following script:</p>

```<code>sess.upload({'t':np.datetime64(datetime(2020,2,2))})
</code>```

Body:
I was trying to upload some DATETIME data with DolphinDB Python API. I tried the following code.

from datetime import datetime
import dolphindb as ddb

sess = ddb.session('localhost', 8848)
sess.upload({'t': datetime(2020, 2, 2)})

But I got the following exception.

Traceback (most recent call last):

File "", line 1, in

File "/home/ynwang/.local/lib/python3.6/site-packages/dolphindb/session.py", line 64, in upload

return self.cpp.upload(nameObjectDict)

RuntimeError: unrecognized Python type:

So how do I correctly upload the datetime data?

Body:
I believe DolphinDB Python API only supports numpy.datetime64. Try the following script:

sess.upload({'t':np.datetime64(datetime(2020,2,2))})


问:
How to include or in a for loop python
I'm trying my first little web scraping attempts with python and I have come across the following problem:

```<code>for resultat in tr.find_all(class_='tc fs-17 white bg-darkgrey p-r' or class_='tc fs-9 white bg-red mb-2 lh-data'):
    data.append(resultat.text)
</code>```

I need to ensure on the for loop that either the class_ is data is appended to the data. however, I have no clue how to do it.

A little help would be appreciated.

Regards,

答:
For simplicity, you can separate the loop. </p>

```<code>for resultat in tr.find_all(class_='tc fs-17 white bg-darkgrey p-r'):
    data.append(resultat.text)
for resultat in tr.find_all(class_='tc fs-9 white bg-red mb-2 lh-data'):
    data.append(resultat.text)
</code>```

Title: How to include or in a for loop python

Body:
I'm trying my first little web scraping attempts with python and I have come across the following problem:

for resultat in tr.find_all(class_='tc fs-17 white bg-darkgrey p-r' or class_='tc fs-9 white bg-red mb-2 lh-data'):
    data.append(resultat.text)

I need to ensure on the for loop that either the class_ is data is appended to the data. however, I have no clue how to do it.

A little help would be appreciated.

Regards,

Body:
For simplicity, you can separate the loop.

for resultat in tr.find_all(class_='tc fs-17 white bg-darkgrey p-r'):
    data.append(resultat.text)
for resultat in tr.find_all(class_='tc fs-9 white bg-red mb-2 lh-data'):
    data.append(resultat.text)


问:
Fetch PUT request gets Cache-Control header modified on Firefox and not Chrome
For the context, I'm creating presigned URL to upload to S3. For these requests the Cache-Control header has to be set to the value public, max-age=31536000, immutable.

I do the fetch with this code

```<code>fetch(
        uploadUrl,
        {
            method: 'PUT',
            cache: 'no-store',
            headers: { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=31536000, immutable' },
            body: data
        })
        .then(response => {
            if (response.ok) {
                doneFunc(publicUrl);
            } else {
                failureFunc(response.status);
            }
        })
        .catch(response => {
            failureFunc(response.status);
        });
</code>```

With Chrome the PUT request is actually sent with the Cache-Control header set in the fetch call public, max-age=31536000, immutable

With Firefox the PUT request is sent with the Cache-Control header set to public, max-age=31536000, immutable, no-cache. Notice the addition of no-cache at the end. This addition makes my presigned URL not valid.

I tried by removing the cache parameter, by setting it to no-cache and to no-store. Firefox always adds something to the Cache-Control header.

Do you know a way to make Firefox behaves like Chrome and respect the headers I set?

答:
Try using the Headers object to add headers.

```<code>const headers = new Headers();
headers.append('Content-Type', contentType);
headers.append('cache-control', 'public, max-age=31536000, immutable, no-store');

fetch(
        uploadUrl,
        {
            method: 'PUT',
            headers: headers,
            body: data
        })
        .then(response => {
            if (response.ok) {
                doneFunc(publicUrl);
            } else {
                failureFunc(response.status);
            }
        })
        .catch(response => {
            failureFunc(response.status);
        });
</code>```

My sample fetch request (if you want to test in firefox console)

```<code>const headers = new Headers();
headers.append('Content-Type', 'text/json');
headers.append('cache-control', 'public, max-age=31536000, immutable, no-custom');

const options = {
    method: 'PUT',
    headers: headers,
    body: JSON.stringify({})
};
fetch('https://www.mozilla.org/', options)
.then(response => console.log(response.ok ? 'done' : 'fail'))
.catch(response => console.log('fail catch'));
</code>```

Body:
For the context, I'm creating presigned URL to upload to S3. For these requests the Cache-Control header has to be set to the value public, max-age=31536000, immutable.

I do the fetch with this code

fetch(
        uploadUrl,
        {
            method: 'PUT',
            cache: 'no-store',
            headers: { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=31536000, immutable' },
            body: data
        })
        .then(response => {
            if (response.ok) {
                doneFunc(publicUrl);
            } else {
                failureFunc(response.status);
            }
        })
        .catch(response => {
            failureFunc(response.status);
        });

With Chrome the PUT request is actually sent with the Cache-Control header set in the fetch call public, max-age=31536000, immutable

With Firefox the PUT request is sent with the Cache-Control header set to public, max-age=31536000, immutable, no-cache. Notice the addition of no-cache at the end. This addition makes my presigned URL not valid.

I tried by removing the cache parameter, by setting it to no-cache and to no-store. Firefox always adds something to the Cache-Control header.

Do you know a way to make Firefox behaves like Chrome and respect the headers I set?

Body:
Try using the Headers object to add headers.

const headers = new Headers();
headers.append('Content-Type', contentType);
headers.append('cache-control', 'public, max-age=31536000, immutable, no-store');

fetch(
        uploadUrl,
        {
            method: 'PUT',
            headers: headers,
            body: data
        })
        .then(response => {
            if (response.ok) {
                doneFunc(publicUrl);
            } else {
                failureFunc(response.status);
            }
        })
        .catch(response => {
            failureFunc(response.status);
        });

My sample fetch request (if you want to test in firefox console)

const headers = new Headers();
headers.append('Content-Type', 'text/json');
headers.append('cache-control', 'public, max-age=31536000, immutable, no-custom');

const options = {
    method: 'PUT',
    headers: headers,
    body: JSON.stringify({})
};
fetch('https://www.mozilla.org/', options)
.then(response => console.log(response.ok ? 'done' : 'fail'))
.catch(response => console.log('fail catch'));


问:
Can I change the image file of an existing Evas_Object?

I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}
```

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

答:
In order for someone to be able to follow, I am testing this on one of the included samples, the "Chronograph Watch". In the file view.c there is the function view_chronograph_create_parts(). Here, all I do is to change the code from:

```<code>case PARTS_TYPE_HANDS_HOUR:
    s_info.hand_hour = part; // at this point, the image is already set
    break;
</code>```

to:

```<code>case PARTS_TYPE_HANDS_HOUR:
    s_info.hand_hour = part; // at this point, the image is already set

    elm_image_file_set(s_info.hand_hour, "images/chrono_hand_min.png", NULL);

    // I tried these two lines as well, but no change
    evas_object_move(s_info.hand_hour, 166, 0);
    evas_object_resize(s_info.hand_hour, 28, 360);

    break;
</code>```

The idea is to change the image of the hour hand after it was set initially, to see if elm_image_file_set() is successfully changing the image. But all I get is the hour hand being not visible at all.

Body:
I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

Body:
In order for someone to be able to follow, I am testing this on one of the included samples, the "Chronograph Watch". In the file view.c there is the function view_chronograph_create_parts(). Here, all I do is to change the code from:

case PARTS_TYPE_HANDS_HOUR:
    s_info.hand_hour = part; // at this point, the image is already set
    break;

to:

case PARTS_TYPE_HANDS_HOUR:
    s_info.hand_hour = part; // at this point, the image is already set

    elm_image_file_set(s_info.hand_hour, "images/chrono_hand_min.png", NULL);

    // I tried these two lines as well, but no change
    evas_object_move(s_info.hand_hour, 166, 0);
    evas_object_resize(s_info.hand_hour, 28, 360);

    break;

The idea is to change the image of the hour hand after it was set initially, to see if elm_image_file_set() is successfully changing the image. But all I get is the hour hand being not visible at all.


问:
regex to not allow continuous characters without space
Hi i am trying to not allow continuous characters without space assuming max length of word can be 25 chars.

Allowed -> hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb.

Not Allowed-> hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&

What i have tried

This will allow only alphanumeric and certain special characters

```<code>^[a-zA-Z0-9 ,()!'".\-_:/\\-]*$
</code>```

but not sure how to find continuous Words length greater than 25 chars without space

答:
Add a negative look ahead for 26 non whitespace chars that is anchored to start:

```<code>^(?!.*\S{26})[a-zA-Z0-9 ,()!'"._:/\\-]*$
</code>```

The hyphen char - was in your character class twice; this regex has one of them removed.

Body:
Hi i am trying to not allow continuous characters without space assuming max length of word can be 25 chars.

Allowed -> hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb.

Not Allowed-> hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&

What i have tried

This will allow only alphanumeric and certain special characters

^[a-zA-Z0-9 ,()!'".\-_:/\\-]*$

but not sure how to find continuous Words length greater than 25 chars without space

Body:
Add a negative look ahead for 26 non whitespace chars that is anchored to start:

^(?!.*\S{26})[a-zA-Z0-9 ,()!'"._:/\\-]*$

The hyphen char - was in your character class twice; this regex has one of them removed.


问:
How to test FileReader wrapped inside promise?
Current code:

```<code>export const readFilePromise = file => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = error => {
      reject(error);
    };
  });
};
</code>```

I am able to test the onload method

```<code>it('readFilePromise method', async () => {
    const fileContentsEncodedInHex = [
      '\x45\x6e\x63\x6f\x64\x65\x49\x6e\x48\x65\x78\x42\x65\x63\x61\x75\x73\x65\x42\x69\x6e\x61\x72\x79\x46\x69\x6c\x65\x73\x43\x6f\x6e\x74\x61\x69\x6e\x55\x6e\x70\x72\x69\x6e\x74\x61\x62\x6c\x65\x43\x68\x61\x72\x61\x63\x74\x65\x72\x73'
    ];
    const blob = new Blob(fileContentsEncodedInHex);
    const result = readFilePromise(blob);
    const output = await result;
    const expectedOutput =
      'data:;base64,RW5jb2RlSW5IZXhCZWNhdXNlQmluYXJ5RmlsZXNDb250YWluVW5wcmludGFibGVDaGFyYWN0ZXJz';
    expect(output).toEqual(expectedOutput);
  });
</code>```

I wonder how do I test the onerror?

答:
If you had something like below because of this

```<code>reader.onerror = () => {
  reject(reader.error);
};
</code>```

Then the below should work.

Just know beforehand error message for passing empty file or nothing. I just wanted to create a scenario

```<code> describe('Error Case', () => {
        it('should return error message for empty file', () => {
              const result = readFilePromise();
               const n = () => {};
               return result.then(n, (errorMessage) => {
                expect('your error message here').to.equal(errorMessage);
            });
        });
</code>```

Body:
Current code:

export const readFilePromise = file => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = error => {
      reject(error);
    };
  });
};

I am able to test the onload method

it('readFilePromise method', async () => {
    const fileContentsEncodedInHex = [
      '\x45\x6e\x63\x6f\x64\x65\x49\x6e\x48\x65\x78\x42\x65\x63\x61\x75\x73\x65\x42\x69\x6e\x61\x72\x79\x46\x69\x6c\x65\x73\x43\x6f\x6e\x74\x61\x69\x6e\x55\x6e\x70\x72\x69\x6e\x74\x61\x62\x6c\x65\x43\x68\x61\x72\x61\x63\x74\x65\x72\x73'
    ];
    const blob = new Blob(fileContentsEncodedInHex);
    const result = readFilePromise(blob);
    const output = await result;
    const expectedOutput =
      'data:;base64,RW5jb2RlSW5IZXhCZWNhdXNlQmluYXJ5RmlsZXNDb250YWluVW5wcmludGFibGVDaGFyYWN0ZXJz';
    expect(output).toEqual(expectedOutput);
  });

I wonder how do I test the onerror?

Body:
If you had something like below because of this

reader.onerror = () => {
  reject(reader.error);
};

Then the below should work.

Just know beforehand error message for passing empty file or nothing. I just wanted to create a scenario

 describe('Error Case', () => {
        it('should return error message for empty file', () => {
              const result = readFilePromise();
               const n = () => {};
               return result.then(n, (errorMessage) => {
                expect('your error message here').to.equal(errorMessage);
            });
        });


问:
Create regular expression from natural language
I would like to know where its possible to create regular expression from natural language in Java. To explain this, let me give a use case.

Support I want to check whether the following string is in correct format or not.

```<code>"aaaa-bbbb-cccc"
</code>```

The business definition of a valid string in this case is as follows:

```<code>4 letters, then hyphen, then 4 letters, then hyphen, then 4 letters.
</code>```

The usual way to implement this is to get the requirements from business and write the regex accordingly. But I am curious to know whether any libraries are available to create regex from natural language. So that we can ask business to provide the formats in a way that they can also understand.

答:
You might want to look at simply-regex library.

This is how you will be able to create regex within your code which will be self explanatory. Instead of having regex variable with typed string, you can have it built one time with readable code as per your requirements. Also easy to change later.

```<code>String builtRegex = SimpleRegex.regex().startingWith().exactString("abc")
                                   .then().oneOfTheCharacters('d', 'e', 'f')
                                   .build();
Pattern pattern = Pattern.compile(builtRegex);
boolean isMatch = pattern.matcher(testString).matches();
</code>```

Body:
I would like to know where its possible to create regular expression from natural language in Java. To explain this, let me give a use case.

Support I want to check whether the following string is in correct format or not.

"aaaa-bbbb-cccc"

The business definition of a valid string in this case is as follows:

4 letters, then hyphen, then 4 letters, then hyphen, then 4 letters.

The usual way to implement this is to get the requirements from business and write the regex accordingly. But I am curious to know whether any libraries are available to create regex from natural language. So that we can ask business to provide the formats in a way that they can also understand.

Body:
You might want to look at simply-regex library.

This is how you will be able to create regex within your code which will be self explanatory. Instead of having regex variable with typed string, you can have it built one time with readable code as per your requirements. Also easy to change later.

String builtRegex = SimpleRegex.regex().startingWith().exactString("abc")
                                   .then().oneOfTheCharacters('d', 'e', 'f')
                                   .build();
Pattern pattern = Pattern.compile(builtRegex);
boolean isMatch = pattern.matcher(testString).matches();


问:
Azure devops Yaml :how to set for loop over agent pool name
I have a use case to run the same stage on different Azure pool name, looking to have a logic to iterate over the pool name

Is there something like this which can work ?

```<code>stages:
- ${{ each name in parameters.poolNames }}:
 - stage: Stage1
   jobs:
   - job: Job1
     pool:
       name: ${{parameters.poolNames}}
     steps:
     - script: echo Hello, world!
       displayName: "Run echo hello world ${{parameters.regionName}} ${{parameters.poolName}}"
</code>```

答: I think what you are looking for is the matrix strategy. Have a look at this example, you should be able to adapt it your use case.</p>

Body:
I have a use case to run the same stage on different Azure pool name, looking to have a logic to iterate over the pool name

Is there something like this which can work ?

stages:
- ${{ each name in parameters.poolNames }}:
 - stage: Stage1
   jobs:
   - job: Job1
     pool:
       name: ${{parameters.poolNames}}
     steps:
     - script: echo Hello, world!
       displayName: "Run echo hello world ${{parameters.regionName}} ${{parameters.poolName}}"


问:
How to scrape specific data from scrape with simple html dom parser
I am trying to scrape the datas from a webpage, but I get need to get all the data in this link.

```<code>include 'simple_html_dom.php';
$html1 = file_get_html('http://www.aktive-buergerschaft.de/buergerstiftungen/unsere_leistungen/buergerstiftungsfinder');

$info1 = $html1->find('b[class=[what to enter herer ]',0);
</code>```

I need to get all the data out of this site.

```<code>Bürgerstiftung Lebensraum Aachen
    rechtsfähige Stiftung des bürgerlichen Rechts
    Ansprechpartner: Hubert Schramm
    Alexanderstr. 69/ 71
    52062 Aachen
    Telefon: 0241 - 4500130
    Telefax: 0241 - 4500131
    Email: info@buergerstiftung-aachen.de
    www.buergerstiftung-aachen.de
    >> Weitere Details zu dieser Stiftung

Bürgerstiftung Achim
    rechtsfähige Stiftung des bürgerlichen Rechts
    Ansprechpartner: Helga Kühn
    Rotkehlchenstr. 72
    28832 Achim
    Telefon: 04202-84981
    Telefax: 04202-955210
    Email: info@buergerstiftung-achim.de
    www.buergerstiftung-achim.de
    >> Weitere Details zu dieser Stiftung
</code>```

I need to have the data that are "behind" the link - is there any way to do this with a easy and understandable parser - one that can be understood and written by a newbie!?

答:
I'd use WWW:Mechanize

http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm

Body:
I am trying to scrape the datas from a webpage, but I get need to get all the data in this link.

include 'simple_html_dom.php';
$html1 = file_get_html('http://www.aktive-buergerschaft.de/buergerstiftungen/unsere_leistungen/buergerstiftungsfinder');

$info1 = $html1->find('b[class=[what to enter herer ]',0);

I need to get all the data out of this site.

Bürgerstiftung Lebensraum Aachen
    rechtsfähige Stiftung des bürgerlichen Rechts
    Ansprechpartner: Hubert Schramm
    Alexanderstr. 69/ 71
    52062 Aachen
    Telefon: 0241 - 4500130
    Telefax: 0241 - 4500131
    Email: info@buergerstiftung-aachen.de
    www.buergerstiftung-aachen.de
    >> Weitere Details zu dieser Stiftung

Bürgerstiftung Achim
    rechtsfähige Stiftung des bürgerlichen Rechts
    Ansprechpartner: Helga Kühn
    Rotkehlchenstr. 72
    28832 Achim
    Telefon: 04202-84981
    Telefax: 04202-955210
    Email: info@buergerstiftung-achim.de
    www.buergerstiftung-achim.de
    >> Weitere Details zu dieser Stiftung

I need to have the data that are "behind" the link - is there any way to do this with a easy and understandable parser - one that can be understood and written by a newbie!?


问:
Not reading the CSS - Express ejs layouts
I am using the express ejs layouts but only the mainPage can read the css the other pages don't read it (the css, the html read it).

Another question, if I wanted to use another layout (ex: layout2.ejs) what would i do to act on a specific page.

Tree:

Project

- public

    - js

    - css

        - style.css

- routes

    - index.js

    - users.js

- views

    - layout.ejs

    - mainPage.ejs

    - login.ejs

     ...

- app.js

I am using particles.js if you need to know.

app.js

```<code>const express = require('express');
const expL = require('express-ejs-layouts');

const app = express(); //Create a Web Application

//EJS
app.use(expL);
app.set('view engine', 'ejs')

//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));

app.listen(3000, ()=> console.log('Listening at 3000'));
app.use(express.static('public'))
</code>```

index.js

```<code>const express = require('express');
const router = express.Router();

router.get('/',(req, res) => {
    res.render('mainPage',{title: 'Groupy'}); (THIS ONE WORK AND READ THE CSS)
});

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

users.js

```<code>const express = require('express');
const router = express.Router();

//Login Page
router.get('/login',function(req, res) {
    res.render('login',{title: 'Groupy Login'}); (DON'T READ CSS)
});

//Register Page
router.get('/register',function(req, res) {
    res.render('register',{title: 'Groupy Register'}); (DON'T READ CSS)
});

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

layout.ejs

```<code><html>
<head>
    <script type="text/javascript" src="code.js"></script>
    <link rel="stylesheet" type="text/css" href="./css/style.css">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    </script>

    <title><%= title %></title>

</head>
<body>
    <div id="particles-js"> </div>
    <script src="js/particles.min.js"></script>
    <script src="js/app.js"></script>
    <h2>teste</h2>
    <%- body %>
</body>
</code>```

mainPage.ejs

```<code><h1 id="title">Groupy</h1>
    <div id="firstBox">
        <div id="SignIn"><a href="/users/register">Register </a><div id="login"><a href="/users/login">Login</a></div>
        </div>
    </div>
    <br>
   <div id="mainBox"></div>
</code>```

login.ejs

```<code><h1 id="title">Groupy Login</h1>
</code>```

Reseult of login (without CSS):

teste

Groupy Login

答:
Can you try the following app.use instead of app.use(express.static('public'))

```<code>app.use('/public', express.static(path.join(__dirname, 'public')));
</code>```

Also you should import path module

```<code>const path = require('path');
</code>```

Body:
I am using the express ejs layouts but only the mainPage can read the css the other pages don't read it (the css, the html read it).

Another question, if I wanted to use another layout (ex: layout2.ejs) what would i do to act on a specific page.

Tree:

Project

- public

    - js

    - css

        - style.css

- routes

    - index.js

    - users.js

- views

    - layout.ejs

    - mainPage.ejs

    - login.ejs

     ...

- app.js

I am using particles.js if you need to know.

app.js

const express = require('express');
const expL = require('express-ejs-layouts');

const app = express(); //Create a Web Application

//EJS
app.use(expL);
app.set('view engine', 'ejs')

//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));

app.listen(3000, ()=> console.log('Listening at 3000'));
app.use(express.static('public'))

index.js

const express = require('express');
const router = express.Router();

router.get('/',(req, res) => {
    res.render('mainPage',{title: 'Groupy'}); (THIS ONE WORK AND READ THE CSS)
});

module.exports = router;

users.js

const express = require('express');
const router = express.Router();

//Login Page
router.get('/login',function(req, res) {
    res.render('login',{title: 'Groupy Login'}); (DON'T READ CSS)
});

//Register Page
router.get('/register',function(req, res) {
    res.render('register',{title: 'Groupy Register'}); (DON'T READ CSS)
});

module.exports = router;

layout.ejs

    <link rel="stylesheet" type="text/css" href="./css/style.css">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    </script>

    <title><%= title %></title>

teste

    <%- body %>

mainPage.ejs

Groupy

Register
Login

login.ejs

Groupy Login

Reseult of login (without CSS):

teste

Groupy Login

Body:
Can you try the following app.use instead of app.use(express.static('public'))

app.use('/public', express.static(path.join(__dirname, 'public')));

Also you should import path module

const path = require('path');


问:
Haskell. Return the index of the first repeated number
A list of integers is given. Determine whether the list contains the same numbers that follow one after another. Return the index of the first repeated number or -1 if there are no repetitions.

The function should output:

```<code>duplicateIndex [1,8,3,3,4] -> 2
duplicateIndex [7,7,3,2,5] -> 0
duplicateIndex [1,2] -> -1
</code>```

I tried to solve as follows, but this solution is not correct!

```<code>let duplicateIndex lst =  [if x ==y then  lst !!x else (-1) |  x:ys <- tails lst, y <- ys]
</code>```

Help me fix the code.

答:
Your list comprehension expression returns a list element rather than a list index (as specified). Furthermore, there is nothing to keep track of the current index value.

If we look for a solution that is easy to visualize, we can try using zip. When it is about comparing 2 adjacent elements, it is common to use zip xs (tail xs) as an auxiliary list.

But that still does not include any information about indexes. For this, we have to add the index sequence as [0..].

As ultimately we aim to return an index, an interesting list comprehension expression would start like:

```<code>[ ... | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], ... constraints ... ]
</code>```

Let's see what our auxiliary list looks like:

```<code> λ>
 λ> printAsLines ys = mapM_  (putStrLn . show) ys
 λ>
 λ> xs = [1,8,3,3,4,7,5,5,2]
 λ>
 λ> printAsLines $ zip  (zip xs (tail xs))  [0..]
((1,8),0)
((8,3),1)
((3,3),2)
((3,4),3)
((4,7),4)
((7,5),5)
((5,5),6)
((5,2),7)
 λ>
</code>```

Furthermore, looking for a repeated number we need to have x == y as a constraint; and we want to return an index, so the left side of the list comprehension has to be idx. This gives:

```<code>[ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]
</code>```

Let's test it:

```<code> λ>
 λ> [ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]
 [2,6]
 λ>

</code>```

So we're almost done: we just need to take the first element of the last list comprehension, assuming of course there is a first element at all. Otherwise, return -1.

This gives the following code:

```<code>duplicateIndex :: Eq α => [α] -> Int
duplicateIndex xs =
    let  indexes = [ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]
    in
         if (null indexes) then  (-1)
                           else  head indexes
</code>```

The language lazyness ensures that the indexes list will not be evaluated beyond finding the first element.

EDIT:

The function can be written in more compact fashion using zip3:

```<code>duplicateIndex :: Eq α => [α] -> Int
duplicateIndex xs =
    let   idxs = [ idx | (x, y, idx)  <-  zip3  xs  (tail xs)  [0..],  x == y ]
    in    if  (null idxs)  then  (-1)  else  (head idxs)
</code>```

Body:
A list of integers is given. Determine whether the list contains the same numbers that follow one after another. Return the index of the first repeated number or -1 if there are no repetitions.

The function should output:

duplicateIndex [1,8,3,3,4] -> 2
duplicateIndex [7,7,3,2,5] -> 0
duplicateIndex [1,2] -> -1

I tried to solve as follows, but this solution is not correct!

let duplicateIndex lst =  [if x ==y then  lst !!x else (-1) |  x:ys <- tails lst, y <- ys]

Help me fix the code.

Body:
Your list comprehension expression returns a list element rather than a list index (as specified). Furthermore, there is nothing to keep track of the current index value.

If we look for a solution that is easy to visualize, we can try using zip. When it is about comparing 2 adjacent elements, it is common to use zip xs (tail xs) as an auxiliary list.

But that still does not include any information about indexes. For this, we have to add the index sequence as [0..].

As ultimately we aim to return an index, an interesting list comprehension expression would start like:

[ ... | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], ... constraints ... ]

Let's see what our auxiliary list looks like:

 λ>
 λ> printAsLines ys = mapM_  (putStrLn . show) ys
 λ>
 λ> xs = [1,8,3,3,4,7,5,5,2]
 λ>
 λ> printAsLines $ zip  (zip xs (tail xs))  [0..]
((1,8),0)
((8,3),1)
((3,3),2)
((3,4),3)
((4,7),4)
((7,5),5)
((5,5),6)
((5,2),7)
 λ>

Furthermore, looking for a repeated number we need to have x == y as a constraint; and we want to return an index, so the left side of the list comprehension has to be idx. This gives:

[ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]

Let's test it:

 λ>
 λ> [ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]
 [2,6]
 λ>

So we're almost done: we just need to take the first element of the last list comprehension, assuming of course there is a first element at all. Otherwise, return -1.

This gives the following code:

duplicateIndex :: Eq α => [α] -> Int
duplicateIndex xs =
    let  indexes = [ idx | ((x,y), idx) <- zip (zip xs (tail xs)) [0..], x == y ]
    in
         if (null indexes) then  (-1)
                           else  head indexes

The language lazyness ensures that the indexes list will not be evaluated beyond finding the first element.

EDIT:

The function can be written in more compact fashion using zip3:

duplicateIndex :: Eq α => [α] -> Int
duplicateIndex xs =
    let   idxs = [ idx | (x, y, idx)  <-  zip3  xs  (tail xs)  [0..],  x == y ]
    in    if  (null idxs)  then  (-1)  else  (head idxs)


问:
Set private setter on property via reflection
I know this has several canonical answers (that I've used successfully in the past!) See https://stackoverflow.com/a/1778410/1675729 and https://stackoverflow.com/a/1565766/1675729. For reference, these methods involve using the SetValue method on the PropertyInfo of the property, or otherwise invoking the setter method with reflection, or in extreme cases, setting the backing field directly. However, none of these methods seem to be working for me now, and I'm curious if something has changed that has broken this functionality.

Consider the following:

```<code>using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var exampleInstance = new Example();
        var exampleType = typeof(Example);
        var fooProperty = exampleType.GetProperty("Foo"); // this works fine - the "GetSetMethod" method returns null, however

        // fails with the following:
        // [System.MethodAccessException: Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.]
        //fooProperty.SetValue(exampleInstance, 24);

        // same error here:
        //Run-time exception (line 14): Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.
        //exampleType.InvokeMember(fooProperty.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, exampleInstance, new object[] { 24 });
    }
}

public class Example
{
    public int Foo { get; private set; }
}
</code>```

The Foo property has a setter, it's just private. It also fails if I change the setter to protected, which seems even more bizarre, since it's no longer the C#6 initializer-only setter. This fails with both .NET 4.5 and .NET Core 2 as the runtime. What am I missing?

答:
I was having a similar issue (with the exception that I'm using a static property) and I was able to invoke private setter like this:

```<code>public static class Example
{
    public static int Foo { get; private set; }
}

typeof(Example).GetProperty("Foo").SetMethod.Invoke(null, new object[] { 42});
</code>```

Haven't tested with non-static though.

Body:
I know this has several canonical answers (that I've used successfully in the past!) See https://stackoverflow.com/a/1778410/1675729 and https://stackoverflow.com/a/1565766/1675729. For reference, these methods involve using the SetValue method on the PropertyInfo of the property, or otherwise invoking the setter method with reflection, or in extreme cases, setting the backing field directly. However, none of these methods seem to be working for me now, and I'm curious if something has changed that has broken this functionality.

Consider the following:

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var exampleInstance = new Example();
        var exampleType = typeof(Example);
        var fooProperty = exampleType.GetProperty("Foo"); // this works fine - the "GetSetMethod" method returns null, however

        // fails with the following:
        // [System.MethodAccessException: Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.]
        //fooProperty.SetValue(exampleInstance, 24);

        // same error here:
        //Run-time exception (line 14): Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.
        //exampleType.InvokeMember(fooProperty.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, exampleInstance, new object[] { 24 });
    }
}

public class Example
{
    public int Foo { get; private set; }
}

The Foo property has a setter, it's just private. It also fails if I change the setter to protected, which seems even more bizarre, since it's no longer the C#6 initializer-only setter. This fails with both .NET 4.5 and .NET Core 2 as the runtime. What am I missing?

Body:
I was having a similar issue (with the exception that I'm using a static property) and I was able to invoke private setter like this:

public static class Example
{
    public static int Foo { get; private set; }
}

typeof(Example).GetProperty("Foo").SetMethod.Invoke(null, new object[] { 42});

Haven't tested with non-static though.


问:
How to use msum to sum only positive numbers in DolphinDB
I have a column numbers, positive or negative, such as the Val column in the table below;

```<code>msg = table(1..100 as id, rand(-100..100,100) as Val)
</code>```

Now I want to calculate the moving summation for Val with the rolling window of length 10 ,but only calculate positive numbers in Val.Something like select msum( if(val>0), 10)  from msg.

答:
Use function iif to convert all negative numbers to zero and then use msum to calculate rolling sum.

```<code>msum(iif(val > 0, val, 0), 10)
</code>```

Body:
I have a column numbers, positive or negative, such as the Val column in the table below;

msg = table(1..100 as id, rand(-100..100,100) as Val)

Now I want to calculate the moving summation for Val with the rolling window of length 10 ,but only calculate positive numbers in Val.Something like select msum( if(val>0), 10)  from msg.

Body:
Use function iif to convert all negative numbers to zero and then use msum to calculate rolling sum.

msum(iif(val > 0, val, 0), 10)


问:
Problem with highlight dates in datepicker
I'm trying to make dates highlighting using a known code, but I need a little help since the dates are not highlighted.

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightdate.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightdate) != -1) {

                    return [true, 'highlighdate', ''];
                }
            }
            return [true];

        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .highlightdate {
       background-color: #ff0;
   }</code>```

   <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

```

答:
You can also use $.datepicker.formatDate( format, date, options ) per the Docs: https://api.jqueryui.com/datepicker/

Example code.

jQuery(function($) {
  var dates = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
  $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    beforeShowDay: function(dt) {
      var dText = $.datepicker.formatDate("yy-mm-dd", dt);
      var result = [true, "", ""];
      if (dates.indexOf(dText) >= 0) {
        result = [true, 'ui-state-highlight', ''];
      }
      return result;
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ui-state-highlight>a.ui-state-default {
  background: #ffe45c;
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css">

```

Body:
I'm trying to make dates highlighting using a known code, but I need a little help since the dates are not highlighted.

var highlightdate = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightdate.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightdate) != -1) {

                    return [true, 'highlighdate', ''];
                }
            }
            return [true];

        }
    });
});

   .highlightdate {
       background-color: #ff0;
   }

   <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

Body:
You can also use $.datepicker.formatDate( format, date, options ) per the Docs: https://api.jqueryui.com/datepicker/

Example code.

jQuery(function($) {
  var dates = ["2020-06-19", "2020-06-20", "2020-06-26", "2020-06-25", "2020-06-30"];
  $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    beforeShowDay: function(dt) {
      var dText = $.datepicker.formatDate("yy-mm-dd", dt);
      var result = [true, "", ""];
      if (dates.indexOf(dText) >= 0) {
        result = [true, 'ui-state-highlight', ''];
      }
      return result;
    }
  });
});

.ui-state-highlight>a.ui-state-default {
  background: #ffe45c;
}

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="datepicker"></div>


问:
What are the default font settings used in the UITableViewCell styles?
Anyone have a listing of the default font settings Apple uses in the UITableViewCells, UILabel etc? Also the positioning information for the textLabel in the UITableViewCell both grouped and plain would be fantastic.</p>

答:
Are you familiar with the debugger?  It knows all.  To get access to the layout, try the following in gdb.

I set the breakpoint in - (void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath which is called right before the cell is displayed

(note: there's a background image in my cell)

```<code>(gdb) po cell
<UITableViewCell: 0x59e9920; frame = (0 66; 320 44); text = '396 Studio'; autoresize = W; layer = <CALayer: 0x59e9a00>>

(gdb) po [cell subviews]
<__NSArrayM 0x4eaf730>(
 <UIImageView: 0x59ea660; frame = (0 0; 320 100); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x59ea690>>,
 <UITableViewCellContentView: 0x59e9eb0; frame = (9 0; 302 44); layer = <CALayer: 0x59ea070>>
)

(gdb) po [[[cell subviews] objectAtIndex:1] subviews]
<__NSArrayM 0x4eaf700>(
 <UILabel: 0x59e9170; frame = (0 0; 0 0); text = '396 Studio'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e91e0>>,
 <UITableViewLabel: 0x59e65c0; frame = (0 0; 0 0); text = 'Houston'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e6690>>
)

(gdb) po [0x59e9170 font]
<UICFFont: 0x5e12610> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 0px

(gdb) p (CGRect)[cell frame]
$1 = {
  origin = {
    x = 0,
    y = 66
  },
  size = {
    width = 320,
    height = 44
  }
}
</code>```

po = print object
p = print, but you have to cast the value to the type you know it is

no property access cell.frame - use objective-c methods [cell frame]

Also, here is a 4 year old, but still useful article on iPhone fonts: daring fireball.

ContentLicense: CC BY-SA 2.5

Body:
Are you familiar with the debugger?  It knows all.  To get access to the layout, try the following in gdb.

I set the breakpoint in - (void)tableView:(UITableView *)tableView  willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath which is called right before the cell is displayed

(note: there's a background image in my cell)

(gdb) po cell
<UITableViewCell: 0x59e9920; frame = (0 66; 320 44); text = '396 Studio'; autoresize = W; layer = <CALayer: 0x59e9a00>>

(gdb) po [cell subviews]
<__NSArrayM 0x4eaf730>(
 <UIImageView: 0x59ea660; frame = (0 0; 320 100); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x59ea690>>,
 <UITableViewCellContentView: 0x59e9eb0; frame = (9 0; 302 44); layer = <CALayer: 0x59ea070>>
)

(gdb) po [[[cell subviews] objectAtIndex:1] subviews]
<__NSArrayM 0x4eaf700>(
 <UILabel: 0x59e9170; frame = (0 0; 0 0); text = '396 Studio'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e91e0>>,
 <UITableViewLabel: 0x59e65c0; frame = (0 0; 0 0); text = 'Houston'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e6690>>
)

(gdb) po [0x59e9170 font]
<UICFFont: 0x5e12610> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 0px

(gdb) p (CGRect)[cell frame]
$1 = {
  origin = {
    x = 0,
    y = 66
  },
  size = {
    width = 320,
    height = 44
  }
}

po = print object
p = print, but you have to cast the value to the type you know it is

no property access cell.frame - use objective-c methods [cell frame]

Also, here is a 4 year old, but still useful article on iPhone fonts: daring fireball.


问:
Oracle Case Statement Query
I am working on an Oracle Query to find if Diagnostic Pack is installed. Query is working fine.

```<code>Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'
</code>```

In the Output I need to add another Column Installed. So if currently_used = 'TRUE' I need the output to be displayed as below.

```<code>DIAGNOSTICS_package INSTALLED
1                   YES
</code>```

I am running into an issue with the INSTALLED Column in the case statement. Please advise.

Thanks

答:
Based on your where clause, you don't need a case expression:

```<code>Select 1 as DIAGNOSTICS_package,
       'YES' as INSTALLED
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%' and
      CURRENTLY_USED = 'TRUE'
</code>```

You are already filtering on CURRENTLY_USED = 'TRUE'.

Title: Oracle Case Statement Query

Body:
I am working on an Oracle Query to find if Diagnostic Pack is installed. Query is working fine.

Select case when currently_used = 'TRUE' then 1
else 0
end DIAGNOSTICS_package
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%'
and CURRENTLY_USED = 'TRUE'

In the Output I need to add another Column Installed. So if currently_used = 'TRUE' I need the output to be displayed as below.

DIAGNOSTICS_package INSTALLED
1                   YES

I am running into an issue with the INSTALLED Column in the case statement. Please advise.

Thanks

Body:
Based on your where clause, you don't need a case expression:

Select 1 as DIAGNOSTICS_package,
       'YES' as INSTALLED
from dba_feature_usage_statistics
where name like '%Diagnostic Pack%' and
      CURRENTLY_USED = 'TRUE'

You are already filtering on CURRENTLY_USED = 'TRUE'.


问:
How to add a WCF connected service using Visual Studio
Was wondering how to add a connected WCF service URL reference in Visual Studio. When I click on Connected Services in my solution, I don't have the "Configure WCF Web Service Reference" option to click on under Connected services to add the service URL. I only have an option to configure Cloud storage. So, where do I find the "Configure WCF Web Service Reference" that used to be available in the find more services option? or is there another way to do it. Can someone help me? I'm using VS V2017.</p>

答:
You need to right click the references menu of the project, not the solution

https://learn.microsoft.com/en-us/visualstudio/data-tools/how-to-add-update-or-remove-a-wcf-data-service-reference?view=vs-2017

https://therefore.net/help/2019/en-us/AR/SDK/WebAPI/the_webapi_guide_addservicereference.html

Adding service reference in VS 2017, MVC


问:
Creating Custom fields from Flex (Salesforce)
I'm trying to CREATE custom fields from flex, but I'm having hard time finding the correct syntax.

Below is the piece of code that I'm using and it's resulting in error "sf:INVALID_TYPE INVALID_TYPE: null objects not allowed in create/update request"

```<code>    var con:Connection = new Connection();
    var lRequest:LoginRequest = new LoginRequest();
    lRequest.username = username1.text;
    lRequest.password = password1.text;
    lRequest.callback = new mx.rpc.Responder(createFields, loginFault);
    con.login(lRequest);

    //CreateFields Method ....
    var externalIdField:CustomField = new CustomField();
    externalIdField.label = 'ProductionId';
    externalIdField.type = FieldType.ID;
    externalIdField._length = 18;
    externalIdField.externalId = true;
    externalIdField.unique = true;

    var customObjectVar:CustomObject = new CustomObject();
    customObjectVar["type"] = "Account";
    customObjectVar.addField(externalIdField);

    var objarray:Array = [];
    objarray[0]=customObjectVar;
    con.updateObject(objarray,new mx.rpc.Responder(saveresults,sfdcFailure));
</code>```

Tried below alternate way (as suggested by Simon), that too results in error

"soapenv:Client Element
  {http://soap.sforce.com/2006/04/metadata}type
  invalid at this location"

```<code>    var externalIdField:CustomField = new CustomField();
    externalIdField.fullName = 'Account.ProductionId__c';
    externalIdField.type = FieldType.STRING;
    externalIdField._length = 18;
    externalIdField.externalId = true;
    externalIdField.unique = true;

    var objarray:Array = [];
    objarray[0]=externalIdField;
    con.updateObject(objarray,new mx.rpc.Responder(saveresults,sfdcFailure));
</code>```

`

答: To create fields you would pass a CustomField instance to the metadata api create call (its not clear from your code what con is), in addition to the fields you've set, you need to set the fullName (e.g. Account.ProductionId__c in this case)

Body:
I'm trying to CREATE custom fields from flex, but I'm having hard time finding the correct syntax.

Below is the piece of code that I'm using and it's resulting in error "sf:INVALID_TYPE INVALID_TYPE: null objects not allowed in create/update request"

    var con:Connection = new Connection();
    var lRequest:LoginRequest = new LoginRequest();
    lRequest.username = username1.text;
    lRequest.password = password1.text;
    lRequest.callback = new mx.rpc.Responder(createFields, loginFault);
    con.login(lRequest);

    //CreateFields Method ....
    var externalIdField:CustomField = new CustomField();
    externalIdField.label = 'ProductionId';
    externalIdField.type = FieldType.ID;
    externalIdField._length = 18;
    externalIdField.externalId = true;
    externalIdField.unique = true;

    var customObjectVar:CustomObject = new CustomObject();
    customObjectVar["type"] = "Account";
    customObjectVar.addField(externalIdField);

    var objarray:Array = [];
    objarray[0]=customObjectVar;
    con.updateObject(objarray,new mx.rpc.Responder(saveresults,sfdcFailure));

Tried below alternate way (as suggested by Simon), that too results in error

"soapenv:Client Element
  {http://soap.sforce.com/2006/04/metadata}type
  invalid at this location"

    var externalIdField:CustomField = new CustomField();
    externalIdField.fullName = 'Account.ProductionId__c';
    externalIdField.type = FieldType.STRING;
    externalIdField._length = 18;
    externalIdField.externalId = true;
    externalIdField.unique = true;

    var objarray:Array = [];
    objarray[0]=externalIdField;
    con.updateObject(objarray,new mx.rpc.Responder(saveresults,sfdcFailure));

`


问:
What is the use of 'WHERE TRUE' in MySQL
I'm working on my colleague's old project and I found on her code WHERE TRUE AND ID='1' AND STAT='1'.
I've tried to removed TRUE AND so the query become WHERE ID='1' AND STAT='1' and get the same result.

I know we can use TRUEas boolean to search 'where something is true' such as WHERE FLAG = TRUE and this MySQL documentation state that

The constants TRUE and FALSE evaluate to 1 and 0, respectively. The constant names can be written in any lettercase.

I also tried SELECT * FROM MYTABLE WHERE TRUE but it's just the same as SELECT * FROM MYTABLE

what is the purpose of TRUE in her query?

答:
If you're writing your SQLString on runtime, and you might add different "where" clausules but you don't know which of all of them will be the first, it makes it easy as all of them may start with "AND ....."

Example:

```<code>SQLString:='SELECT * FROM YOUTABLE WHERE TRUE'

If condition1 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition2 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition3 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition4 THEN SQLString:=SQLString+' AND Whatever=whatever';
</code>```

otherwhise, you should add the WHERE clause not on the first SQLString:= but on the first condition that happens to be true, which you don't know will it be a priori

Body:
If you're writing your SQLString on runtime, and you might add different "where" clausules but you don't know which of all of them will be the first, it makes it easy as all of them may start with "AND ....."

Example:

SQLString:='SELECT * FROM YOUTABLE WHERE TRUE'

If condition1 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition2 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition3 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition4 THEN SQLString:=SQLString+' AND Whatever=whatever';

otherwhise, you should add the WHERE clause not on the first SQLString:= but on the first condition that happens to be true, which you don't know will it be a priori


问:
When and how does bool get called in this code?
I've been working my way through CS50 just to learn the basics of coding. I successfully made plurality of Problem Set 3, but I don't really understand how the boolean works. So the specific questions are:

1) How does the structure of the boolean work?
2) When and how does it get called?

I'm trying to understand the fundamental aspect of using this. Thanks for any help.

Here's the code:

```<code>#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
   // TODO
   for (int i = 0; i < candidate_count; i++)
   {
       if (strcmp (name, candidates[i].name) == 0)
       {
           candidates[i].votes++;
           return true;
       }
   }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes < candidates[i].votes)
        candidates[0].votes = candidates[i].votes;
    }
    printf ("%s\n", candidates[0].name);
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes == candidates[i].votes)
        printf ("%s\n", candidates[i].name);
    }
    return;
}
</code>```

答:
bool is a type, used to create a boolean variable, i.e. one that will be sufficient for true/false evaluations.  So, because bool  not a function it does not get called.

The prototype: bool vote(string name); indicates that the function vote() accepts a string variable as an argument, and returns a bool value (true or false) upon its return, where the value returned by the bool type can only be a 1 or 0. (TRUE or FALSE) This property of bool is what makes the statement if (!vote(name)){...} possible.    This construct uses a common shortcut syntax to call the function, evaluate the return value and  decide on execution flow all in one line.

This could have also been written using more verbose syntax:

```<code>bool result = false; //'result' is created and initialized to false

result = vote(name);//function vote() is called, and assigns its return value to result.
if(result == false)
{
     printf("Invalid vote.\n");
}
</code>```

where the bool variable result is assigned the return value of the function vote().
Implied also, if the return value of vote() had been true, then the comparison statement (result == false) would fail, and bypass the fail message.

Body:
I've been working my way through CS50 just to learn the basics of coding. I successfully made plurality of Problem Set 3, but I don't really understand how the boolean works. So the specific questions are:

1) How does the structure of the boolean work?
2) When and how does it get called?

I'm trying to understand the fundamental aspect of using this. Thanks for any help.

Here's the code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
   // TODO
   for (int i = 0; i < candidate_count; i++)
   {
       if (strcmp (name, candidates[i].name) == 0)
       {
           candidates[i].votes++;
           return true;
       }
   }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes < candidates[i].votes)
        candidates[0].votes = candidates[i].votes;
    }
    printf ("%s\n", candidates[0].name);
    for (int i = 1; i < candidate_count; i++)
    {
        if (candidates[0].votes == candidates[i].votes)
        printf ("%s\n", candidates[i].name);
    }
    return;
}

Body:
bool is a type, used to create a boolean variable, i.e. one that will be sufficient for true/false evaluations.  So, because bool  not a function it does not get called.

The prototype: bool vote(string name); indicates that the function vote() accepts a string variable as an argument, and returns a bool value (true or false) upon its return, where the value returned by the bool type can only be a 1 or 0. (TRUE or FALSE) This property of bool is what makes the statement if (!vote(name)){...} possible.    This construct uses a common shortcut syntax to call the function, evaluate the return value and  decide on execution flow all in one line.

This could have also been written using more verbose syntax:

bool result = false; //'result' is created and initialized to false

result = vote(name);//function vote() is called, and assigns its return value to result.
if(result == false)
{
     printf("Invalid vote.\n");
}

where the bool variable result is assigned the return value of the function vote().
Implied also, if the return value of vote() had been true, then the comparison statement (result == false) would fail, and bypass the fail message.


问:
mysql insert problems and comparing
Hi guys after searching for 2-3 days,i have totally no clue as to what is wrong so i appreciate some help :)

I am using wampserver..what i am having problem is inseting data into mysql from android ..whenever i press the insert button,a blank row is added to my columns without any information.

This is my php for inserting

```<code><?php
$abc=$_POST['abc'];
$con = mysql_connect("localhost","root","");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("dbinsert", $con);
$sql="INSERT INTO Detail (Utext) VALUES ('".$abc."')";

if (!mysql_query($sql,$con))

{

die('Error: ' . mysql_error());

}

echo "1 record added";

mysql_close($con)

?>
</code>```

for my android

```<code>  package com.project.insert;

  import java.util.ArrayList;

  import org.apache.http.HttpEntity;

  import org.apache.http.HttpResponse;

  import org.apache.http.NameValuePair;

  import org.apache.http.client.HttpClient;

  import org.apache.http.client.entity.UrlEncodedFormEntity;

  import org.apache.http.client.methods.HttpPost;

  import org.apache.http.impl.client.DefaultHttpClient;

  import org.apache.http.message.BasicNameValuePair;

  import android.app.Activity;

  import android.os.Bundle;

  import android.util.Log;

  import android.view.View;

  import android.widget.Button;

  import android.widget.EditText;

  public class PassData extends Activity {

      /** Called when the activity is first created. */

      @Override

      public void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          setContentView(R.layout.main);

          Button Insert=(Button)findViewById(R.id.button1);

          Insert.setOnClickListener(new View.OnClickListener(){

          public void onClick(View v)

          {

          try

               {

                  EditText CompleteText=(EditText)findViewById(R.id.editText1);

                  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                  nameValuePairs.add(new BasicNameValuePair("abc", "'"+CompleteText.getText().toString()+"'"));

                       Log.e(""+CompleteText.getText().toString(),"0");

                       HttpClient httpclient = new DefaultHttpClient();

                       HttpPost httppost = new HttpPost("http://10.0.2.2/InsertStatement.php");

                       HttpResponse response = httpclient.execute(httppost);

               }

               catch(Exception e)

               {

                       Log.e("log_tag", "Error in http connection "+e.toString());

               }

          }

      });

      }

  }
</code>```

答:
I don't see where you do anything with nameValuePairs to put it into the request.

```<code>HttpPost httppost = new HttpPost("http://10.0.2.2/InsertStatement.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
</code>```

might do the trick.

For security reasons, you might want to add the ' on the server (and not the android code - right now you use both which would show a mysql error) and use mysql_real_escape_string server-side.

Title: mysql insert problems and comparing

Body:
Hi guys after searching for 2-3 days,i have totally no clue as to what is wrong so i appreciate some help :)

I am using wampserver..what i am having problem is inseting data into mysql from android ..whenever i press the insert button,a blank row is added to my columns without any information.

This is my php for inserting

<?php
$abc=$_POST['abc'];
$con = mysql_connect("localhost","root","");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

mysql_select_db("dbinsert", $con);
$sql="INSERT INTO Detail (Utext) VALUES ('".$abc."')";

if (!mysql_query($sql,$con))

{

die('Error: ' . mysql_error());

}

echo "1 record added";

mysql_close($con)

?>

for my android

  package com.project.insert;

  import java.util.ArrayList;

  import org.apache.http.HttpEntity;

  import org.apache.http.HttpResponse;

  import org.apache.http.NameValuePair;

  import org.apache.http.client.HttpClient;

  import org.apache.http.client.entity.UrlEncodedFormEntity;

  import org.apache.http.client.methods.HttpPost;

  import org.apache.http.impl.client.DefaultHttpClient;

  import org.apache.http.message.BasicNameValuePair;

  import android.app.Activity;

  import android.os.Bundle;

  import android.util.Log;

  import android.view.View;

  import android.widget.Button;

  import android.widget.EditText;

  public class PassData extends Activity {

      /** Called when the activity is first created. */

      @Override

      public void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          setContentView(R.layout.main);

          Button Insert=(Button)findViewById(R.id.button1);

          Insert.setOnClickListener(new View.OnClickListener(){

          public void onClick(View v)

          {

          try

               {

                  EditText CompleteText=(EditText)findViewById(R.id.editText1);

                  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                  nameValuePairs.add(new BasicNameValuePair("abc", "'"+CompleteText.getText().toString()+"'"));

                       Log.e(""+CompleteText.getText().toString(),"0");

                       HttpClient httpclient = new DefaultHttpClient();

                       HttpPost httppost = new HttpPost("http://10.0.2.2/InsertStatement.php");

                       HttpResponse response = httpclient.execute(httppost);

               }

               catch(Exception e)

               {

                       Log.e("log_tag", "Error in http connection "+e.toString());

               }

          }

      });

      }

  }

Body:
I don't see where you do anything with nameValuePairs to put it into the request.

HttpPost httppost = new HttpPost("http://10.0.2.2/InsertStatement.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);

might do the trick.

For security reasons, you might want to add the ' on the server (and not the android code - right now you use both which would show a mysql error) and use mysql_real_escape_string server-side.


问:
Shell variable inside sshagent block of a Jenkinsfile
I have this sshagent code block:

```<code>            sshagent(['ssh_key.hashed']) {
              sh """
              ssh -o StrictHostKeyChecking=no -l user example.com <<EOF
              today=`date +%Y-%m-%d`
              drush -r /var/www/html/example.com sql-dump --gzip > /var/www/html/example.com/backups/example_prodDB-jenkins-${today}.sql.gz
              EOF
              """.stripIndent()
            }
</code>```

Where as you can see, the real intention is to get the db dump of a drupal database.
Now, it will work if used on a regular shell script.

I need to write it that way as I will reuse the $today shell variable in another line of code.

Within the jenkinsfile, it seems like it is interpreted as a groovy variable based on the error:

```<code>groovy.lang.MissingPropertyException: No such property: today for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
    at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:11)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
    at jdk.internal.reflect.GeneratedMethodAccessor305.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Finished: FAILURE
</code>```

Any hints is appreciated.

Thanks.

答:
After a lot of searching online and trial and error found this helpful reference https://code-maven.com/jenkins-pipeline-environment-variables

I don't know if it's the right way to do it but it works.

So in summary, I had to add an environment variable and add use it within my "sshagent"

Posting sample Jenkinsfile that works.

```<code>pipeline {
   agent any

   stages {
      stage('Dump Prod DB') {
           environment {
               today = sh(script: 'date +%Y-%m-%d', , returnStdout: true).trim()
           }
         steps {
            sshagent(['promet_key.hashed']) {
              sh """
              ssh -o StrictHostKeyChecking=no -l user example.com <<EOF
              drush -r /var/www/html/example.com sql-dump --gzip > /var/www/html/example.com/backups/example_prodDB-jenkins-${today}.sql.gz
              EOF
              """.stripIndent()
            }
         }
      }
   }
}
</code>```

Body:
I have this sshagent code block:

            sshagent(['ssh_key.hashed']) {
              sh """
              ssh -o StrictHostKeyChecking=no -l user example.com <<EOF
              today=`date +%Y-%m-%d`
              drush -r /var/www/html/example.com sql-dump --gzip > /var/www/html/example.com/backups/example_prodDB-jenkins-${today}.sql.gz
              EOF
              """.stripIndent()
            }

Where as you can see, the real intention is to get the db dump of a drupal database.
Now, it will work if used on a regular shell script.

I need to write it that way as I will reuse the $today shell variable in another line of code.

Within the jenkinsfile, it seems like it is interpreted as a groovy variable based on the error:

groovy.lang.MissingPropertyException: No such property: today for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
    at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:11)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
    at jdk.internal.reflect.GeneratedMethodAccessor305.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Finished: FAILURE

Any hints is appreciated.

Thanks.

Body:
After a lot of searching online and trial and error found this helpful reference https://code-maven.com/jenkins-pipeline-environment-variables

I don't know if it's the right way to do it but it works.

So in summary, I had to add an environment variable and add use it within my "sshagent"

Posting sample Jenkinsfile that works.

pipeline {
   agent any

   stages {
      stage('Dump Prod DB') {
           environment {
               today = sh(script: 'date +%Y-%m-%d', , returnStdout: true).trim()
           }
         steps {
            sshagent(['promet_key.hashed']) {
              sh """
              ssh -o StrictHostKeyChecking=no -l user example.com <<EOF
              drush -r /var/www/html/example.com sql-dump --gzip > /var/www/html/example.com/backups/example_prodDB-jenkins-${today}.sql.gz
              EOF
              """.stripIndent()
            }
         }
      }
   }
}


问:
Uncaught TypeError: d3plus.Pie is not a constructor
I want to make a Pie Chart based on d3plus library. I try with below code (But i have a problem, d3plus.Pie is not a constructor)

```<code><html>
    <head>
        <title>D3Plus</title>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3plus/1.9.8/d3plus.full.js"></script>
    </head>
    <body>

        <script>
            var myData = [
              {"Group": "Store", "Sub-Group": "Convenience Store", "Number of Food Stores": 100},
              {"Group": "Store", "Sub-Group": "Grocery Store", "Number of Food Stores": 150},
              {"Group": "Store", "Sub-Group": "Farmer's Market", "Number of Food Stores": 50},
              {"Group": "Store", "Sub-Group": "Supercenters", "Number of Food Stores": 30},
              {"Group": "Restaurant", "Sub-Group": "Fast-Food Restaurant", "Number of Food Stores": 60},
              {"Group": "Restaurant", "Sub-Group": "Full-Service Restaurant", "Number of Food Stores": 120}
            ];

            new d3plus.Pie()
              .config({
                data: myData,
                groupBy: ["Group", "Sub-Group"],
                value: function(d) {
                  return d["Number of Food Stores"];
                }
              })
              .render();
        </script>
    </body>
</html>
</code>```

答:
It seems like you need a different source including hierarchy

```<code>https://d3plus.org/js/d3plus-hierarchy.v0.8.full.min.js"
</code>```

        <title>D3Plus</title>

```

d3plus modules list can be found at
https://github.com/d3plus

Body:
I want to make a Pie Chart based on d3plus library. I try with below code (But i have a problem, d3plus.Pie is not a constructor)

        <title>D3Plus</title>

Body:
It seems like you need a different source including hierarchy

https://d3plus.org/js/d3plus-hierarchy.v0.8.full.min.js"

<html>
    <head>
        <title>D3Plus</title>

        <script type="text/javascript" src="https://d3plus.org/js/d3plus-hierarchy.v0.8.full.min.js"></script>
    </head>
    <body>

        <script>
            var myData = [
              {"Group": "Store", "Sub-Group": "Convenience Store", "Number of Food Stores": 100},
              {"Group": "Store", "Sub-Group": "Grocery Store", "Number of Food Stores": 150},
              {"Group": "Store", "Sub-Group": "Farmer's Market", "Number of Food Stores": 50},
              {"Group": "Store", "Sub-Group": "Supercenters", "Number of Food Stores": 30},
              {"Group": "Restaurant", "Sub-Group": "Fast-Food Restaurant", "Number of Food Stores": 60},
              {"Group": "Restaurant", "Sub-Group": "Full-Service Restaurant", "Number of Food Stores": 120}
            ];
            new d3plus.Pie()
              .config({
                data: myData,
                groupBy: ["Group", "Sub-Group"],
                value: function(d) {
                  return d["Number of Food Stores"];
                }
              })
              .render();
        </script>
    </body>
</html>

d3plus modules list can be found at
https://github.com/d3plus