问:
Clicking a Checkbox in an Enzyme test
I am trying to simulate a click on a material-ui checkbox.  I have tried

selectAllCheckbox.simulate("change", { target: { checked: true } });

and

```<code>act(() => {
  selectAllCheckbox.props().onClick();
});
</code>```

I have tried re-finding the item and updating the wrapper, and I cannot get the checked prop to change.

I feel like I missing something fundamental.

I have a codesandbox here:  https://codesandbox.io/s/enzymetestformaterialuitable-t1ruq
the sandbox has a material-ui table (lifted from their demos page).

TIA

答:
I got a hand from a few sources including https://github.com/airbnb/enzyme/issues/216

complete sandbox https://codesandbox.io/s/enzymetestformaterialuitable-updb9 with tests passing

check the 4th checkbox on the table:

```<code> let innerInputElement5 = wrapper
   .find('[role="checkbox"]')
   .hostNodes()
   .at(4);
 innerInputElement5.simulate("click");
</code>```

check the indeterminate checkbox in the header:

```<code>let selectAllCheckboxInHeader = wrapper
      .find(TableHead)
      .find('input[type="checkbox"]')
      .simulate("change", { target: { checked: true } });
</code>```

Title: Clicking a Checkbox in an Enzyme test

Body:
I am trying to simulate a click on a material-ui checkbox.  I have tried

selectAllCheckbox.simulate("change", { target: { checked: true } });

and

act(() => {
  selectAllCheckbox.props().onClick();
});

I have tried re-finding the item and updating the wrapper, and I cannot get the checked prop to change.

I feel like I missing something fundamental.

I have a codesandbox here:  https://codesandbox.io/s/enzymetestformaterialuitable-t1ruq
the sandbox has a material-ui table (lifted from their demos page).

TIA

Body:
I got a hand from a few sources including https://github.com/airbnb/enzyme/issues/216

complete sandbox https://codesandbox.io/s/enzymetestformaterialuitable-updb9 with tests passing

check the 4th checkbox on the table:

 let innerInputElement5 = wrapper
   .find('[role="checkbox"]')
   .hostNodes()
   .at(4);
 innerInputElement5.simulate("click");

check the indeterminate checkbox in the header:

let selectAllCheckboxInHeader = wrapper
      .find(TableHead)
      .find('input[type="checkbox"]')
      .simulate("change", { target: { checked: true } });


来源: stackexchange

问:
Optimize WPF ComboBox search with thousands items
I have a WPF ComboBox control with an itemsSource of 66000 items. To improve loading performance I've used VirtualizingStackPanel and it's ok but now I've another problem.

The ComboBox is editable and when I type on TextBox it start search for SelectedItem to match...but it is slow and don't immediately respond to character typed.

How can avoid this behavior?

答:
What Bruno basically said:

Read up on msdn more about it:
http://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel.aspx

Here's the code Note you'll need to add in your other bindings... :

```<code><ItemsPanelTemplate x:Key="VirtualPanel">
    <VirtualizingStackPanel />
</ItemsPanelTemplate>

<ComboBox ItemsPanel="{DynamicResource VirtualPanel}">
</code>```

Or you can manually add it in ...

```<code>             <ComboBox VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate >
                <VirtualizingStackPanel/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
    </ComboBox>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What Bruno basically said:

Read up on msdn more about it:
http://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel.aspx

Here's the code Note you'll need to add in your other bindings... :

<ItemsPanelTemplate x:Key="VirtualPanel">
    <VirtualizingStackPanel />
</ItemsPanelTemplate>

<ComboBox ItemsPanel="{DynamicResource VirtualPanel}">

Or you can manually add it in ...

             <ComboBox VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling">
        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate >
                <VirtualizingStackPanel/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
    </ComboBox>


问:
Pass ARGs in docker ENTRYPOINT
I'm running my app on Azure App Services, so I don't have access to docker run command. Now, I want to pass some variables into ENTRYPOINT for which I'm trying to use ARGs during build time itself. Here is how it looks,

```<code>docker build -t $IMAGE_NAME --build-arg env=dev --build-arg amplify_key=xxxxxxxxxxxxxx .
</code>```

In my Dockerfile,

```<code>ARG env
ARG amplify_key

ENTRYPOINT ["/bin/bash", "-c", "init.sh $env $amplify_key"]
</code>```

But this doesn't seem to be working. Please let me know the issue.

答:
$variable references can be either expanded in the Dockerfile or by the shell when a command gets run.  Only some Dockerfile commands perform variable expansions; for RUN, CMD, and ENTRYPOINT, it is only done by a shell.  When a shell does the expansion it's not aware of Docker-specific ARGs, only environment variables, so you need to copy the argument to an ENV.  There's an example of this in the Dockerfile documentation.

ARG env
ARG amplify_key
ENV env=$env amplify_key=$amplify_key
CMD init.sh $env $amplify_key
```

<p>Assuming <code>init.sh</code> is your own script, though, once you have those values in environment variables, you can just access them directly, without passing them through positional parameters.</p>

<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
echo "Running in $env environment"
curl -H "Authorization: Bearer $amplify_key" ...
</code>```

ARG env
ARG amplify_key
ENV env=$env amplify_key=$amplify_key
CMD ["init.sh"]
```

This lets you do things like override the variable values at startup time more easily, and if you need to manually supply parameters to the command, the set of mandatory options is much smaller.  If you're using the pattern of ENTRYPOINT doing some first-time setup and then running exec "$@" to run the CMD, this also works much better (ENTRYPOINT and sh -c have some tricky interactions).

ContentLicense: CC BY-SA 4.0

Title: Pass ARGs in docker ENTRYPOINT

Body:
I'm running my app on Azure App Services, so I don't have access to docker run command. Now, I want to pass some variables into ENTRYPOINT for which I'm trying to use ARGs during build time itself. Here is how it looks,

docker build -t $IMAGE_NAME --build-arg env=dev --build-arg amplify_key=xxxxxxxxxxxxxx .

In my Dockerfile,

ARG env
ARG amplify_key

ENTRYPOINT ["/bin/bash", "-c", "init.sh $env $amplify_key"]

But this doesn't seem to be working. Please let me know the issue.

Body:
$variable references can be either expanded in the Dockerfile or by the shell when a command gets run.  Only some Dockerfile commands perform variable expansions; for RUN, CMD, and ENTRYPOINT, it is only done by a shell.  When a shell does the expansion it's not aware of Docker-specific ARGs, only environment variables, so you need to copy the argument to an ENV.  There's an example of this in the Dockerfile documentation.

ARG env
ARG amplify_key
ENV env=$env amplify_key=$amplify_key
CMD init.sh $env $amplify_key

Assuming init.sh is your own script, though, once you have those values in environment variables, you can just access them directly, without passing them through positional parameters.

#!/bin/sh
echo "Running in $env environment"
curl -H "Authorization: Bearer $amplify_key" ...

ARG env
ARG amplify_key
ENV env=$env amplify_key=$amplify_key
CMD ["init.sh"]

This lets you do things like override the variable values at startup time more easily, and if you need to manually supply parameters to the command, the set of mandatory options is much smaller.  If you're using the pattern of ENTRYPOINT doing some first-time setup and then running exec "$@" to run the CMD, this also works much better (ENTRYPOINT and sh -c have some tricky interactions).


问:
Laravel Error: Too few arguments to function, 0 passed and exactly 1 expected
Using Laravel-5.8, I have this code:

```<code>public function manager_employee_list(Request $request)
{

    $employees = HrEmployee::paginate(6);

    return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}
</code>```

And it render this view: manager_employee_list

```<code>      <div class="row d-flex align-items-stretch">
          @if (count($employees))
          @foreach($employees as $key => $employee)
        <div class="col-12 col-sm-6 col-md-4 d-flex align-items-stretch">
          <div class="card bg-light">
            <div class="card-header text-muted border-bottom-0">
              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}
            </div>
            <div class="card-body pt-0">
              <div class="row">
                <div class="col-7">
                  <h2 class="lead"><b>Staff ID: {{$employee->employee_code}}</b></h2>
                  <h2 class="lead"><b>{{$employee->first_name}} {{$employee->last_name}}</b></h2>

                  <h6 class="lead"><b>Employee Department: </b>{{isset($employee->department) ? $employee->department->dept_name : ''}}</h6>
                </div>
                <div class="col-5 text-center">
                            @if($employee->emp_image != '')
                                <img src="{{ URL::to('/') }}/public/storage/employees/image/{{ $employee->emp_image }}" class="img-circle img-fluid" />

                            @else
                                <img class="profile-user-img img-fluid img-circle" src="{{asset('theme/adminlte3/dist/img/default.png')}}" alt="" class="img-circle img-fluid">
                            @endif
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="text-right">
                <a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
                  <i class="fas fa-user"></i> View Goal
                </a>
              </div>
            </div>
          </div>
        </div>
        @endforeach
        @else
        <h4 style="text-align:center;">No matching records found</h4>
        @endif
      </div>
</code>```

I want to pass the parameter

['id'=>$employee->id]

from above to another controller action:

```<code>public function manager_employee_goal($id)
{

    $goals = AppraisalGoal::where('employee_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);
}
</code>```

It utilizes it here:

$goals = AppraisalGoal::where('employee_id', $id)->get();

When I clicked on

```<code><a href="{{ route('appraisal.appraisal_goals.manager_employee_goal', ['id'=>$employee->id]) }}" class="btn btn-sm btn-primary">
     <i class="fas fa-user"></i> View Goal
</a>
</code>```

I got this error:

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected

and this is underlined:

public function manager_employee_goal($id)

route/web.php

```<code>Route::get('appraisal_goals/manager_employee_list', 'Appraisal\AppraisalGoalsController@manager_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
</code>```

How do I resolve it?

Thank you.

答:
I believe your route need to be updated to</p>

```<code>Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');
</code>```

Body:
Using Laravel-5.8, I have this code:

public function manager_employee_list(Request $request)
{

    $employees = HrEmployee::paginate(6);

    return view('appraisal.appraisal_goals.manager_employee_list')->with('employees', $employees);
}

And it render this view: manager_employee_list

          @if (count($employees))
          @foreach($employees as $key => $employee)

              {{isset($employee->designation) ? $employee->designation->designation_name : ''}}

Staff ID: {{$employee->employee_code}}

{{$employee->first_name}} {{$employee->last_name}}

Employee Department: {{isset($employee->department) ? $employee->department->dept_name : ''}}

                            @if($employee->emp_image != '')
                                emp_image }}" class="img-circle img-fluid" />

                            @else

                            @endif

                $employee->id]) }}" class="btn btn-sm btn-primary">
                   View Goal

        @endforeach
        @else

No matching records found

        @endif

I want to pass the parameter

['id'=>$employee->id]

from above to another controller action:

public function manager_employee_goal($id)
{

    $goals = AppraisalGoal::where('employee_id', $id)->get();

    return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals);
}

It utilizes it here:

$goals = AppraisalGoal::where('employee_id', $id)->get();

When I clicked on

$employee->id]) }}" class="btn btn-sm btn-primary">
      View Goal

I got this error:

Too few arguments to function App\Http\Controllers\Appraisal\AppraisalGoalsController::manager_employee_goal(), 0 passed and exactly 1 expected

and this is underlined:

public function manager_employee_goal($id)

route/web.php

Route::get('appraisal_goals/manager_employee_list', 'Appraisal\AppraisalGoalsController@manager_employee_list')->name('appraisal.appraisal_goals.manager_employee_list');
Route::get('appraisal_goals/manager_employee_goal', 'Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');

How do I resolve it?

Thank you.

Body:
I believe your route need to be updated to

Route::get('appraisal_goals/manager_employee_goal/{id}','Appraisal\AppraisalGoalsController@manager_employee_goal')->name('appraisal.appraisal_goals.manager_employee_goal');


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答:
You'r trying to INSERT INTO Submission data from TbComments.  So you need to SELECT the data from TbComments and then INSERT INTO Submission</p>

```<code>string comQuery =
"INSERT INTO Submission (
     Status,
     StatusComment,
     StatusValue)
 SELECT
    'decline',
    TbComments.Text,
    2)
 FROM TbComments
 WHERE SubmissionId =" + x;
</code>```

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}

Body:
You'r trying to INSERT INTO Submission data from TbComments.  So you need to SELECT the data from TbComments and then INSERT INTO Submission

string comQuery =
"INSERT INTO Submission (
     Status,
     StatusComment,
     StatusValue)
 SELECT
    'decline',
    TbComments.Text,
    2)
 FROM TbComments
 WHERE SubmissionId =" + x;


问:
Struggling with Nativescript Geolocation Plugin
When using the nativescript geolocation plugin in a semi rural area, the results are wildly inaccurate, sometimes as much as 500 meters away. The results always place me at the nearest urban development rather than in the field in which I am stood. This does not happen when I am in a fully urbanised ennvironment, where results are always perfect. The field in which I walk is the highest point in my area, with phone mast arrays aplenty, so I am unsure why these results occur.

To me, the results are somehow coming from screwed up phone signal triangulation and distant wifi signals. I have tried to eradicate this by de-activating my sim card to use GPS only, but then NOTHING is returned. This suggests that GPS is not working, and I am relying on wifi and phone signal data for positioning, but as I am trying to develop an app for use in areas of poor phone signal, GPS only positioning is vital (and, at around 20 meters accuracy in most cases - perfectly acceptable for my purposes).

function buttonGetLocationTap(args) {

    var location = geolocation.getCurrentLocation({
        desiredAccuracy: accuracy.any,
        updateDistance: 0,
        maximumAge: 5000,
        timeout: 5000

     //   desiredAccuracy: 1
     //   , updateDistance: 10
     //   , minimumUpdateTime: 600000
     //   , maximumAge: 600000
     //   , timeout: 5000

    }).
    then(function(loc) {
        if (loc) {

            var match = 'n';
            var z = '';
            for (var i = 0; i < x.markers.length; i++) {
                var names = x.markers[i].name;
                var items = x.markers[i].coordinates;

                var targetLatitude = (items.latitude);
                var targetLongitude = (items.longitude);
                var currentLatitude = (loc.latitude.toFixed(4));
                var currentLongitude = (loc.longitude.toFixed(4));

                var targetLatitudelow=targetLatitude -0.0005;
                var targetLatitudehigh=targetLatitude +0.0005;
                var targetLongitudelow=targetLongitude -0.0005;
                var targetLongitudehigh=targetLongitude +0.0005;

                if (currentLatitude >= targetLatitudelow && currentLatitude <= targetLatitudehigh) {
                    if (currentLongitude >= targetLongitudelow && currentLongitude <= targetLongitudehigh) {
                        match = 'y';
                        z = JSON.stringify(names);
                        console.log(z);
                        page.bindingContext = {
                            username: z
                        }
                    }
                }
                else
                {

                    match = 'n';
                    z = currentLatitude + currentLongitude;
                    console.log(z);
                    page.bindingContext = {
                        username: z
                    }

                }
                ;
                if (match =='y') { break; }
            }
        }
```

I would expect the same result in the semi rural area as the urbanised, am clearly have two problems:

1.Why is GPS only not working
2.Despite GPS not working - why are the results of wifi and phone signal data so wildly inaccurate when I am stood next to a mobile phone mast in the middle of a field??

Any help would be much appreciated!!

答:
Set desiredAccuracy to Accuracy.high

Your location deceleration would then become as follows:

```<code>    var location = geolocation.getCurrentLocation({
        desiredAccuracy: Accuracy.high,
        updateDistance: 0,
        maximumAge: 5000,
        timeout: 5000
    })
</code>```

Body:
When using the nativescript geolocation plugin in a semi rural area, the results are wildly inaccurate, sometimes as much as 500 meters away. The results always place me at the nearest urban development rather than in the field in which I am stood. This does not happen when I am in a fully urbanised ennvironment, where results are always perfect. The field in which I walk is the highest point in my area, with phone mast arrays aplenty, so I am unsure why these results occur.

To me, the results are somehow coming from screwed up phone signal triangulation and distant wifi signals. I have tried to eradicate this by de-activating my sim card to use GPS only, but then NOTHING is returned. This suggests that GPS is not working, and I am relying on wifi and phone signal data for positioning, but as I am trying to develop an app for use in areas of poor phone signal, GPS only positioning is vital (and, at around 20 meters accuracy in most cases - perfectly acceptable for my purposes).

function buttonGetLocationTap(args) {

    var location = geolocation.getCurrentLocation({
        desiredAccuracy: accuracy.any,
        updateDistance: 0,
        maximumAge: 5000,
        timeout: 5000

     //   desiredAccuracy: 1
     //   , updateDistance: 10
     //   , minimumUpdateTime: 600000
     //   , maximumAge: 600000
     //   , timeout: 5000

    }).
    then(function(loc) {
        if (loc) {

            var match = 'n';
            var z = '';
            for (var i = 0; i < x.markers.length; i++) {
                var names = x.markers[i].name;
                var items = x.markers[i].coordinates;

                var targetLatitude = (items.latitude);
                var targetLongitude = (items.longitude);
                var currentLatitude = (loc.latitude.toFixed(4));
                var currentLongitude = (loc.longitude.toFixed(4));

                var targetLatitudelow=targetLatitude -0.0005;
                var targetLatitudehigh=targetLatitude +0.0005;
                var targetLongitudelow=targetLongitude -0.0005;
                var targetLongitudehigh=targetLongitude +0.0005;

                if (currentLatitude >= targetLatitudelow && currentLatitude <= targetLatitudehigh) {
                    if (currentLongitude >= targetLongitudelow && currentLongitude <= targetLongitudehigh) {
                        match = 'y';
                        z = JSON.stringify(names);
                        console.log(z);
                        page.bindingContext = {
                            username: z
                        }
                    }
                }
                else
                {

                    match = 'n';
                    z = currentLatitude + currentLongitude;
                    console.log(z);
                    page.bindingContext = {
                        username: z
                    }

                }
                ;
                if (match =='y') { break; }
            }
        }

I would expect the same result in the semi rural area as the urbanised, am clearly have two problems:

1.Why is GPS only not working
2.Despite GPS not working - why are the results of wifi and phone signal data so wildly inaccurate when I am stood next to a mobile phone mast in the middle of a field??

Any help would be much appreciated!!

Body:
Set desiredAccuracy to Accuracy.high

Your location deceleration would then become as follows:

    var location = geolocation.getCurrentLocation({
        desiredAccuracy: Accuracy.high,
        updateDistance: 0,
        maximumAge: 5000,
        timeout: 5000
    })


问:
Debugging a program that doesn't start
How would I go about determining why a VB6 (or 5) application doesn't start?  I can't attach a debugger to it because of that.  I have IDA Pro Freeware at my disposal, but need some pointers as to where to start with it.

I don't have the source for this program, only the .exe.  When I say it doesn't start, I double-click the .exe, and nothing happens - there is no process left running - nadda.

Running under admin it creates three empty folders, then exits silently before a UI is shown.  OllyDbg tells me there was an 'Inexact floating point result', but I need to spend a few hours or days learning to interpret all the info OllyDbg gives me.  My book on Advanced Windows Debugging should arrive on Monday or Tuesday as well.

答: It seems like I answer with this a lot, but try looking at the Windows Events log. There is often information here that can be useful, such as a control, or dll your program depends on that was not found.</p>

OwnerDisplayName: ProfK

ContentLicense: CC BY-SA 2.5

Title: Debugging a program that doesn't start

LastEditorDisplayName: ProfK

OwnerDisplayName: Beaner


问:
Automated importing/renaming of Flash assets
So I have an AS3 flash project with A LOT of assets, roughly 1000 at the time being but that may expand to several thousand later. They are all images but half of them are Animated GIFs so I can't import them at runtime. I considered simply dragging them into the flash project but I don't seem to have any control over the naming scheme. Basically, what I want to know is:

Is there a way to automate importing and renaming of flash assets, like "Import these 1000 files and export them for Actionscript with this name"?

Additionally, is there a better way for me to be doing this? I've tried http://code.google.com/p/as3gif/ AS3GIF but it struggles with larger animated gifs like the ones I'm working with (650x450). Any help would be appreciated.

答:
If I remember right, if all the images are named like "image0", "image1" etc., when you add the first one to Flash, it'll say something like "It looks like this image is part of a sequence, do you want to import them all?". That'll take a bit of time though. Once they're in, you can shift-click to select them all to give them an export name (provided you don't want to change it, you can keep their name and it should be fine).

Why can't you load these at runtime again? Does Flash even playing animated gifs, so does that even matter? Exporting a SWF with that many images is going to kill your productivity and probably your computer (Flash gets a bit flaky when the file size gets huge). Waiting for that SWF to download on the client side would be a killer. Especially if your clients aren't going to be looking at all the images - you're throwing away MBs of bandwidth there.

I'd either load them at runtime (ideal - loading a compressed xml file is much quicker and easier), or if they absolutely had to be in the fla, i'd break it up into multiples.


问:
Null Values in Zones in Highcharts
I have graphs that have zones. Currently if there is a null value, that null value is displayed in the tooltip with the zone color of the point before it. I want the null value to always be the color black.

For example,

The tooltip in graph 1 has all the correct information... but "Strength: null" has a green dot. I want to make this dot black because it is a null value.

Is it possible to make this happen? Thanks so much.

https://codepen.io/austeng/pen/gOppRWY

```<code>zones: [
  {
    value: 0.3,
    color: "green"
  },
  {
    value: 0.5,
    color: "black",
  },
  {
    color: "red"
  }
]
</code>```

答:
I have added this functionality by defining the color point like this:

```<code>let color = point.y === null ? 'black' : point.color
</code>```

and use this color variable in the result:

```<code>  result +=
    '<span style="color:' +
    color +
    '">●</span> ' +
    point.series.name +
    ": <b>" +
    point.y +
    "</b><br/>";
</code>```

Demo: https://jsfiddle.net/BlackLabel/7x1oc2pw/

Is that what you had in mind?

Title: Null Values in Zones in Highcharts

Body:
I have graphs that have zones. Currently if there is a null value, that null value is displayed in the tooltip with the zone color of the point before it. I want the null value to always be the color black.

For example,

The tooltip in graph 1 has all the correct information... but "Strength: null" has a green dot. I want to make this dot black because it is a null value.

Is it possible to make this happen? Thanks so much.

https://codepen.io/austeng/pen/gOppRWY

zones: [
  {
    value: 0.3,
    color: "green"
  },
  {
    value: 0.5,
    color: "black",
  },
  {
    color: "red"
  }
]

Body:
I have added this functionality by defining the color point like this:

let color = point.y === null ? 'black' : point.color

and use this color variable in the result:

  result +=
    '<span style="color:' +
    color +
    '">●</span> ' +
    point.series.name +
    ": <b>" +
    point.y +
    "</b><br/>";

Demo: https://jsfiddle.net/BlackLabel/7x1oc2pw/

Is that what you had in mind?


问:
Phpmyadmin mysql server choice
I have installed Wamp server.

When I create databases and tables by php and mysql, all are created
in 'Mariadb'(server choice) in phpMyAdmin.

How to create database and table in 'mysql'(server choice) ?

Here is my code sample:

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Create database

$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
</code>```

答:
In recent versions of WAMPServer it has installed both mariaDB and MySQL.

The default has become mariaDB.

In phpMyAdmin you can select the Server you want to be interacting with using the Server Choice dropdown

Alternatively if you know you are not going to use both database servers you can remove one of them and save yourself some memory.

To remove the one you dont want (It can be added back later quite easily) you simple use the WAMPSevrer menus like this

To remove mariaDB

```<code>right click wampmanager -> WAMP Settings -> and click on **Allow mariaDB**
</code>```

and give WAMPServer a few seconds to configure and restart and the mariaDB server will have been removed and you will only ever be using MySQL. You will also no get the Server Choice dropdown on the phpMyAdmin login page as there will no longer be a choice.

To reactivate mariaDB later, just reverse the process and click Allow mariaDB again and it will be reconfigured and reinstalled, and the green tick will reappear by the name

Title: Phpmyadmin mysql server choice

Body:
I have installed Wamp server.

When I create databases and tables by php and mysql, all are created
in 'Mariadb'(server choice) in phpMyAdmin.

How to create database and table in 'mysql'(server choice) ?

Here is my code sample:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Create database

$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Body:
In recent versions of WAMPServer it has installed both mariaDB and MySQL.

The default has become mariaDB.

In phpMyAdmin you can select the Server you want to be interacting with using the Server Choice dropdown

Alternatively if you know you are not going to use both database servers you can remove one of them and save yourself some memory.

To remove the one you dont want (It can be added back later quite easily) you simple use the WAMPSevrer menus like this

To remove mariaDB

right click wampmanager -> WAMP Settings -> and click on **Allow mariaDB**

and give WAMPServer a few seconds to configure and restart and the mariaDB server will have been removed and you will only ever be using MySQL. You will also no get the Server Choice dropdown on the phpMyAdmin login page as there will no longer be a choice.

To reactivate mariaDB later, just reverse the process and click Allow mariaDB again and it will be reconfigured and reinstalled, and the green tick will reappear by the name


问:
coroutine Flow : Not sure how to convert a Cursor to this method's return type
When I am trying to change the Dao to the new FlowApi, I am getting the compilation error stating that

```<code>Not sure how to convert a Cursor to this method's return type
    public abstract kotlinx.coroutines.flow.Flow<java.util.List<com.ezek.ezign.model.ECampaign>> readCampaigns();
</code>```

The Dao is

```<code>@Dao
interface CampaignDao {

    @Query("SELECT * FROM campaign ORDER BY timeStamp ASC")
    fun readCampaigns(): Flow<List<ECampaign>>

    @Query("SELECT * FROM campaign WHERE id = :campaignId")
    fun readCampaign(campaignId: Int): Flow<ECampaign>
}
</code>```

and the dependencies are

```<code>    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'

    implementation "android.arch.persistence.room:runtime:$rootProject.ext.room_version"
    kapt "android.arch.persistence.room:compiler:$rootProject.ext.room_version"

//room_version = "2.1.0"
</code>```

I have tried with Both List and ArrayList, but No luck.

Thanks in advance.

答:
Do not use both suspend and Flow<> on the same method! Like this

```<code> @Query("SELECT * FROM user")
    suspend fun loadAll(): Flow<Array<User>>
</code>```

Just

```<code>@Query("SELECT * FROM user")
    suspend fun loadAll(): Array<User>
</code>```

OR

```<code>@Query("SELECT * FROM user")
   fun loadAll(): Flow<Array<User>>
</code>```

Body:
When I am trying to change the Dao to the new FlowApi, I am getting the compilation error stating that

Not sure how to convert a Cursor to this method's return type
    public abstract kotlinx.coroutines.flow.Flow<java.util.List<com.ezek.ezign.model.ECampaign>> readCampaigns();

The Dao is

@Dao
interface CampaignDao {

    @Query("SELECT * FROM campaign ORDER BY timeStamp ASC")
    fun readCampaigns(): Flow<List<ECampaign>>

    @Query("SELECT * FROM campaign WHERE id = :campaignId")
    fun readCampaign(campaignId: Int): Flow<ECampaign>
}

and the dependencies are

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'

    implementation "android.arch.persistence.room:runtime:$rootProject.ext.room_version"
    kapt "android.arch.persistence.room:compiler:$rootProject.ext.room_version"

//room_version = "2.1.0"

I have tried with Both List and ArrayList, but No luck.

Thanks in advance.

Body:
Do not use both suspend and Flow<> on the same method! Like this

 @Query("SELECT * FROM user")
    suspend fun loadAll(): Flow<Array<User>>

Just

@Query("SELECT * FROM user")
    suspend fun loadAll(): Array<User>

OR

@Query("SELECT * FROM user")
   fun loadAll(): Flow<Array<User>>


问:
How can I quickly hide/resume a terminal-based app?
How can I implement the feature to quickly hide/resume a terminal-based app?

I'd like to create a very responsive tty app that can be invoked and dismissed quickly (and is not bound to a specific terminal window).  The best I have found:

an http server with a thin client.  Unfortunately, the client still has slow startup time and http incurs some latency

a background process (daemon) that redirects its tty to the current terminal session.  This turns out to be rather complicated, and platform dependent; reptyr for example (and other tools like it) is only available for linux (I would like linux & mac).

put the running app in a dedicated screen session and map key bindings to resume/detach the session.  This is...hacky to say the least, but best approximates the behavior I'm interested in.

答:
Depending on your usecase, a terminal multiplexer (like tmux, https://github.com/tmux/tmux/wiki) might be of use here, but you would need to explicitly start a session before running your application. Is this something you want to use personally, or to deploy to other users as a feature? If the former, you can "wrap" the call using tmux. This doesn't solve the problem if the latter, however.

This is better as a comment, but I lack the reputation to comment as opposed to answering your question.


问:
How to change two variables to values that are opposite to another
I have a question about changing variables.

I'm making a scoreboard for table tennis. I'm trying to show the players who has to serve. Everytime the x-key gets pressed (/when a point is scored), I check if the right to serve has to change. For this example I removed that bit.

What I'm trying to do:
Everytime an input is detected (keyboard event), the opacity of the first variable is changed to be the opposite from what is was, as well as the second variable.
Perhaps, you could think of it like a railroad crossing.

What is happening:
Only the opacity of the first variable is 1. This is due to the code running from top to bottom. It sees that the currentActionPlayer1 variable is 0, so it makes it 1. But when it reaches the if statement 'currentActionPlayer2 == 0', that is true. So the currentActionPlayer1 variable becomes 0, and cAP2 becomes 1 again.

I don't really know how to explain it any better.

var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;

window.addEventListener("keyup", checkKeyUp);

function checkKeyUp(keyUp) {
  if (keyUp.keyCode == "88") { //X
    changeActionPlayer();
  }
}

function changeActionPlayer() {
  if (currentActionPlayer1 == 1) {
    currentActionPlayer1 = 0;
    currentActionPlayer2 = 1;
    changeActionIcon();
  }
  if (currentActionPlayer2 == 1) {
    currentActionPlayer1 = 0;
    currentActionPlayer1 = 1;
    changeActionIcon();
  }
}

function changeActionIcon() {
  if (currentActionPlayer1 == 1) {
    document.getElementById('actionP1').style.opacity = "1";
    document.getElementById('actionP2').style.opacity = "0.2";
  }
  if (currentActionPlayer2 == 1) {
    document.getElementById('actionP1').style.opacity = "0.2";
    document.getElementById('actionP2').style.opacity = "1";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>

  <p id='actionP1' style='opacity: 0.2'>action</p>
  <p id='actionP2' style='opacity: 0.2'>action</p>

</body>

</html></code>```

答:
If I right understand, you need something like this one?

var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;

window.addEventListener("keyup", checkKeyUp);

function checkKeyUp(keyUp) {
  if (keyUp.code == "KeyX") { //X
    changeActionPlayer();
  }
}

function changeActionPlayer() {
    if (currentActionPlayer1 == 1) {
        currentActionPlayer1 = 0;
        currentActionPlayer2 = 1;
        changeActionIcon();
    } else if (currentActionPlayer2 == 1) {
        currentActionPlayer2 = 0;
        currentActionPlayer1 = 1;
        changeActionIcon();
    }
}

function changeActionIcon() {
  if (currentActionPlayer1 == 1) {
    document.getElementById('actionP1').style.opacity = "1";
    document.getElementById('actionP2').style.opacity = "0.2";
  }
  if (currentActionPlayer2 == 1) {
    document.getElementById('actionP1').style.opacity = "0.2";
    document.getElementById('actionP2').style.opacity = "1";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>

  <p id='actionP1' style='opacity: 0.2'>action</p>
  <p id='actionP2' style='opacity: 0.2'>action</p>

</body>

</html></code>```

Body:
I have a question about changing variables.

I'm making a scoreboard for table tennis. I'm trying to show the players who has to serve. Everytime the x-key gets pressed (/when a point is scored), I check if the right to serve has to change. For this example I removed that bit.

What I'm trying to do:
Everytime an input is detected (keyboard event), the opacity of the first variable is changed to be the opposite from what is was, as well as the second variable.
Perhaps, you could think of it like a railroad crossing.

What is happening:
Only the opacity of the first variable is 1. This is due to the code running from top to bottom. It sees that the currentActionPlayer1 variable is 0, so it makes it 1. But when it reaches the if statement 'currentActionPlayer2 == 0', that is true. So the currentActionPlayer1 variable becomes 0, and cAP2 becomes 1 again.

I don't really know how to explain it any better.

var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;

window.addEventListener("keyup", checkKeyUp);

function checkKeyUp(keyUp) {
  if (keyUp.keyCode == "88") { //X
    changeActionPlayer();
  }
}

function changeActionPlayer() {
  if (currentActionPlayer1 == 1) {
    currentActionPlayer1 = 0;
    currentActionPlayer2 = 1;
    changeActionIcon();
  }
  if (currentActionPlayer2 == 1) {
    currentActionPlayer1 = 0;
    currentActionPlayer1 = 1;
    changeActionIcon();
  }
}

function changeActionIcon() {
  if (currentActionPlayer1 == 1) {
    document.getElementById('actionP1').style.opacity = "1";
    document.getElementById('actionP2').style.opacity = "0.2";
  }
  if (currentActionPlayer2 == 1) {
    document.getElementById('actionP1').style.opacity = "0.2";
    document.getElementById('actionP2').style.opacity = "1";
  }
}

action

action

Body:
If I right understand, you need something like this one?

var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;

window.addEventListener("keyup", checkKeyUp);

function checkKeyUp(keyUp) {
  if (keyUp.code == "KeyX") { //X
    changeActionPlayer();
  }
}

function changeActionPlayer() {
    if (currentActionPlayer1 == 1) {
        currentActionPlayer1 = 0;
        currentActionPlayer2 = 1;
        changeActionIcon();
    } else if (currentActionPlayer2 == 1) {
        currentActionPlayer2 = 0;
        currentActionPlayer1 = 1;
        changeActionIcon();
    }
}

function changeActionIcon() {
  if (currentActionPlayer1 == 1) {
    document.getElementById('actionP1').style.opacity = "1";
    document.getElementById('actionP2').style.opacity = "0.2";
  }
  if (currentActionPlayer2 == 1) {
    document.getElementById('actionP1').style.opacity = "0.2";
    document.getElementById('actionP2').style.opacity = "1";
  }
}

<html>

<head>
</head>

<body>

  <p id='actionP1' style='opacity: 0.2'>action</p>
  <p id='actionP2' style='opacity: 0.2'>action</p>

</body>

</html>


问:
Navbar can't be shown
In my project after login, the Navbar has to change.

class App extends React.Component {
  render(){
        return(
          <BrowserRouter>

              {firebase.auth().onAuthStateChanged(user =>{
                if(user){
                  return(
                    <UserNavBar/>
                  )
                }else{
                  return(
                    <CommonNavBar/>
                  )
                }
              })}
              <Route path="/Home" component={Home}/>
              <Route path="/Photos" component={Photos}/>
              <Route path="/RegisterPage" component={RegisterPage}/>
              <Route path="/LoginPage" component={LoginPage}/>
              <Route path="/Account" component={Account}/>

          </BrowserRouter>
        )
    }
}

export default App```

But nothing is returned, I tried to debug it many times:

The system detects that the user is login

If I console log after the if it's work

答:
I believe the problem is that you misunderstand the Async code (Promises) and template rendering concept. You can't just return some component out of Promise and expect it to appear in the result. Here is a bit different approach that you can use for start:

```<code>import React, { useState, useEffect } from 'react';

const NavBar = ({ user, isLoading }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [user, setUser] = useState(null);

    useEffect(() => {
        firebase.auth().onAuthStateChanged(user =>{
            setUser(user);
            setIsLoading(false);
        });
    }, []);

    if (isLoading) {
        return <div>Some navigation placeholder without content while info is loading....</div>
    }

    return user ? <UserNavBar/> : <CommonNavBar/>;
}

const App = () => {
    return(
        <div className="App">
            <NavBar />

            <BrowserRouter>
                <Route path="/Home" component={Home}/>
                <Route path="/Photos" component={Photos}/>
                <Route path="/RegisterPage" component={RegisterPage}/>
                <Route path="/LoginPage" component={LoginPage}/>
                <Route path="/Account" component={Account}/>
            </BrowserRouter>
        </div>
    )
};

export default App
</code>```

Important things here:

In onAuthStateChanged we don't return some component, but we set the state data with user information. Setting state would re-render component and depends on current existing user data on hands, component would render the result.

While data is loading, it's a good practice to show some placeholder (empty nav) to avoid too much glitching

We've extracted Navigation data and rendering logic to separate component - to not pollute common App component with very specific code.

Code looks a bit differently because of Hooks API which are more "fancy and popular" these days in React community.

In case of questions, feel free to add comments, I'd be glad to help.

Title: Navbar can't be shown

Body:
In my project after login, the Navbar has to change.

class App extends React.Component {
  render(){
        return(
          <BrowserRouter>

              {firebase.auth().onAuthStateChanged(user =>{
                if(user){
                  return(
                    <UserNavBar/>
                  )
                }else{
                  return(
                    <CommonNavBar/>
                  )
                }
              })}
              <Route path="/Home" component={Home}/>
              <Route path="/Photos" component={Photos}/>
              <Route path="/RegisterPage" component={RegisterPage}/>
              <Route path="/LoginPage" component={LoginPage}/>
              <Route path="/Account" component={Account}/>

          </BrowserRouter>
        )
    }
}

export default App

But nothing is returned, I tried to debug it many times:

The system detects that the user is login

If I console log after the if it's work

Body:
I believe the problem is that you misunderstand the Async code (Promises) and template rendering concept. You can't just return some component out of Promise and expect it to appear in the result. Here is a bit different approach that you can use for start:

import React, { useState, useEffect } from 'react';

const NavBar = ({ user, isLoading }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [user, setUser] = useState(null);

    useEffect(() => {
        firebase.auth().onAuthStateChanged(user =>{
            setUser(user);
            setIsLoading(false);
        });
    }, []);

    if (isLoading) {
        return <div>Some navigation placeholder without content while info is loading....</div>
    }

    return user ? <UserNavBar/> : <CommonNavBar/>;
}

const App = () => {
    return(
        <div className="App">
            <NavBar />

            <BrowserRouter>
                <Route path="/Home" component={Home}/>
                <Route path="/Photos" component={Photos}/>
                <Route path="/RegisterPage" component={RegisterPage}/>
                <Route path="/LoginPage" component={LoginPage}/>
                <Route path="/Account" component={Account}/>
            </BrowserRouter>
        </div>
    )
};

export default App

Important things here:

In onAuthStateChanged we don't return some component, but we set the state data with user information. Setting state would re-render component and depends on current existing user data on hands, component would render the result.

While data is loading, it's a good practice to show some placeholder (empty nav) to avoid too much glitching

We've extracted Navigation data and rendering logic to separate component - to not pollute common App component with very specific code.

Code looks a bit differently because of Hooks API which are more "fancy and popular" these days in React community.

In case of questions, feel free to add comments, I'd be glad to help.


问:
How to find string length in php with out using strlen()?
How can you find the length of a string in php with out using strlen() ?

答:
```<code><?php

$arr = array('vadapalanai','annanager','chennei','salem','coimbatore');

$min = $arr[0];

$max = $arr[0];

foreach($arr as $key => $val){
    if (strlen($min) > strlen($val)) {
        $min = $val ;
    }
    if(strlen($max) < strlen($val)){
        $max = $val;
    }
}
echo "The shortest array length is : " .$min. " ".strlen($min);
echo "<br>";
echo "The longest array length is: " .$max. " ".strlen($max);

 ?>
</code>```


问:
WPF Rectangle CommandBinding MVVM
I have the following problem
I have a lot of rectangles(or a paths) and I want to add a command to every rectangle, that when I click the rectangle an object will be fill with the values of the rectangle(color,name).And from the GUI I want to change the color of the rectangle when I execute the command
How can I do that in MVVM?

For example I have an object Ractangle

public Class Rectangle{
        String name;
        String color;

   public String Color{
      get{ return color;}
      set {color=value;}

      OnPropertyChange(color);
}

  public String Name{
      get{ return name;}
      set {name=value;}
      OnPropertyChange(name);

}
```

答: I think it would be easier if you wrapped your Rectangle into a Button which gives you the readily usable Command property you can bind a command to. To be honest though I'm not 100% sure what you're after, please elaborate your scenario.</p>

Title: WPF Rectangle CommandBinding MVVM


问:
adding annotations while copying a pdf file to another
I am trying to add annotations to every Page which gets copied to my new pdf but not able to do that...

Here is my code.

```<code>import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;

import java.awt.*;
import java.io.FileOutputStream;

public class Annotations {

    public static void main(String[] args) {

        try {

            PdfReader reader = new PdfReader("string-to-pdf.pdf");
            Document document = new Document(reader.getPageSizeWithRotation(1));
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream("temp.pdf"));
            copy.setPdfVersion(PdfWriter.VERSION_1_5);
            document.open();
            for(int i = 1; i <=reader.getNumberOfPages();i++){
                copy.addPage(copy.getImportedPage(reader,i));
                copy.addAnnotation(PdfAnnotation.createLink(copy, new Rectangle(200f, 700f, 30455454f, 800f), PdfAnnotation.HIGHLIGHT_TOGGLE, PdfAction.javaScript("app.alert('Hello');\r", copy)));
            }

            document.newPage();
            // page 3
            PdfContentByte pcb = new PdfContentByte(copy);
            pcb.setColorFill(new Color(0xFF, 0x00, 0x00));

            document.close();

        } catch (Exception de) {
            de.printStackTrace();
        }
    }
}

</code>```

the files are getting copied but can't see the annotations in the new file.

答:
PdfCopy is for faithful page copying, not for creation; thus, modification routines inherited from PdfWriter are disabled, e.g.

```<code>@Override
public void addAnnotation(PdfAnnotation annot) {  }
</code>```

Dedicated manipulations are possible, though, by means of page stamps, cf. createPageStamp. The JavaDocs of that method contain some example usage code including an addition of an annotation:

```<code>PdfImportedPage page = copy.getImportedPage(reader, 1);
PdfCopy.PageStamp ps = copy.createPageStamp(page);
ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment"));
PdfContentByte under = ps.getUnderContent();
under.addImage(img);
PdfContentByte over = ps.getOverContent();
over.beginText();
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showText("total page " + totalPage);
over.endText();
ps.alterContents();
copy.addPage(page);
</code>```

Beware, though, applying a PageStamp like this actually manipulates the original PdfReader. Afterwards, therefore, don't continue using the PdfReader instance assuming its contents are the original contents, in particular the pagestamped copied pages are dirty.

Body:
I am trying to add annotations to every Page which gets copied to my new pdf but not able to do that...

Here is my code.

import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;

import java.awt.*;
import java.io.FileOutputStream;

public class Annotations {

    public static void main(String[] args) {

        try {

            PdfReader reader = new PdfReader("string-to-pdf.pdf");
            Document document = new Document(reader.getPageSizeWithRotation(1));
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream("temp.pdf"));
            copy.setPdfVersion(PdfWriter.VERSION_1_5);
            document.open();
            for(int i = 1; i <=reader.getNumberOfPages();i++){
                copy.addPage(copy.getImportedPage(reader,i));
                copy.addAnnotation(PdfAnnotation.createLink(copy, new Rectangle(200f, 700f, 30455454f, 800f), PdfAnnotation.HIGHLIGHT_TOGGLE, PdfAction.javaScript("app.alert('Hello');\r", copy)));
            }

            document.newPage();
            // page 3
            PdfContentByte pcb = new PdfContentByte(copy);
            pcb.setColorFill(new Color(0xFF, 0x00, 0x00));

            document.close();

        } catch (Exception de) {
            de.printStackTrace();
        }
    }
}

the files are getting copied but can't see the annotations in the new file.

Body:
PdfCopy is for faithful page copying, not for creation; thus, modification routines inherited from PdfWriter are disabled, e.g.

@Override
public void addAnnotation(PdfAnnotation annot) {  }

Dedicated manipulations are possible, though, by means of page stamps, cf. createPageStamp. The JavaDocs of that method contain some example usage code including an addition of an annotation:

PdfImportedPage page = copy.getImportedPage(reader, 1);
PdfCopy.PageStamp ps = copy.createPageStamp(page);
ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment"));
PdfContentByte under = ps.getUnderContent();
under.addImage(img);
PdfContentByte over = ps.getOverContent();
over.beginText();
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showText("total page " + totalPage);
over.endText();
ps.alterContents();
copy.addPage(page);

Beware, though, applying a PageStamp like this actually manipulates the original PdfReader. Afterwards, therefore, don't continue using the PdfReader instance assuming its contents are the original contents, in particular the pagestamped copied pages are dirty.


问:
How to redirect Kotlin stdio to files?
Is it possible to redirect Kotlin stdio to files through command line parameters, something like < input.txt > output.txt?
If not, is there any simple way?

I'm using IntelliJ IDEA.

答:
If you run the program with an IntelliJ IDEA run configuration, then you can configure it to save the console output to a file.

Open the run configuration settings:

In the Logs tab, check Save console output to file and enter the file name:

Redirecting is possible for Java applications as per
this Q&A, but this option seems to be missing for Kotlin. This is a known issue, please vote and follow https://youtrack.jetbrains.com/issue/KT-28854

Redirecting the input and output with < and > is the shell feature, and passing these arguments to the JVM or your program won't make any effect.

Title: How to redirect Kotlin stdio to files?


问:
Forking a process into 7 children without looping
How can I create 7 processes using 1 parent in just 3 forks() calls? Looping is not allowed out of 7 1 is the parent one

答:
I tried

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    printf("master process is %d.\n", getpid());
    fork();
    fork();
    fork();
    wait(0);
    printf("my pid is %d; my parent pid is %d\n", getpid(), getppid());
    return 0;
}
</code>```

and got the output

```
master process is 28982.
my pid is 28982; my parent pid is 31294
my pid is 28985; my parent pid is 28982
my pid is 28984; my parent pid is 28982
my pid is 28983; my parent pid is 1
my pid is 28986; my parent pid is 28984
my pid is 28988; my parent pid is 28983
my pid is 28987; my parent pid is 1
my pid is 28989; my parent pid is 28987
```

Body:
I tried

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    printf("master process is %d.\n", getpid());
    fork();
    fork();
    fork();
    wait(0);
    printf("my pid is %d; my parent pid is %d\n", getpid(), getppid());
    return 0;
}

and got the output

master process is 28982.
my pid is 28982; my parent pid is 31294
my pid is 28985; my parent pid is 28982
my pid is 28984; my parent pid is 28982
my pid is 28983; my parent pid is 1
my pid is 28986; my parent pid is 28984
my pid is 28988; my parent pid is 28983
my pid is 28987; my parent pid is 1
my pid is 28989; my parent pid is 28987


问:
Import CV2: DLL load failed: The specified module could not be found while successful pip installation
I was working with Python 3.7 and OpenCV 4.2 in Pycharm IDE (Windows10). The system environment variables were changed by one of my co-workers by accident (we don't know what happened exactly). Then I found that my code did not work with this error!:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed: The specified module could not be found.
</code>```

Then I used this command:

```<code>pip uninstall opencv-python
pip uninstall opencv-contrib-python
pip install opencv-python
</code>```

All of them executed successfully, but when I write import cv2 the above error is appeared. By the way, the system knows command Python, it shows the right path to the python.exe. Moreover, commands like import numpy works correctly! How can I fix this problem?

答: I found the answer! There was an extra cv2.py file in site-packages/cv2 path. So, I removed it and the code worked

Body:
I was working with Python 3.7 and OpenCV 4.2 in Pycharm IDE (Windows10). The system environment variables were changed by one of my co-workers by accident (we don't know what happened exactly). Then I found that my code did not work with this error!:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed: The specified module could not be found.

Then I used this command:

pip uninstall opencv-python
pip uninstall opencv-contrib-python
pip install opencv-python

All of them executed successfully, but when I write import cv2 the above error is appeared. By the way, the system knows command Python, it shows the right path to the python.exe. Moreover, commands like import numpy works correctly! How can I fix this problem?


问:
the following code is about rotating a sorted arrray by some value d
my code is not working it is producing unexpected results.the code is about array rotation by using  a temp array . function "rotate" rotates the array , while function printArray prints the array .in the main function both functions are called. then there is cout with "hello". the overall output if "ellolloloohello". why am i getting this output.thanks

```<code> #include<iostream>
 using namespace std;

 void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}

}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{

    cout<<arr[i]+" " ;
}
}
int main()
{

int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;
</code>```

the output is "ellolloloohello" instead of "hello". whats happening here?????

答:
For starters the variable length arrays

```<code>void rotate(int arr[],int d, int n){
    int temp[d];
    //...
</code>```

is not a standard C++ feature. Either use an auxiliary standard container as for example std::vector or std::list or you should dynamically allocate an array.

In the last loop of the function

```<code> void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}
}
</code>```

you are overwriting the array temp instead of the array arr.

And in the function printArray in this statement

```<code>cout<<arr[i]+" " ;
</code>```

in the expression

```<code>arr[i]+" "
</code>```

there is used the pointer arithmetic. That is the string literal " " is implicitly converted to pointer to its first element and the numeric value arr[i] is used as an offset for this pointer. Instead write

```<code>cout<<arr[i] << " " ;
</code>```

Body:
my code is not working it is producing unexpected results.the code is about array rotation by using  a temp array . function "rotate" rotates the array , while function printArray prints the array .in the main function both functions are called. then there is cout with "hello". the overall output if "ellolloloohello". why am i getting this output.thanks

 #include<iostream>
 using namespace std;

 void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}

}
void printArray(int arr[],int size){
for(int i =0;i<size;i++)
{

    cout<<arr[i]+" " ;
}
}
int main()
{

int arr[10] = {0,1,2,3,4,5,6,7,8,9};
rotate(arr,3,10);
printArray(arr,10);
cout <<"hello";
}
;

the output is "ellolloloohello" instead of "hello". whats happening here?????

Body:
For starters the variable length arrays

void rotate(int arr[],int d, int n){
    int temp[d];
    //...

is not a standard C++ feature. Either use an auxiliary standard container as for example std::vector or std::list or you should dynamically allocate an array.

In the last loop of the function

 void rotate(int arr[],int d, int n){
int temp[d];
for(int i =0;i<d;i++){
    temp[i]=arr[i];

}
for(int i = 0;i<n-d;i++){
    arr[i] = arr[i+d];
}
for(int i =0 ;i < d;i++)
{
    temp[i]= arr[n-d+i];

}
}

you are overwriting the array temp instead of the array arr.

And in the function printArray in this statement

cout<<arr[i]+" " ;

in the expression

arr[i]+" "

there is used the pointer arithmetic. That is the string literal " " is implicitly converted to pointer to its first element and the numeric value arr[i] is used as an offset for this pointer. Instead write

cout<<arr[i] << " " ;


问:
How can i list all holidays' date for each country using holidays module in python?
I am trying to find holidays' date with holidays package in python for many countries but, instead of writing one by one like this:

```<code>import holidays
for date in holidays.UnitedKingdom(years=2011).items():
    print(str(date[0]))

for date in holidays.Argentina(years=2011).items():
    print(str(date[0]))
</code>```

I am trying to do this with a function like this:

```<code>for i in dir(holidays):
    for j in range(2010,2016):
        holidays.i(years=2011).keys()
</code>```

I know that with loop every country's name is a string but I want to implement it as a loop, if you have any advice or suggestion please share with me.
thank you.

答:
Firstly: pip show holidays
and then copy the location into the locationVariable

```<code>import holidays
import os
locationVariable = ""
countries = [name.split(".py")[0].replace("_"," ") for name in os.listdir(locationVariable+"holidays/countries/") if name.endswith(".py") and  not name.startswith("__")]

print("List of countries are : " + str(len(countries)))

for i in countries:
    for j in range(2010,2021):
        try:
            print(getattr(holidays,i.title().replace(" ",""))(years=j).keys())
        except:
            print("unable to iterate "+i.title().replace(" ",""))
            break
</code>```

seems like the formatting of the name is inconsistent(for Hongkong), please and use.

Make sure to mark is answered if helpfull.

Body:
I am trying to find holidays' date with holidays package in python for many countries but, instead of writing one by one like this:

import holidays
for date in holidays.UnitedKingdom(years=2011).items():
    print(str(date[0]))

for date in holidays.Argentina(years=2011).items():
    print(str(date[0]))

I am trying to do this with a function like this:

for i in dir(holidays):
    for j in range(2010,2016):
        holidays.i(years=2011).keys()

I know that with loop every country's name is a string but I want to implement it as a loop, if you have any advice or suggestion please share with me.
thank you.

Body:
Firstly: pip show holidays
and then copy the location into the locationVariable

import holidays
import os
locationVariable = ""
countries = [name.split(".py")[0].replace("_"," ") for name in os.listdir(locationVariable+"holidays/countries/") if name.endswith(".py") and  not name.startswith("__")]

print("List of countries are : " + str(len(countries)))

for i in countries:
    for j in range(2010,2021):
        try:
            print(getattr(holidays,i.title().replace(" ",""))(years=j).keys())
        except:
            print("unable to iterate "+i.title().replace(" ",""))
            break

seems like the formatting of the name is inconsistent(for Hongkong), please and use.

Make sure to mark is answered if helpfull.


问:
How to socialize GWT application?
I am developing a GWT application that displays services provided by a company and I must allow users to share links of services in social networks like Facebook, LinkedIn and Twitter.
Have you any idea how to do such a thing?
Any help is appreciated
Thank you in advance for your help :)

Edit

i have tried AddThis but nothing was displayed
there is the code :

```<code>    HTML socialNetworkLink = new HTML(
            "<div class=\"addthis_toolbox addthis_default_style addthis_32x32_style\">"
                    + "<a class=\"addthis_button_preferred_1\"></a>"
                    + "<a class=\"addthis_button_preferred_2\"></a>"
                    + "<a class=\"addthis_button_preferred_3\"></a>"
                    + "<a class=\"addthis_button_preferred_4\"></a>"
                    + "<a class=\"addthis_button_compact\"></a>"
                    + "<a class=\"addthis_counter addthis_bubble_style\"></a>"
                    + "</div>"
                    + "<script type=\"text/javascript\">var addthis_config = {\"data_track_clickback\":true};</script>"
                    + "<script type=\"text/javascript\" src=\"http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4dd380ca4d8393c9\"></script>");
    sharePanel.add(socialNetworkLink);
</code>```

答:
Twitter: http://twitter.com/about/resources/tweetbutton

Facebook: http://developers.facebook.com/docs/reference/plugins/like/

LinkedIn: http://developer.linkedin.com/docs/DOC-1075

So where's the problem?

Title: How to socialize GWT application?

Body:
I am developing a GWT application that displays services provided by a company and I must allow users to share links of services in social networks like Facebook, LinkedIn and Twitter.
Have you any idea how to do such a thing?
Any help is appreciated
Thank you in advance for your help :)

Edit

i have tried AddThis but nothing was displayed
there is the code :

    HTML socialNetworkLink = new HTML(
            "
"
                    + ""
                    + ""
                    + ""
                    + ""
                    + ""
                    + ""
                    + "
"
                    + ""
                    + "");
    sharePanel.add(socialNetworkLink);


问:
Access-Control-Allow-Origin cors error happening on NodeJS or Nginx
First at all, I have researched about the topic after writing the question, there are many similar question but I think the problem here is different:

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

We are getting  this Access-Control-Allow-Origin cors error just when we send a heavy request:

Access to XMLHttpRequest at 'https://backend.*****.es/xxxxxx' from
  origin 'https://www.testing.*******.es' has been blocked by CORS
  policy: No 'Access-Control-Allow-Origin' header is present on the
  requested resource

The rest of the request are working fine, I tried setting:

```<code>app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});
</code>```

but I got the same error.

I am starting to think it can be related with nginx.

This is the architecture we are using:

NodeJs, Expressjs

Middlewares:

const LIMIT = '100mb';
const global = () => [
    morganMiddleware(),
    compression(),
    cors(),
    bodyParser.urlencoded({ extended: true, limit: LIMIT }),
    bodyParser.json({ limit: LIMIT }),
    helmet(),
];

Server: Nginx 12.14.1

Host in AWS Elastic BeanStalk

Let me know if anyone have any clue what can be happening because I do not know if it is coming from our nodejs server, or nginx. We have tested many solutions and are still checking out other options.

答:
We are getting this error in our sever:

2020/02/20 10:56:00 [error] 2784#0: *127 client intended to send too
  large body: 4487648 bytes, client: 172.31.3.222, server: , request:
  "PUT /cars/drafts/f7124841-f72c-4133-b49e-d9f709b4cf4d HTTP/1.1",
  host: "backend.xxxxx.es", referrer:
  "https://www.testing.xxxx.es/sellcar/photos/f7124841-f72c-4133-b49e-d9f709b4cf4d"

So besides the error that appears in the front is Access-Control-Allow-Origin it is related with the a limit set in NGINX.

Now we just need to figure out how to access to our elastic beanstalk instance to change that variables and that is already solved.

SSH to Elastic Beanstalk instance

To solve it, create a file x.config inside .ebextensions and change this variables with the next yaml file:

```<code>files:
  "/etc/nginx/conf.d/01-client_max_body_size.conf":
    mode: 000644
    owner: root
    group: root
    content: |
      # MODIFIED VARIABLES ADDED BY 01-client_max_body_size.conf
      client_max_body_size 12m;
      client_body_buffer_size 16k;
container_commands:
  nginx_reload:
    command: sudo service nginx reload
</code>```

Then redeploy you environment.

Thank you very much all for your help!

Body:
First at all, I have researched about the topic after writing the question, there are many similar question but I think the problem here is different:

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

We are getting  this Access-Control-Allow-Origin cors error just when we send a heavy request:

Access to XMLHttpRequest at 'https://backend.*****.es/xxxxxx' from
  origin 'https://www.testing.*******.es' has been blocked by CORS
  policy: No 'Access-Control-Allow-Origin' header is present on the
  requested resource

The rest of the request are working fine, I tried setting:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

but I got the same error.

I am starting to think it can be related with nginx.

This is the architecture we are using:

NodeJs, Expressjs

Middlewares:

const LIMIT = '100mb';
const global = () => [
    morganMiddleware(),
    compression(),
    cors(),
    bodyParser.urlencoded({ extended: true, limit: LIMIT }),
    bodyParser.json({ limit: LIMIT }),
    helmet(),
];

Server: Nginx 12.14.1

Host in AWS Elastic BeanStalk

Let me know if anyone have any clue what can be happening because I do not know if it is coming from our nodejs server, or nginx. We have tested many solutions and are still checking out other options.

Body:
We are getting this error in our sever:

2020/02/20 10:56:00 [error] 2784#0: *127 client intended to send too
  large body: 4487648 bytes, client: 172.31.3.222, server: , request:
  "PUT /cars/drafts/f7124841-f72c-4133-b49e-d9f709b4cf4d HTTP/1.1",
  host: "backend.xxxxx.es", referrer:
  "https://www.testing.xxxx.es/sellcar/photos/f7124841-f72c-4133-b49e-d9f709b4cf4d"

So besides the error that appears in the front is Access-Control-Allow-Origin it is related with the a limit set in NGINX.

Now we just need to figure out how to access to our elastic beanstalk instance to change that variables and that is already solved.

SSH to Elastic Beanstalk instance

To solve it, create a file x.config inside .ebextensions and change this variables with the next yaml file:

files:
  "/etc/nginx/conf.d/01-client_max_body_size.conf":
    mode: 000644
    owner: root
    group: root
    content: |
      # MODIFIED VARIABLES ADDED BY 01-client_max_body_size.conf
      client_max_body_size 12m;
      client_body_buffer_size 16k;
container_commands:
  nginx_reload:
    command: sudo service nginx reload

Then redeploy you environment.

Thank you very much all for your help!


问:
Making at least One Checkbox mandatory out of the given checkboxes on submit
I have the several check boxes inside of the form group. How can I made this Area of Interest checkbox mandatory on submit? At least the user clicks on one checkbox before submitting. I have used react-bootstrap.

Any help are appreciated.

<Form.Group>
    <Form.Label>Area of Interest</Form.Label>
    <Form.Check
        name="areaOfInterest"
        label="Dedicated Teams"
        id="dt"
        value={"Dedicated Teams" || formInput.areaOfInterest}
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Cloud Expert Advice & Support"
        id="ceas"
        value="Cloud Expert Advice & Support"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Software Development"
        id="sd"
        value="Software Development"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Digital Transformation"
        id="dit"
        value="Digital Transformation"
        onChange={handleCheck}
    />
</Form.Group>
```

答: You can simply check before submitting the form if areaOfInterest has any value to it or not. If it doesn't, show user an error telling them it's a compulsory. If areaOfInterest has even a single response to it, let the form submit.


问:
(SAS) Proc HPBIN output with original variables
In SAS, Proc HPBIN, OUTPUT option does not keep original variables as explained below

OUTPUT=SAS-data-set
creates an output SAS data set in single-machine mode or a database table that is saved alongside the distributed database in distributed mode. The output data set or table contains binning variables. To avoid data duplication for large data sets, the variables in the input data set are not included in the output data set.

--> How can I keep original variables and bin number?

答:
Do a 1:1 merge of the output data set with the input data set.

For example:

```<code>proc hpbin data=sashelp.orsales noprint out=profitbinned;
  var profit;
run;

data want;
  merge sashelp.orsales profitbinned;
  * 1:1 merge does not have a BY statement;
run;
</code>```

If the input data has a primary, or unique key, you can specify those key variables in an ID statement to ensure a more robust post-binning merge:

```<code>proc hpbin data=sashelp.citiday noprint out=dowcmp_binned;
  var SNYDJCM;
  id date;
run;

proc sql;
  create table want as
  select bin.date, ticker.SNYDJCM, bin.bin_SNYDJCM
  from sashelp.citiday as ticker
  join work.dowcmp_binned as bin
  on ticker.date = bin.date
  order by bin.date;
</code>```

Body:
Do a 1:1 merge of the output data set with the input data set.

For example:

proc hpbin data=sashelp.orsales noprint out=profitbinned;
  var profit;
run;

data want;
  merge sashelp.orsales profitbinned;
  * 1:1 merge does not have a BY statement;
run;

If the input data has a primary, or unique key, you can specify those key variables in an ID statement to ensure a more robust post-binning merge:

proc hpbin data=sashelp.citiday noprint out=dowcmp_binned;
  var SNYDJCM;
  id date;
run;

proc sql;
  create table want as
  select bin.date, ticker.SNYDJCM, bin.bin_SNYDJCM
  from sashelp.citiday as ticker
  join work.dowcmp_binned as bin
  on ticker.date = bin.date
  order by bin.date;


问:
Cookie showing alert after move on next steps(page)
I'm using the Stepper for Register process (like this: step-1...to, step3) which every step is a different page in bootstrap4.

When a page load Cookie alert will be showing. But after the close it (stored into local storage) or will be removed after 10 Seconds. when will I move to the next step (step-2), Cookie alert will be again showing. Actually don't want to show it again (if once closed it) till the end (last step).

Is there a way to handle this issue? Below mentioned the code I'm using right now. Please help.

```<code>$(function () {
  if (getCookie('BlockPop') == null || (getCookie('BlockPop') != undefined && getCookie('BlockPop').toLowerCase() != 'true')) {
        setCookie('BlockPop', 'true', 30);
        $('.popuphome').slideToggle(1000);
        $('.close').click(function () {
            setCookie('BlockPop', 'true', 30);
            $('.popuphome').slideUp(1000);
        });
        setTimeout(function () {
            $('.popuphome').slideUp(1000);
        }, 30000);
    }
});

function setCookie(ckname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = ckname + "=" + cvalue + "; " + expires;
}
function getCookie(ckname) {
    var name = ckname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
</code>```

答:
Firstly != undefined is not how to check if something is undefined, sadly. So change that condition to

typeof getCookie('BlockPop') !== 'undefined'
```

<p>Next up, your full if statement essentially says "if the BlockPop cookie is null or if it is defined and has the value <code>'true'</code> then ..."</p>

<p>I'm not sure how the code guarded by your if statement will <strong>not</strong> be executed.</p>

<p>I think you'll get the desired effect if you change the condition to be </p>

<pre class="lang-js prettyprint-override"><code>if(getCookie('BlockPop') === '')
</code>```

Because now you're checking if the cookie is empty, and then you will set it. getCookie returns an empty string for an undefined cookie, so you don't need to check for null or undefined.

Once it's set you'll not call the rest of the code for 30 days. The time parameter (exdays) of setCookie is the number of days until the cookie expires, so it will last far more than 10 seconds.

If you want the cookie to expire after 10 seconds, then change the code in setCookie that sets the expiry to:

d.setTime(d.getTime() + (exdays * 1000));
```

<p>And call <code>setCookie</code> like:</p>

<pre class="lang-js prettyprint-override"><code>setCookie('BlockPop', 'true', 10);
</code>```

Body:
I'm using the Stepper for Register process (like this: step-1...to, step3) which every step is a different page in bootstrap4.

When a page load Cookie alert will be showing. But after the close it (stored into local storage) or will be removed after 10 Seconds. when will I move to the next step (step-2), Cookie alert will be again showing. Actually don't want to show it again (if once closed it) till the end (last step).

Is there a way to handle this issue? Below mentioned the code I'm using right now. Please help.

$(function () {
  if (getCookie('BlockPop') == null || (getCookie('BlockPop') != undefined && getCookie('BlockPop').toLowerCase() != 'true')) {
        setCookie('BlockPop', 'true', 30);
        $('.popuphome').slideToggle(1000);
        $('.close').click(function () {
            setCookie('BlockPop', 'true', 30);
            $('.popuphome').slideUp(1000);
        });
        setTimeout(function () {
            $('.popuphome').slideUp(1000);
        }, 30000);
    }
});

function setCookie(ckname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = ckname + "=" + cvalue + "; " + expires;
}
function getCookie(ckname) {
    var name = ckname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

Body:
Firstly != undefined is not how to check if something is undefined, sadly. So change that condition to

typeof getCookie('BlockPop') !== 'undefined'

Next up, your full if statement essentially says "if the BlockPop cookie is null or if it is defined and has the value 'true' then ..."

I'm not sure how the code guarded by your if statement will not be executed.

I think you'll get the desired effect if you change the condition to be

if(getCookie('BlockPop') === '')

Because now you're checking if the cookie is empty, and then you will set it. getCookie returns an empty string for an undefined cookie, so you don't need to check for null or undefined.

Once it's set you'll not call the rest of the code for 30 days. The time parameter (exdays) of setCookie is the number of days until the cookie expires, so it will last far more than 10 seconds.

If you want the cookie to expire after 10 seconds, then change the code in setCookie that sets the expiry to:

d.setTime(d.getTime() + (exdays * 1000));

And call setCookie like:

setCookie('BlockPop', 'true', 10);


问:
Method to clear pre-filled data of a ST.future.Component
Is there a way to clear an input field while using the ST.component("locator"); API?

Using ST.component("locator").setValue(""); results in the following error:

TypeError: ST.component(...).setValue is not a function...

PS: Is the old forum now permanently closed? Is there a way to view older questions?

Edit: Seems like the other forum was down yesterday, therefore the PS.

答:
If it's an Ext JS field you will need to use the ST.field API in Sencha Test, which has a setValue method. This method isn't available on the more generic ST.component API.

```<code>ST.field('myfield')
    .setValue('');
</code>```

Or if it's a normal input field (not an Ext JS component), then you can do the following:

```<code>ST.element('@myfield')
    .execute(function(field) {
        field.dom.value = '';
    });
</code>```

Body:
If it's an Ext JS field you will need to use the ST.field API in Sencha Test, which has a setValue method. This method isn't available on the more generic ST.component API.

ST.field('myfield')
    .setValue('');

Or if it's a normal input field (not an Ext JS component), then you can do the following:

ST.element('@myfield')
    .execute(function(field) {
        field.dom.value = '';
    });


问:
Delete X files in each folders and sub folders
I want to delete files in a folder and its subfolders but not X last files again in each folder. For example in C:\Test I want to keep 10 txt files but also in C:\Test\subtest1 and C:\Test\subtest2. Here, X X is the number of files I want to keep.

But it will not keep 10 files in each folder but in the entire arborescence.

My script is not fully functional, but it did it well in the C:\Test directory:

```<code>Set-ExecutionPolicy unrestricted $txtfiles = 'C:\Users\MUC8VX\Documents\Test
ForEach-Object {    Get-ChildItem $txtfiles | where{ -not $_.PsIsContainer}|
     sort LastWriteTime -desc| select -Skip 10 |
     Remove-Item -Include *.txt* -Force }
</code>```

And if I add -Recurse it will not keep 10 files in each folders but in the entire arborescence:

```<code>Set-ExecutionPolicy unrestricted
$txtfiles =`C:\Users\MUC8VX\Documents\Test'
ForEach-Object {    Get-ChildItem $txtfiles -Recurse | where{ -not
 $_.PsIsContainer}| sort LastWriteTime -desc|
     select -Skip 10 | Remove-Item -Include *.txt* -Force }
</code>```

edit :
Thanks a lot Manuel Batsching.

Here's a generic script :

```<code>#Insert your parent folder which contains files and subfolders

Get-Childitem -Path C:\Your\Parent\Folder -Recurse |

Group-Object Directory |
ForEach-Object {
    $_.Group |

        #sort by the last written files
        Sort-Object LastWriteTime -Descending |

        #Keep the X last files you want to keep
        Select-Object -Skip X |

        #Remove files according to their extension
        Remove-Item -Include *.extension* -Force }
</code>```

答:
I haven't tested but you can try this.

```<code>Set-ExecutionPolicy unrestricted
$txtfiles = 'C:\Users\MUC8VX\Documents\Test'
Get-ChildItem -Directory -Recurse -Path $txtfiles | ForEach-Object {
    Get-ChildItem -Path $_.fullname -Include *.txt | Sort-Object LastWriteTime -Descending | Select-Object -Skip 10 | Remove-Item -Force
}
</code>```

Basically, this code iterate over each folder recursively, for each folder, it find the files, skip 10 and remove all others.

Body:
I want to delete files in a folder and its subfolders but not X last files again in each folder. For example in C:\Test I want to keep 10 txt files but also in C:\Test\subtest1 and C:\Test\subtest2. Here, X X is the number of files I want to keep.

But it will not keep 10 files in each folder but in the entire arborescence.

My script is not fully functional, but it did it well in the C:\Test directory:

Set-ExecutionPolicy unrestricted $txtfiles = 'C:\Users\MUC8VX\Documents\Test
ForEach-Object {    Get-ChildItem $txtfiles | where{ -not $_.PsIsContainer}|
     sort LastWriteTime -desc| select -Skip 10 |
     Remove-Item -Include *.txt* -Force }

And if I add -Recurse it will not keep 10 files in each folders but in the entire arborescence:

Set-ExecutionPolicy unrestricted
$txtfiles =`C:\Users\MUC8VX\Documents\Test'
ForEach-Object {    Get-ChildItem $txtfiles -Recurse | where{ -not
 $_.PsIsContainer}| sort LastWriteTime -desc|
     select -Skip 10 | Remove-Item -Include *.txt* -Force }

edit :
Thanks a lot Manuel Batsching.

Here's a generic script :

#Insert your parent folder which contains files and subfolders

Get-Childitem -Path C:\Your\Parent\Folder -Recurse |

Group-Object Directory |
ForEach-Object {
    $_.Group |

        #sort by the last written files
        Sort-Object LastWriteTime -Descending |

        #Keep the X last files you want to keep
        Select-Object -Skip X |

        #Remove files according to their extension
        Remove-Item -Include *.extension* -Force }

Body:
I haven't tested but you can try this.

Set-ExecutionPolicy unrestricted
$txtfiles = 'C:\Users\MUC8VX\Documents\Test'
Get-ChildItem -Directory -Recurse -Path $txtfiles | ForEach-Object {
    Get-ChildItem -Path $_.fullname -Include *.txt | Sort-Object LastWriteTime -Descending | Select-Object -Skip 10 | Remove-Item -Force
}

Basically, this code iterate over each folder recursively, for each folder, it find the files, skip 10 and remove all others.


问:
Python pandas - Divide a column in dataframe1 with a column in dataframe2 based on another column in dataframe1
Dateframe1

```<code>df = pd.DataFrame(SQL_Query, columns=[ X,Y . . . . Currency,Amount]

Index         X             Y  ...         Currency          Amount
0             74            1  ...         USD               100
1             75            1  ...         EUR               5000
2             76            1  ...         AUD               300
3             79            1  ...         EUR               750

[1411137 rows x 162 columns]
</code>```

A large SQL query so I avoid writing out all columns.

```<code>df1=pd.read_excel(r`FX_EUR.xlsx)

Index       Currency      FX
0             AUD      1.61350
1             BGN      1.95580
2             BRL      4.51450
3             CAD      1.45830
4             CHF      1.09280
</code>```

So what would I like to achieve is to make a lookup in DF1 to see which Currency is used then divide the "DF1 Amount" column with "DF2 FX" column and to this for all rows in DF1. Either by making a third DF3 or by creating a new column i DF1 called Amount_EUR.

Any ideas on how to write this code?

答:
You could use merge to build a series containing the correct FX (same Currency) with the same index as df. The division is then trivial:

```<code>fx = df.merge(df1, 'left', on='Currency')['FX']
df.loc[~ fx.isna(),'EUR_Amount'] = df.loc[~ fx.isna()]['Amount']/fx.loc[~ fx.isna()]
</code>```

With your sample data it gives:

```<code>        X  Y  ... Currency  Amount  EUR_Amount
Index
0      74  1  ...      USD     100         NaN
1      75  1  ...      EUR    5000         NaN
2      76  1  ...      AUD     300  185.931205
3      79  1  ...      EUR     750         NaN
</code>```

Body:
Dateframe1

df = pd.DataFrame(SQL_Query, columns=[ X,Y . . . . Currency,Amount]

Index         X             Y  ...         Currency          Amount
0             74            1  ...         USD               100
1             75            1  ...         EUR               5000
2             76            1  ...         AUD               300
3             79            1  ...         EUR               750

[1411137 rows x 162 columns]

A large SQL query so I avoid writing out all columns.

df1=pd.read_excel(r`FX_EUR.xlsx)

Index       Currency      FX
0             AUD      1.61350
1             BGN      1.95580
2             BRL      4.51450
3             CAD      1.45830
4             CHF      1.09280

So what would I like to achieve is to make a lookup in DF1 to see which Currency is used then divide the "DF1 Amount" column with "DF2 FX" column and to this for all rows in DF1. Either by making a third DF3 or by creating a new column i DF1 called Amount_EUR.

Any ideas on how to write this code?

Body:
You could use merge to build a series containing the correct FX (same Currency) with the same index as df. The division is then trivial:

fx = df.merge(df1, 'left', on='Currency')['FX']
df.loc[~ fx.isna(),'EUR_Amount'] = df.loc[~ fx.isna()]['Amount']/fx.loc[~ fx.isna()]

With your sample data it gives:

        X  Y  ... Currency  Amount  EUR_Amount
Index
0      74  1  ...      USD     100         NaN
1      75  1  ...      EUR    5000         NaN
2      76  1  ...      AUD     300  185.931205
3      79  1  ...      EUR     750         NaN


问:
Retrieve RGB image from 1-dim array containing RGB image data
I pass a C array containing RGB image data to a function in Python to further process the image.
How can I retrieve this image and plot it as well in Python?

the C array named c_data that contains RGB image data was created by

```<code>for(k = 0; k < c; ++k){
    for(j = 0; j < h; ++j){
        for(i = 0; i < w; ++i){
            int dst_index = i + w*j + w*h*k;
            int src_index = k + c*i + c*w*j;
            c_data[dst_index] = (float)stb_im[src_index]/255.;
        }
    }
}
</code>```

the C array is converted into a numpy array and is passed to the Python function with the following header via the parameter named im_data

```<code>def read_img_from_c(im_data, im_h, im_w):

print(im_h) // 480
print(im_w) // 640
print(im_data.shape) // (921600,) --> (480*640*3)
</code>```

I tried to simply reshape the numpy array using

```<code>data = im_data.reshape((im_h, im_w, 3))
</code>```

and create a PIL image object using

```<code>img = PIL.Image.fromarray(data, 'RGB')
</code>```

, but when I run the following command

```<code>img.show()
</code>```

I got the following rather than the original image.

Update: I follow the suggestion by multiplying those normalized pixel values by 255.0, cast the numpy array to type int and plot:

```<code>im_data = (im_data*255.0).astype(np.uint8)
im_data = im_data.reshape((im_h, im_w, 3))
img = Image.fromarray(im_data, 'RGB')
img.show()
</code>```

and I got the image with repeated patterns instead of a single big RGB
image:

答: Try multiplying data by 255 again and rounding it to int. I guess the values in RGB tuple should be from range 0-255, not 0-1.

Body:
I pass a C array containing RGB image data to a function in Python to further process the image.
How can I retrieve this image and plot it as well in Python?

the C array named c_data that contains RGB image data was created by

for(k = 0; k < c; ++k){
    for(j = 0; j < h; ++j){
        for(i = 0; i < w; ++i){
            int dst_index = i + w*j + w*h*k;
            int src_index = k + c*i + c*w*j;
            c_data[dst_index] = (float)stb_im[src_index]/255.;
        }
    }
}

the C array is converted into a numpy array and is passed to the Python function with the following header via the parameter named im_data

def read_img_from_c(im_data, im_h, im_w):

print(im_h) // 480
print(im_w) // 640
print(im_data.shape) // (921600,) --> (480*640*3)

I tried to simply reshape the numpy array using

data = im_data.reshape((im_h, im_w, 3))

and create a PIL image object using

img = PIL.Image.fromarray(data, 'RGB')

, but when I run the following command

img.show()

I got the following rather than the original image.

Update: I follow the suggestion by multiplying those normalized pixel values by 255.0, cast the numpy array to type int and plot:

im_data = (im_data*255.0).astype(np.uint8)
im_data = im_data.reshape((im_h, im_w, 3))
img = Image.fromarray(im_data, 'RGB')
img.show()

and I got the image with repeated patterns instead of a single big RGB
image:


问:
MQTT/MongoDB application performance loss after update
I updated an application that subscribes on MQTT topics and persists received messages in a MongoDB database.

Is use the paho Java MQTT driver and Spring Data MongoDB.

The application works like this:

When a message arrives the message processing is moved to a separate Thread (using ThreadPoolExecutor). Thus arrived messages are confirmed very fast, which I need to not get into trouble with dropped messages because of 'inflight queue full' errors when the system is under temporary heavy load. What might happen, but which I normally not observe, is, that the ThreadPoolExecutor Queue grows rapidly because it can not be handled fast enough.

After updating the system I observe that - especially after the start, but not only - the ThreadPoolExecutor queue grows. The application always manages to catch up with the processing, but there are always times when the queue grows to several 10 thousand tasks. And this with a continuously same load of about 700 messages per second (because of testing).

What I tested so far is:

```<code>Java  8 and App build with Java 8  -> works great
Java 11 and App build with Java 8  -> works great (some Illegal reflective access warnings of course)
Java 11 and App build with Java 11 -> makes some problems
</code>```

The application update contains dependency updates of course, mainly the following

```<code>spring-boot-starter-data-mongodb         1.15.12.RELEASE -> 2.2.4.RELEASE
  spring-data-mongodb                    1.10.11.RELEASE -> 2.2.4.RELEASE
  mongodb-driver                                          3.4.3 -> 3.11.2

org.eclipse.paho.client.mqttv3                              1.2.0 -> 1.2.2

MongoDB Server Version is 3.4.24
</code>```

I suspect that something in the libraries is causing the performance to degrade. Something like the changed WriteConcern in the MongoDB Java Driver like described here (but this is not my problem because I already use the mongo driver 3.4.3 in my Java 8 build application). I just can't find what it can be.

If you have any idea what could be causing this behavior, please let me know. Right now I'm at a loss.

答:
It turned out that the update of the paho java MQTT client from version 1.2.0 to 1.2.1 (or also 1.2.2) caused a significant increase of CPU usage.

The issue #754 was created in the GitHub issue tracker for this.

Body:
I updated an application that subscribes on MQTT topics and persists received messages in a MongoDB database.

Is use the paho Java MQTT driver and Spring Data MongoDB.

The application works like this:

When a message arrives the message processing is moved to a separate Thread (using ThreadPoolExecutor). Thus arrived messages are confirmed very fast, which I need to not get into trouble with dropped messages because of 'inflight queue full' errors when the system is under temporary heavy load. What might happen, but which I normally not observe, is, that the ThreadPoolExecutor Queue grows rapidly because it can not be handled fast enough.

After updating the system I observe that - especially after the start, but not only - the ThreadPoolExecutor queue grows. The application always manages to catch up with the processing, but there are always times when the queue grows to several 10 thousand tasks. And this with a continuously same load of about 700 messages per second (because of testing).

What I tested so far is:

Java  8 and App build with Java 8  -> works great
Java 11 and App build with Java 8  -> works great (some Illegal reflective access warnings of course)
Java 11 and App build with Java 11 -> makes some problems

The application update contains dependency updates of course, mainly the following

spring-boot-starter-data-mongodb         1.15.12.RELEASE -> 2.2.4.RELEASE
  spring-data-mongodb                    1.10.11.RELEASE -> 2.2.4.RELEASE
  mongodb-driver                                          3.4.3 -> 3.11.2

org.eclipse.paho.client.mqttv3                              1.2.0 -> 1.2.2

MongoDB Server Version is 3.4.24

I suspect that something in the libraries is causing the performance to degrade. Something like the changed WriteConcern in the MongoDB Java Driver like described here (but this is not my problem because I already use the mongo driver 3.4.3 in my Java 8 build application). I just can't find what it can be.

If you have any idea what could be causing this behavior, please let me know. Right now I'm at a loss.