问:
Threads running inside a child process are not timing out as per the set alarm time
This question is an extension to my previous question.

The only addition here is that now I would like the threads to timeout if the operation is not complete within the set timeout duration.

So after going through the perldoc and certain examples, I have drafted a working version and it works - but there is something off.

The timeout doesn't exactly happen in the set duration but sometimes takes double  the amount of time.

I am not able to investigate this and I need you help on the same on how to investigate this further.

In this program, I have set the timeout value to 3 seconds via alarm function and have installed signal handler in the thread function.

My observations during the multiple runs are as follows:

timeout never happens below the set value.

timeout happens always above the set value and its value is never exactly the set value.

Please find the program output & the program itself for your review. Your comments and feedback are welcome.

Program output:

```<code>(20:51:59) $:little-stuff>  perl 10-20190530-batch-processing-using-threads-with-busy-pool-detection-2-with-threads-timeout.pl 12
29872: STARTING TASKS IN BATCHES
29872: MAIN: engine (e1) is RUNNING batch #1 tasks: (1 2)
29872: MAIN: engine (e2) is RUNNING batch #2 tasks: (3 4 5)
29872: MAIN: engine (e3) is RUNNING batch #3 tasks: (6 7)
29878: TASK_RUNNER: engine (e3) finished batch #3 task #7 in (1.27) seconds
29878: TASK_RUNNER: engine (e3) finished batch #3 task #6 in (2.12) seconds
29876: TASK_RUNNER: engine (e1) finished batch #1 task #1 in (2.97) seconds
29878: TASK_ORCHESTRATOR: engine (e3) finished batch #3 tasks in (2.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29878) has finished with status (0).
29877: TASK_RUNNER: engine (e2) finished batch #2 task #4 in (3.65) seconds
29877: TASK_RUNNER: engine (e2) finished batch #2 task #3 in (4.62) seconds
29872: MAIN: engine (e3) is RUNNING batch #4 tasks: (8 9)
29876: TASK_RUNNER: engine (e1) finished batch #1 task #2 in (6.43) seconds
29876: TASK_ORCHESTRATOR: engine (e1) finished batch #1 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29876) has finished with status (0).
29872: MAIN: engine (e1) is RUNNING batch #5 tasks: (10 11)
29877: TASK_RUNNER: engine (e2), batch #2 task #5 has TIMED OUT in (6.00) seconds !!
29877: TASK_ORCHESTRATOR: engine (e2) finished batch #2 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29877) has finished with status (0).
29872: MAIN: engine (e2) is RUNNING batch #6 tasks: (12)
30000: TASK_RUNNER: engine (e3) finished batch #4 task #8 in (5.28) seconds
30059: TASK_RUNNER: engine (e1) finished batch #5 task #10 in (3.02) seconds
30059: TASK_RUNNER: engine (e1) finished batch #5 task #11 in (3.58) seconds
30059: TASK_ORCHESTRATOR: engine (e1) finished batch #5 tasks in (3.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30059) has finished with status (0).
30000: TASK_RUNNER: engine (e3), batch #4 task #9 has TIMED OUT in (6.00) seconds !!
30000: TASK_ORCHESTRATOR: engine (e3) finished batch #4 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30000) has finished with status (0).
30129: TASK_RUNNER: engine (e2) finished batch #6 task #12 in (3.95) seconds
30129: TASK_ORCHESTRATOR: engine (e2) finished batch #6 tasks in (3.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30129) has finished with status (0).
29872: ALL ORCHESTRATORS HAVE FINISHED
29872: FINISHED TASKS IN BATCHES
</code>```

Program:

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;
use POSIX ':sys_wait_h';
use Thread qw(async);

STDOUT->autoflush(1);

my $timeout = 3;
my @total_tasks = (1 .. shift || 10);
my $sleep_time = 6;
my @engines = (qw/e1 e2 e3/);
my $sizes = { e1 => 2, e2 => 3, e3 => 2, };

my $proc_hash;
my $global_string = "engine";

###
# source: https://duyanghao.github.io/ways_avoid_zombie_process/
#
  sub REAPER {
    local ($!, $?);
    while ( (my $reaped_pid = waitpid(-1, WNOHANG)) > 0 ) {
      if ( WIFEXITED($?) )
      {
        my $ret_code = WEXITSTATUS($?);
        print "$$: REAPER: TASK_ORCHESTRATOR pid ($reaped_pid) has finished with status ($ret_code).\n";
        my $engine_name = $proc_hash->{$reaped_pid};
        delete ($proc_hash->{$reaped_pid});
        delete ($proc_hash->{$engine_name});
      }
    }
  }
#
###

$SIG{CHLD} = \&REAPER;

sub random_sleep_time { return sprintf ("%.2f",(rand ($sleep_time) + 1)) }

sub task_runner {
  my @args = @_;

  STDOUT->autoflush(1);
  my ($batch_engine, $task) = ($args[0]->[0],$args[0]->[1]);
  my ($batch, $engine) = split (/_/,$batch_engine);

  my $start_time = time;
  #my $end_time = undef;
  #my $tot_time = undef;

  $SIG{ALRM} = sub {
    my $end_time = time;
    my $tot_time = sprintf ("%.2f",($end_time - $start_time));
    print "$$: TASK_RUNNER: $global_string ($engine), batch #$batch".
          " task #$task has TIMED OUT in ($tot_time) seconds !!\n";
    threads->exit(0);
  };

  my $task_time = random_sleep_time();
  sleep ($task_time);
  #sleep (random_sleep_time());
  #$end_time = time;
  #$tot_time = sprintf ("%.2f",($end_time - $start_time));
  #print "$$: TASK_RUNNER: $global_string ($engine) finished batch #$batch task #$task in ($tot_time) seconds\n";
  print "$$: TASK_RUNNER: $global_string ($engine) finished batch #$batch task #$task in ($task_time) seconds\n";
  threads->exit(0);
};

sub task_orchestrator {
  my ($batch_engine, @tasks) = @_;
  my ($batch, $engine) = split (/_/,$batch_engine);
  my $task_orch_pid = fork();
  die "Failed to fork task_orchestrator\n" if not defined $task_orch_pid;

  if ($task_orch_pid != 0) {
    $proc_hash->{$engine} = $task_orch_pid;
    $proc_hash->{$task_orch_pid} = $engine;
  }

  if ($task_orch_pid == 0) {
    my @tids;
    alarm ($timeout);
    STDOUT->autoflush(1);
    my $start_time = time;
    for (my $i=1 ; $i <= $#tasks ; $i++) { push (@tids,$i) }
    foreach my $task_number (0 .. $#tasks) {
      $tids [$task_number] = threads->create (
        \&task_runner,[$batch_engine,$tasks [$task_number]]
      );
    }

    $SIG{ALRM} = sub {
      foreach my $t (@tids) {
        if ($t->is_running()) { $t->kill('ALRM') }
      }
    };

    foreach my $tid (@tids) {$tid->join()}
    my $end_time = time;
    my $tot_time = sprintf ("%.2f",($end_time - $start_time));
    print "$$: TASK_ORCHESTRATOR: engine ($engine) finished batch #$batch tasks in ($tot_time) seconds.\n";
    exit (0);
  }
}

my $batch=1;
print "$$: STARTING TASKS IN BATCHES\n";
while (@total_tasks)
{
  foreach my $engine (@engines)
  {
    if (exists $proc_hash->{$engine})
    {
      sleep (1);
      next;
    }
    else
    {
      my @engine_tasks;
      my $engine_max_tasks = $sizes->{$engine};
      while ($engine_max_tasks-- != 0)
      {
        my $task = shift @total_tasks;
        push (@engine_tasks,$task) if $task;
      }
      if (@engine_tasks)
      {
        my $batch_engine = $batch.'_'.$engine;
        print "$$: MAIN: engine ($engine) is RUNNING batch #$batch tasks: (@engine_tasks)\n";
        task_orchestrator ("$batch_engine",@engine_tasks);
        $batch++;
      }
    }
  }
}

# All Work fine
#sleep (.2) while ((waitpid(-1, WNOHANG)) >= 0);
#sleep (.2) while ((waitpid(-1, WNOHANG)) != -1);
sleep (.2) while ((waitpid(-1, WNOHANG)) > -1);
# All Work fine

print "$$: ALL ORCHESTRATORS HAVE FINISHED\n";
print "$$: FINISHED TASKS IN BATCHES\n";
__END__
</code>```

答:
The timing of alarm() is not guaranteed to have sub-second accuracy. The standard Time::HiRes module offers ualarm() and a re-implementation of alarm() in terms of ualarm() which may be closer to what you want. Solving your problem may be as simple as adding

```<code>use Time::HiRes qw(alarm);
</code>```

to the top of your program.

Body:
This question is an extension to my previous question.

The only addition here is that now I would like the threads to timeout if the operation is not complete within the set timeout duration.

So after going through the perldoc and certain examples, I have drafted a working version and it works - but there is something off.

The timeout doesn't exactly happen in the set duration but sometimes takes double  the amount of time.

I am not able to investigate this and I need you help on the same on how to investigate this further.

In this program, I have set the timeout value to 3 seconds via alarm function and have installed signal handler in the thread function.

My observations during the multiple runs are as follows:

timeout never happens below the set value.

timeout happens always above the set value and its value is never exactly the set value.

Please find the program output & the program itself for your review. Your comments and feedback are welcome.

Program output:

(20:51:59) $:little-stuff>  perl 10-20190530-batch-processing-using-threads-with-busy-pool-detection-2-with-threads-timeout.pl 12
29872: STARTING TASKS IN BATCHES
29872: MAIN: engine (e1) is RUNNING batch #1 tasks: (1 2)
29872: MAIN: engine (e2) is RUNNING batch #2 tasks: (3 4 5)
29872: MAIN: engine (e3) is RUNNING batch #3 tasks: (6 7)
29878: TASK_RUNNER: engine (e3) finished batch #3 task #7 in (1.27) seconds
29878: TASK_RUNNER: engine (e3) finished batch #3 task #6 in (2.12) seconds
29876: TASK_RUNNER: engine (e1) finished batch #1 task #1 in (2.97) seconds
29878: TASK_ORCHESTRATOR: engine (e3) finished batch #3 tasks in (2.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29878) has finished with status (0).
29877: TASK_RUNNER: engine (e2) finished batch #2 task #4 in (3.65) seconds
29877: TASK_RUNNER: engine (e2) finished batch #2 task #3 in (4.62) seconds
29872: MAIN: engine (e3) is RUNNING batch #4 tasks: (8 9)
29876: TASK_RUNNER: engine (e1) finished batch #1 task #2 in (6.43) seconds
29876: TASK_ORCHESTRATOR: engine (e1) finished batch #1 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29876) has finished with status (0).
29872: MAIN: engine (e1) is RUNNING batch #5 tasks: (10 11)
29877: TASK_RUNNER: engine (e2), batch #2 task #5 has TIMED OUT in (6.00) seconds !!
29877: TASK_ORCHESTRATOR: engine (e2) finished batch #2 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (29877) has finished with status (0).
29872: MAIN: engine (e2) is RUNNING batch #6 tasks: (12)
30000: TASK_RUNNER: engine (e3) finished batch #4 task #8 in (5.28) seconds
30059: TASK_RUNNER: engine (e1) finished batch #5 task #10 in (3.02) seconds
30059: TASK_RUNNER: engine (e1) finished batch #5 task #11 in (3.58) seconds
30059: TASK_ORCHESTRATOR: engine (e1) finished batch #5 tasks in (3.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30059) has finished with status (0).
30000: TASK_RUNNER: engine (e3), batch #4 task #9 has TIMED OUT in (6.00) seconds !!
30000: TASK_ORCHESTRATOR: engine (e3) finished batch #4 tasks in (6.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30000) has finished with status (0).
30129: TASK_RUNNER: engine (e2) finished batch #6 task #12 in (3.95) seconds
30129: TASK_ORCHESTRATOR: engine (e2) finished batch #6 tasks in (3.00) seconds.
29872: REAPER: TASK_ORCHESTRATOR pid (30129) has finished with status (0).
29872: ALL ORCHESTRATORS HAVE FINISHED
29872: FINISHED TASKS IN BATCHES

Program:

#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;
use POSIX ':sys_wait_h';
use Thread qw(async);

STDOUT->autoflush(1);

my $timeout = 3;
my @total_tasks = (1 .. shift || 10);
my $sleep_time = 6;
my @engines = (qw/e1 e2 e3/);
my $sizes = { e1 => 2, e2 => 3, e3 => 2, };

my $proc_hash;
my $global_string = "engine";

###
# source: https://duyanghao.github.io/ways_avoid_zombie_process/
#
  sub REAPER {
    local ($!, $?);
    while ( (my $reaped_pid = waitpid(-1, WNOHANG)) > 0 ) {
      if ( WIFEXITED($?) )
      {
        my $ret_code = WEXITSTATUS($?);
        print "$$: REAPER: TASK_ORCHESTRATOR pid ($reaped_pid) has finished with status ($ret_code).\n";
        my $engine_name = $proc_hash->{$reaped_pid};
        delete ($proc_hash->{$reaped_pid});
        delete ($proc_hash->{$engine_name});
      }
    }
  }
#
###

$SIG{CHLD} = \&REAPER;

sub random_sleep_time { return sprintf ("%.2f",(rand ($sleep_time) + 1)) }

sub task_runner {
  my @args = @_;

  STDOUT->autoflush(1);
  my ($batch_engine, $task) = ($args[0]->[0],$args[0]->[1]);
  my ($batch, $engine) = split (/_/,$batch_engine);

  my $start_time = time;
  #my $end_time = undef;
  #my $tot_time = undef;

  $SIG{ALRM} = sub {
    my $end_time = time;
    my $tot_time = sprintf ("%.2f",($end_time - $start_time));
    print "$$: TASK_RUNNER: $global_string ($engine), batch #$batch".
          " task #$task has TIMED OUT in ($tot_time) seconds !!\n";
    threads->exit(0);
  };

  my $task_time = random_sleep_time();
  sleep ($task_time);
  #sleep (random_sleep_time());
  #$end_time = time;
  #$tot_time = sprintf ("%.2f",($end_time - $start_time));
  #print "$$: TASK_RUNNER: $global_string ($engine) finished batch #$batch task #$task in ($tot_time) seconds\n";
  print "$$: TASK_RUNNER: $global_string ($engine) finished batch #$batch task #$task in ($task_time) seconds\n";
  threads->exit(0);
};

sub task_orchestrator {
  my ($batch_engine, @tasks) = @_;
  my ($batch, $engine) = split (/_/,$batch_engine);
  my $task_orch_pid = fork();
  die "Failed to fork task_orchestrator\n" if not defined $task_orch_pid;

  if ($task_orch_pid != 0) {
    $proc_hash->{$engine} = $task_orch_pid;
    $proc_hash->{$task_orch_pid} = $engine;
  }

  if ($task_orch_pid == 0) {
    my @tids;
    alarm ($timeout);
    STDOUT->autoflush(1);
    my $start_time = time;
    for (my $i=1 ; $i <= $#tasks ; $i++) { push (@tids,$i) }
    foreach my $task_number (0 .. $#tasks) {
      $tids [$task_number] = threads->create (
        \&task_runner,[$batch_engine,$tasks [$task_number]]
      );
    }

    $SIG{ALRM} = sub {
      foreach my $t (@tids) {
        if ($t->is_running()) { $t->kill('ALRM') }
      }
    };

    foreach my $tid (@tids) {$tid->join()}
    my $end_time = time;
    my $tot_time = sprintf ("%.2f",($end_time - $start_time));
    print "$$: TASK_ORCHESTRATOR: engine ($engine) finished batch #$batch tasks in ($tot_time) seconds.\n";
    exit (0);
  }
}

my $batch=1;
print "$$: STARTING TASKS IN BATCHES\n";
while (@total_tasks)
{
  foreach my $engine (@engines)
  {
    if (exists $proc_hash->{$engine})
    {
      sleep (1);
      next;
    }
    else
    {
      my @engine_tasks;
      my $engine_max_tasks = $sizes->{$engine};
      while ($engine_max_tasks-- != 0)
      {
        my $task = shift @total_tasks;
        push (@engine_tasks,$task) if $task;
      }
      if (@engine_tasks)
      {
        my $batch_engine = $batch.'_'.$engine;
        print "$$: MAIN: engine ($engine) is RUNNING batch #$batch tasks: (@engine_tasks)\n";
        task_orchestrator ("$batch_engine",@engine_tasks);
        $batch++;
      }
    }
  }
}

# All Work fine
#sleep (.2) while ((waitpid(-1, WNOHANG)) >= 0);
#sleep (.2) while ((waitpid(-1, WNOHANG)) != -1);
sleep (.2) while ((waitpid(-1, WNOHANG)) > -1);
# All Work fine

print "$$: ALL ORCHESTRATORS HAVE FINISHED\n";
print "$$: FINISHED TASKS IN BATCHES\n";
__END__

Body:
The timing of alarm() is not guaranteed to have sub-second accuracy. The standard Time::HiRes module offers ualarm() and a re-implementation of alarm() in terms of ualarm() which may be closer to what you want. Solving your problem may be as simple as adding

use Time::HiRes qw(alarm);

to the top of your program.


来源: stackexchange

问:
how can i format a datediff to show hh:mm
I am not sure how to format a datediff to show as hours and minutes. It show as eg. 7.78

```<code>=DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60
</code>```

I would like this to show as eg. hh:mm

答:
If you have no need to accommodate for anything over 24 hours this simple function will work.

```<code>=Format(DateAdd("n", DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value), "00:00:00"), "HH:mm")
</code>```

If you need to count anything over 24 hours then this will do the trick.

```<code>=
CStr(Int(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60)) +
":" +
Replace(CStr(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value) - Int(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60)*60), "0.", "")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am not sure how to format a datediff to show as hours and minutes. It show as eg. 7.78

=DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60

I would like this to show as eg. hh:mm

Body:
If you have no need to accommodate for anything over 24 hours this simple function will work.

=Format(DateAdd("n", DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value), "00:00:00"), "HH:mm")

If you need to count anything over 24 hours then this will do the trick.

=
CStr(Int(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60)) +
":" +
Replace(CStr(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value) - Int(DateDiff("n", Fields!StartOfDay.Value, Fields!EndOfDay.Value)/60)*60), "0.", "")


问:
Insert if not exists?
I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.

I make the call

```<code>mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);
</code>```

Which calls...

```<code>public long createNote(String value, String table) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(table, value);

        return mDb.insert(table, null, initialValues);
    }
</code>```

Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried

```<code>return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);
</code>```

However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...

How can I get this to work?

Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.

答: Add a Primary Key.  If you try to insert another row with the same key, the insert will fail.</p>

ContentLicense: CC BY-SA 3.0

Title: Insert if not exists?

Body:
I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.

I make the call

mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);

Which calls...

public long createNote(String value, String table) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(table, value);

        return mDb.insert(table, null, initialValues);
    }

Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried

return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);

However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...

How can I get this to work?

Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.


问:
Is set.seed consistent over different versions of R (and Ubuntu)?
I am currently running R version 3.1.0 (on Ubuntu 12.04 LTS) and as both my R version and my operating system is getting rather old, I plan on updating both. However, I have a lot of simulations that rely on set.seed() and I would like them to still give me the same random numbers after updating both R and my operating system.

So my question is three-fold.

Can I update R without changing which numbers are generated from each seed?

Can I do the same for my operating system?

If no to either 1) or 2), is there a way to change the seeds in my code in such a way that they are consistent with the olds seeds?

答:
Cross-OS consistency: yes

If you installed R on two different operating systems without manually changing defaults or the RProfile, you should get the same results when using set.seed().

Consistency over versions of R: not necessarily

It used to be the case that set.seed() would give the same results across R versions, but that's no longer generally true thanks to a little-announced update in R 3.6.0. So you can get cross version consistency comparing results before R 3.6.0, but if you compare a post-3.6.0 use of set.seed() to a pre-3.6.0 use of set.seed(), you will get different results.

You can see that in the examples below:

R 3.2.0

```<code>> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"
</code>```

R 3.5.3

```<code>> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"
</code>```

R 3.6.0

```<code>set.seed(1999)
sample(LETTERS, 3)
[1] "D" "Z" "R"
</code>```

The reason for the inconsistency is that in R 3.6.0, the default kind of under-the-hood random-number generator was changed. Now, in order to get the results from set.seed() to match, you have to first call the function RNGkind(sample.kind = "Rounding").

R 3.6.0

```<code>> RNGkind(sample.kind = "Rounding")
Warning message:
In RNGkind(sample.kind = "Rounding") : non-uniform 'Rounding' sampler used
> set.seed(1999)
> sample(Letters, 3)
[1] "T" "N" "L"
</code>```

Body:
Cross-OS consistency: yes

If you installed R on two different operating systems without manually changing defaults or the RProfile, you should get the same results when using set.seed().

Consistency over versions of R: not necessarily

It used to be the case that set.seed() would give the same results across R versions, but that's no longer generally true thanks to a little-announced update in R 3.6.0. So you can get cross version consistency comparing results before R 3.6.0, but if you compare a post-3.6.0 use of set.seed() to a pre-3.6.0 use of set.seed(), you will get different results.

You can see that in the examples below:

R 3.2.0

> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"

R 3.5.3

> set.seed(1999)
> sample(LETTERS, 3)
[1] "T" "N" "L"

R 3.6.0

set.seed(1999)
sample(LETTERS, 3)
[1] "D" "Z" "R"

The reason for the inconsistency is that in R 3.6.0, the default kind of under-the-hood random-number generator was changed. Now, in order to get the results from set.seed() to match, you have to first call the function RNGkind(sample.kind = "Rounding").

R 3.6.0

> RNGkind(sample.kind = "Rounding")
Warning message:
In RNGkind(sample.kind = "Rounding") : non-uniform 'Rounding' sampler used
> set.seed(1999)
> sample(Letters, 3)
[1] "T" "N" "L"


问:
Freezing bootstrap according while creating from AJAX
Actually in my website i populate bootstrap according dynamically when an according is opened, once it has been open the data is saved.

The issue is that when i open the according for first time it's freezing (as it have to append a lot of divs) and that trigger me a lot, so i would know how should i make it more performable or like which approach should i take to prevent that freezing.

The AJAX method is build as the following:

```<code>function getBody(body, key) {

    $.ajax({
        type: "POST",
        url: "casse.aspx/getBody",
        data: JSON.stringify({ key: key }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {

            data = r.d;
            data = $.parseJSON(data);

            $.each(data, function (i, item) {

                var piva = item.piva;
                var desmag = item.desmag;
                var via = item.via;
                var loc = item.loc;
                var servb2b = item.servb2b;
                var idtrabb2b = item.idtrabb2b;
                var matricola = item.matricola;
                var azzer = item.azzer;
                var mac = item.mac;
                var vp = item.vp;
                var vb = item.vb;
                var dr = item.dr;
                var vu = item.vu;
                var cpu = item.cpu;
                var rt = item.giart;
                var datart = item.avviort;

                var card = "";

                card += '<div class="row ml-2 mr-2">';
                card += '<div class="col">';
                card += '<div class="row"><span class="badge badge-primary">Cliente</span></div>';
                card += '<div class="row"><small class="text-muted">P.Iva</small></div>';
                card += '<div class="row"><p class="info">' + piva + '</p></div>';
                card += '<div class="row"><small class="text-muted">Info Negozio</small></div>';
                card += '<div class="row"><p class="info">' + desmag + '</p></div>';
                card += '<div class="row"><small class="text-muted">Via</small></div>';
                card += '<div class="row"><p class="info">' + via + '</p></div>';
                card += '<div class="row"><small class="text-muted">Localita</small></div>';
                card += '<div class="row"><p class="info">' + loc + '</p></div></div>';

                card += '<div class="col">';
                card += '<div class="row"><span class="badge badge-primary">Software</span></div>';
                card += '<div class="row"><small class="text-muted">VisualPos</small></div>';
                card += '<div class="row"><a href="#" class="badge badge-warning">' + vp + '</a></div>';
                card += '<div class="row"><small class="text-muted">VisualB2B</small></div>';
                card += '<div class="row"><a href="#" class="badge badge-warning">' + vb + '</a></div>';
                card += '<div class="row"><small class="text-muted">Driver</small></div>';
                card += '<div class="row"><a href="#" class="badge badge-warning">' + dr + '</a></div>';
                card += '<div class="row"><small class="text-muted">VisualUpdate</small></div>';
                card += '<div class="row"><p class="info">' + vu + '</p></div></div>';

                card += '<div class="col">';
                card += '<div class="row"><span class="badge badge-primary">Fiscale</span></div>';
                card += '<div class="row"><small class="text-muted">Matricola</small></div>';
                card += '<div class="row"><p class="info">' + matricola + '</p></div>';
                card += '<div class="row"><small class="text-muted">Azzeramento Fiscale</small></div>';
                card += '<div class="row"><p class="info">' + azzer + '</p></div>';
                card += '<div class="row"><small class="text-muted">RT</small></div>';
                card += '<div class="row"><p class="info">' + rt + '</p></div>';
                card += '<div class="row"><small class="text-muted">Data Avvio RT</small></div>';
                card += '<div class="row"><p class="info">' + datart + '</p></div></div>';

                card += '<div class="col">';
                card += '<div class="row"><span class="badge badge-primary">Fatturazione Elettronica</span></div>';
                card += '<div class="row"><small class="text-muted">Servizio B2B</small></div>';
                card += '<div class="row"><p class="info">' + servb2b + '</p></div>';
                card += '<div class="row"><small class="text-muted">Trasmittente B2B</small></div>';
                card += '<div class="row"><p class="info">' + idtrabb2b + '</p></div></div>';

                card += '<div class="col">';
                card += '<div class="row"><span class="badge badge-primary">Hardware</span></div>';
                card += '<div class="row"><small class="text-muted">CPU</small></div>';
                card += '<div class="row"><p class="info">' + cpu + '</p></div>';
                card += '<div class="row"><small class="text-muted">MAC</small></div>';
                card += '<div class="row"><p class="info">' + mac + '</p></div></div></div>';

                $(body).find('.card-body').append(card);
            });

        },
        error: function (error) {
            OnFailure(error);
            alert('Error');
        }
    });
}
</code>```

And called when the according is triggered

```<code>$('.accordion').on('show.bs.collapse', function (e) {
    var id = $(e.target).attr('id');
    var item = '#' + $(e.target).attr('id');
    if ($(item).find('.card-body').is(':empty')) {
        getBody(item, id);
    } else {

    }

});
</code>```

答:
You are going to need to manually trigger the toggle after the data has finished loading, and after you have put your data into the DOM.  That means you need to remove the data-target value from your Collapse and manually add the event listener/handler.  I wish that there was a pre/post collapse aspect that you could hook to, but there isn't.

Consider the example below that doesn't have the lag you experience.

$("#test-button").click(e => {
  $.ajax({
     url: "https://jsonplaceholder.typicode.com/todos",
     dataType: "json"
  }).done(d => {
    $("#collapseOne .card-body").text(JSON.stringify(d
, null, 4));
    $("#collapseOne").collapse("toggle");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button id="test-button" class="btn btn-link" type="button" data-toggle="collapse" aria-expanded="false" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body"></div>
    </div>
  </div>
</div></code>```

Body:
Actually in my website i populate bootstrap according dynamically when an according is opened, once it has been open the data is saved.

The issue is that when i open the according for first time it's freezing (as it have to append a lot of divs) and that trigger me a lot, so i would know how should i make it more performable or like which approach should i take to prevent that freezing.

The AJAX method is build as the following:

function getBody(body, key) {

    $.ajax({
        type: "POST",
        url: "casse.aspx/getBody",
        data: JSON.stringify({ key: key }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {

            data = r.d;
            data = $.parseJSON(data);

            $.each(data, function (i, item) {

                var piva = item.piva;
                var desmag = item.desmag;
                var via = item.via;
                var loc = item.loc;
                var servb2b = item.servb2b;
                var idtrabb2b = item.idtrabb2b;
                var matricola = item.matricola;
                var azzer = item.azzer;
                var mac = item.mac;
                var vp = item.vp;
                var vb = item.vb;
                var dr = item.dr;
                var vu = item.vu;
                var cpu = item.cpu;
                var rt = item.giart;
                var datart = item.avviort;

                var card = "";

                card += '
';
                card += '
';
                card += '
Cliente
';
                card += '
P.Iva
';
                card += '

' + piva + '

';
                card += '
Info Negozio
';
                card += '

' + desmag + '

';
                card += '
Via
';
                card += '

' + via + '

';
                card += '
Localita
';
                card += '

' + loc + '

';

                card += '
';
                card += '
Software
';
                card += '
VisualPos
';
                card += '
' + vp + '
';
                card += '
VisualB2B
';
                card += '
' + vb + '
';
                card += '
Driver
';
                card += '
' + dr + '
';
                card += '
VisualUpdate
';
                card += '

' + vu + '

';

                card += '
';
                card += '
Fiscale
';
                card += '
Matricola
';
                card += '

' + matricola + '

';
                card += '
Azzeramento Fiscale
';
                card += '

' + azzer + '

';
                card += '
RT
';
                card += '

' + rt + '

';
                card += '
Data Avvio RT
';
                card += '

' + datart + '

';

                card += '
';
                card += '
Fatturazione Elettronica
';
                card += '
Servizio B2B
';
                card += '

' + servb2b + '

';
                card += '
Trasmittente B2B
';
                card += '

' + idtrabb2b + '

';

                card += '
';
                card += '
Hardware
';
                card += '
CPU
';
                card += '

' + cpu + '

';
                card += '
MAC
';
                card += '

' + mac + '

';

                $(body).find('.card-body').append(card);
            });

        },
        error: function (error) {
            OnFailure(error);
            alert('Error');
        }
    });
}

And called when the according is triggered

$('.accordion').on('show.bs.collapse', function (e) {
    var id = $(e.target).attr('id');
    var item = '#' + $(e.target).attr('id');
    if ($(item).find('.card-body').is(':empty')) {
        getBody(item, id);
    } else {

    }

});

Body:
You are going to need to manually trigger the toggle after the data has finished loading, and after you have put your data into the DOM.  That means you need to remove the data-target value from your Collapse and manually add the event listener/handler.  I wish that there was a pre/post collapse aspect that you could hook to, but there isn't.

Consider the example below that doesn't have the lag you experience.

$("#test-button").click(e => {
  $.ajax({
     url: "https://jsonplaceholder.typicode.com/todos",
     dataType: "json"
  }).done(d => {
    $("#collapseOne .card-body").text(JSON.stringify(d
, null, 4));
    $("#collapseOne").collapse("toggle");
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button id="test-button" class="btn btn-link" type="button" data-toggle="collapse" aria-expanded="false" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body"></div>
    </div>
  </div>
</div>


问:
Combining extension and custom class on UIButton creates issues
I have a class and an extension for UIButton. A custom class removing the title and displaying a loading indicator on click (LoadingButton). - An extension declaring a custom function to apply a gradient to the button etc.

Both are working, but calling the function typeMain() on a button of class LoadingButton involves an issue - the title of the button isn't getting removed, hence the loading button is being displayed on top of the title.

How can I combine both solving this issue?

Btw.: button.typeMain() is being called in viewDidLoad().

LoadingButton:

```<code>class LoadingButton: UIButton {
var originalButtonText: String?
var activityIndicator: UIActivityIndicatorView!

func showLoading() {
    originalButtonText = self.titleLabel?.text
    self.setTitle("", for: .normal)

    if (activityIndicator == nil) {
        activityIndicator = createActivityIndicator()
    }

    showSpinning()
}

func hideLoading() {
    self.setTitle(originalButtonText, for: .normal)
    activityIndicator.stopAnimating()
}

private func createActivityIndicator() -> UIActivityIndicatorView {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    return activityIndicator
}

private func showSpinning() {
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(activityIndicator)
    centerActivityIndicatorInButton()
    activityIndicator.startAnimating()
}

private func centerActivityIndicatorInButton() {
    let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0)
    self.addConstraint(xCenterConstraint)

    let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0)
    self.addConstraint(yCenterConstraint)
}
</code>```

Extension to customize every button:

```<code>extension UIButton {

func typeMain() {
    self.translatesAutoresizingMaskIntoConstraints = false
    let height = UIScreen.main.bounds.height * 0.07
    let width = UIScreen.main.bounds.width * 0.9
    self.heightAnchor.constraint(equalToConstant: height).isActive = true
    self.widthAnchor.constraint(equalToConstant: width).isActive = true

    layoutIfNeeded()

    self.addCharacterSpacing()
    self.tintColor = UIColor.white
    let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1)
    let sndColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1)

    self.layer.cornerRadius = self.frame.size.height / 5.0

    self.applyGradient(colours: [color, sndColor], locations: [0.0, 1.0])

    let shadowSize : CGFloat = 2.0
    self.layer.shadowColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1).cgColor
    self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    self.layer.shadowOpacity = 0.4
    let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                               y: shadowSize,
                                               width: self.frame.size.width + shadowSize,
                                               height: self.frame.size.height + shadowSize))
    self.layer.shadowPath = shadowPath.cgPath
    self.layer.shadowRadius = 5
    self.layer.masksToBounds = false
}
</code>```

CharacterSpacing

```<code>extension UILabel {
func addCharacterSpacing(kernValue: Double = 0.5) {
    if let labelText = text, labelText.count > 0 {
        let attributedString = NSMutableAttributedString(string: labelText)
        attributedString.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
        attributedText = attributedString
    }
}
</code>```

答:
Your custom class uses button title and the extension method uses button attributedTitle. Update your custom class to keep a reference to attributedTitle</p>

```<code>class LoadingButton: UIButton {
    var originalButtonText: String?
    var attributedButtonText: NSAttributedString?
    var activityIndicator: UIActivityIndicatorView!

    func showLoading() {
        originalButtonText = self.titleLabel?.text
        attributedButtonText = self.attributedTitle(for: .normal)
        self.setTitle("", for: .normal)
        self.setAttributedTitle(NSAttributedString(string: ""), for: .normal)

        if (activityIndicator == nil) {
            activityIndicator = createActivityIndicator()
        }
        showSpinning()
    }
    func hideLoading() {
        self.setAttributedTitle(attributedButtonText, for: .normal)
        self.setTitle(originalButtonText, for: .normal)
        activityIndicator.stopAnimating()
    }
}
</code>```

Body:
I have a class and an extension for UIButton. A custom class removing the title and displaying a loading indicator on click (LoadingButton). - An extension declaring a custom function to apply a gradient to the button etc.

Both are working, but calling the function typeMain() on a button of class LoadingButton involves an issue - the title of the button isn't getting removed, hence the loading button is being displayed on top of the title.

How can I combine both solving this issue?

Btw.: button.typeMain() is being called in viewDidLoad().

LoadingButton:

class LoadingButton: UIButton {
var originalButtonText: String?
var activityIndicator: UIActivityIndicatorView!

func showLoading() {
    originalButtonText = self.titleLabel?.text
    self.setTitle("", for: .normal)

    if (activityIndicator == nil) {
        activityIndicator = createActivityIndicator()
    }

    showSpinning()
}

func hideLoading() {
    self.setTitle(originalButtonText, for: .normal)
    activityIndicator.stopAnimating()
}

private func createActivityIndicator() -> UIActivityIndicatorView {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    return activityIndicator
}

private func showSpinning() {
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(activityIndicator)
    centerActivityIndicatorInButton()
    activityIndicator.startAnimating()
}

private func centerActivityIndicatorInButton() {
    let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0)
    self.addConstraint(xCenterConstraint)

    let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0)
    self.addConstraint(yCenterConstraint)
}

Extension to customize every button:

extension UIButton {

func typeMain() {
    self.translatesAutoresizingMaskIntoConstraints = false
    let height = UIScreen.main.bounds.height * 0.07
    let width = UIScreen.main.bounds.width * 0.9
    self.heightAnchor.constraint(equalToConstant: height).isActive = true
    self.widthAnchor.constraint(equalToConstant: width).isActive = true

    layoutIfNeeded()

    self.addCharacterSpacing()
    self.tintColor = UIColor.white
    let color = UIColor(red: 11/255, green: 95/255, blue: 244/255, alpha: 1)
    let sndColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1)

    self.layer.cornerRadius = self.frame.size.height / 5.0

    self.applyGradient(colours: [color, sndColor], locations: [0.0, 1.0])

    let shadowSize : CGFloat = 2.0
    self.layer.shadowColor = UIColor(red: 106/255, green: 178/255, blue: 255/255, alpha: 1).cgColor
    self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    self.layer.shadowOpacity = 0.4
    let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                               y: shadowSize,
                                               width: self.frame.size.width + shadowSize,
                                               height: self.frame.size.height + shadowSize))
    self.layer.shadowPath = shadowPath.cgPath
    self.layer.shadowRadius = 5
    self.layer.masksToBounds = false
}

CharacterSpacing

extension UILabel {
func addCharacterSpacing(kernValue: Double = 0.5) {
    if let labelText = text, labelText.count > 0 {
        let attributedString = NSMutableAttributedString(string: labelText)
        attributedString.addAttribute(NSAttributedString.Key.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
        attributedText = attributedString
    }
}

Body:
Your custom class uses button title and the extension method uses button attributedTitle. Update your custom class to keep a reference to attributedTitle

class LoadingButton: UIButton {
    var originalButtonText: String?
    var attributedButtonText: NSAttributedString?
    var activityIndicator: UIActivityIndicatorView!

    func showLoading() {
        originalButtonText = self.titleLabel?.text
        attributedButtonText = self.attributedTitle(for: .normal)
        self.setTitle("", for: .normal)
        self.setAttributedTitle(NSAttributedString(string: ""), for: .normal)

        if (activityIndicator == nil) {
            activityIndicator = createActivityIndicator()
        }
        showSpinning()
    }
    func hideLoading() {
        self.setAttributedTitle(attributedButtonText, for: .normal)
        self.setTitle(originalButtonText, for: .normal)
        activityIndicator.stopAnimating()
    }
}


问:
Django form missing a field
I have a model and a modelform to change some settings. The form is displayed allright, with the correct values, but when I submit the form one field is missing in the request.POST dict.

The model:

```<code>class NodeSettings(models.Model):
    nodetype = models.CharField(max_length=8, editable=False)
    nodeserial = models.IntegerField(editable=False)
    upper_limit = models.FloatField(null=True, blank=True,
                                    help_text="Values above this limit will be of different color.")
    graph_time = models.IntegerField(null=True, blank=True,
                                     help_text="The `width' of the graph, in minutes.")
    tick_time = models.IntegerField(null=True, blank=True,
                                    help_text="Number of minutes between `ticks' in the graph.")
    graph_height = models.IntegerField(null=True, blank=True,
                                       help_text="The top value of the graphs Y-axis.")

    class Meta:
        unique_together = ("nodetype", "nodeserial")
</code>```

The view class (I'm using Django 1.3 with class-based views):

```<code>class EditNodeView(TemplateView):
    template_name = 'live/editnode.html'

    class NodeSettingsForm(forms.ModelForm):
        class Meta:
            model = NodeSettings

    # Some stuff cut out

    def post(self, request, *args, **kwargs):
        nodetype = request.POST['nodetype']
        nodeserial = request.POST['nodeserial']

        # 'logger' is a Django logger instance defined in the settings
        logger.debug('nodetype   = %r' % nodetype)
        logger.debug('nodeserial = %r' % nodeserial)

        try:
            instance = NodeSettings.objects.get(nodetype=nodetype, nodeserial=nodeserial)
            logger.debug('have existing instance')
        except NodeSettings.DoesNotExist:
            instance = NodeSettings(nodetype=nodetype, nodeserial=nodeserial)
            logger.debug('creating new instance')

        logger.debug('instance.tick_time = %r' % instance.tick_time)

        try:
            logger.debug('POST[tick_time] = %r' % request.POST['tick_time'])
        except Exception, e:
            logger.debug('error: %r' % e)

        form = EditNodeView.NodeSettingsForm(request.POST, instance=instance)
        if form.is_valid():
            from django.http import HttpResponse
            form.save()
            return HttpResponse()
        else:
            return super(EditNodeView, self).get(request, *args, **kwargs)
</code>```

The relevant portion of the template:

```<code><form action="{{ url }}edit_node/" method="POST">
  {% csrf_token %}
  <table>
    {{ form.as_table }}
  </table>
  <input type="submit" value="Ok" />
</form>
</code>```

Here is the debug output in the console when running the debug server:

```<code>2011-04-12 16:18:05,972 DEBUG nodetype   = u'V10'
2011-04-12 16:18:05,972 DEBUG nodeserial = u'4711'
2011-04-12 16:18:06,038 DEBUG have existing instance
2011-04-12 16:18:06,038 DEBUG instance.tick_time = 5
2011-04-12 16:18:06,039 DEBUG error: MultiValueDictKeyError("Key 'tick_time' not found in <QueryDict: {u'nodetype': [u'V10'], u'graph_time': [u'5'], u'upper_limit': [u''], u'nodeserial': [u'4711'], u'csrfmiddlewaretoken': [u'fb11c9660ed5f51bcf0fa39f71e01c92'], u'graph_height': [u'25']}>",)
</code>```

As you can see, the field tick_time is nowhere in the QueryDict from request.POST.

It should be noted that the field is in the web-browser, and when looking at the HTML source it looks just like the other fields in the form.

Anyone have any hints on what can be wrong?

答:
Since you are using generic view, isn't it best to extend ProcessFormView instead of TemplateView?

EDIT

I've tried your code with TemplateView:

```<code>class EditNodeView(TemplateView):
</code>```

Do you have a get_context_data to push the form?

```<code>def get_context_data(self, **kwargs):
    instance = NodeSettings.objects.get(pk=kwargs['node_id'])
    form = EditNodeView.NodeSettingsForm(instance=instance)
    context = super(EditNodeView, self).get_context_data(**kwargs)
    context['form'] = form
    return context
</code>```

The best way for editing existing objects is to get by primary key, I have the following in the urls.py:

```<code>url(r'^edit-node/(?P<node_id>\d+)/$', EditNodeView.as_view(), name='edit-node'),
</code>```

I fetch the instance by primary key, might want to do some checking above like throwing 404 if not present.

In your models, you have nodetype and nodeserial as editable=False, how do you display or create those items if they are set to not editable?  I've set them to True for testing purposes.

In the template, I have changed the first line to:

```<code><form action="" method="POST">
</code>```

I'm aware that there are a lot of changes but the above can view and edit your model properly.  You could set the nodetype and nodeserial to be read-only at the form level to prevent people from editing it.

Title: Django form missing a field

Body:
I have a model and a modelform to change some settings. The form is displayed allright, with the correct values, but when I submit the form one field is missing in the request.POST dict.

The model:

class NodeSettings(models.Model):
    nodetype = models.CharField(max_length=8, editable=False)
    nodeserial = models.IntegerField(editable=False)
    upper_limit = models.FloatField(null=True, blank=True,
                                    help_text="Values above this limit will be of different color.")
    graph_time = models.IntegerField(null=True, blank=True,
                                     help_text="The `width' of the graph, in minutes.")
    tick_time = models.IntegerField(null=True, blank=True,
                                    help_text="Number of minutes between `ticks' in the graph.")
    graph_height = models.IntegerField(null=True, blank=True,
                                       help_text="The top value of the graphs Y-axis.")

    class Meta:
        unique_together = ("nodetype", "nodeserial")

The view class (I'm using Django 1.3 with class-based views):

class EditNodeView(TemplateView):
    template_name = 'live/editnode.html'

    class NodeSettingsForm(forms.ModelForm):
        class Meta:
            model = NodeSettings

    # Some stuff cut out

    def post(self, request, *args, **kwargs):
        nodetype = request.POST['nodetype']
        nodeserial = request.POST['nodeserial']

        # 'logger' is a Django logger instance defined in the settings
        logger.debug('nodetype   = %r' % nodetype)
        logger.debug('nodeserial = %r' % nodeserial)

        try:
            instance = NodeSettings.objects.get(nodetype=nodetype, nodeserial=nodeserial)
            logger.debug('have existing instance')
        except NodeSettings.DoesNotExist:
            instance = NodeSettings(nodetype=nodetype, nodeserial=nodeserial)
            logger.debug('creating new instance')

        logger.debug('instance.tick_time = %r' % instance.tick_time)

        try:
            logger.debug('POST[tick_time] = %r' % request.POST['tick_time'])
        except Exception, e:
            logger.debug('error: %r' % e)

        form = EditNodeView.NodeSettingsForm(request.POST, instance=instance)
        if form.is_valid():
            from django.http import HttpResponse
            form.save()
            return HttpResponse()
        else:
            return super(EditNodeView, self).get(request, *args, **kwargs)

The relevant portion of the template:

<form action="{{ url }}edit_node/" method="POST">
  {% csrf_token %}

    {{ form.as_table }}

  <input type="submit" value="Ok" />
</form>

Here is the debug output in the console when running the debug server:

2011-04-12 16:18:05,972 DEBUG nodetype   = u'V10'
2011-04-12 16:18:05,972 DEBUG nodeserial = u'4711'
2011-04-12 16:18:06,038 DEBUG have existing instance
2011-04-12 16:18:06,038 DEBUG instance.tick_time = 5
2011-04-12 16:18:06,039 DEBUG error: MultiValueDictKeyError("Key 'tick_time' not found in <QueryDict: {u'nodetype': [u'V10'], u'graph_time': [u'5'], u'upper_limit': [u''], u'nodeserial': [u'4711'], u'csrfmiddlewaretoken': [u'fb11c9660ed5f51bcf0fa39f71e01c92'], u'graph_height': [u'25']}>",)

As you can see, the field tick_time is nowhere in the QueryDict from request.POST.

It should be noted that the field is in the web-browser, and when looking at the HTML source it looks just like the other fields in the form.

Anyone have any hints on what can be wrong?

Body:
Since you are using generic view, isn't it best to extend ProcessFormView instead of TemplateView?

EDIT

I've tried your code with TemplateView:

class EditNodeView(TemplateView):

Do you have a get_context_data to push the form?

def get_context_data(self, **kwargs):
    instance = NodeSettings.objects.get(pk=kwargs['node_id'])
    form = EditNodeView.NodeSettingsForm(instance=instance)
    context = super(EditNodeView, self).get_context_data(**kwargs)
    context['form'] = form
    return context

The best way for editing existing objects is to get by primary key, I have the following in the urls.py:

url(r'^edit-node/(?P<node_id>\d+)/$', EditNodeView.as_view(), name='edit-node'),

I fetch the instance by primary key, might want to do some checking above like throwing 404 if not present.

In your models, you have nodetype and nodeserial as editable=False, how do you display or create those items if they are set to not editable?  I've set them to True for testing purposes.

In the template, I have changed the first line to:

<form action="" method="POST">

I'm aware that there are a lot of changes but the above can view and edit your model properly.  You could set the nodetype and nodeserial to be read-only at the form level to prevent people from editing it.


问:
Change colour of jitter points according to facet_wrap
I want to compare the number of different coloured flowers (red and green) at two different sites. I have a boxplot in ggplot2 with a jitter plot in the background. I want the colour of the jitter points to be different according to the colour of the flowers. Not sure how to do this! Is there a way to colour code my facets depending on the colour of the flower?

Some sample data:

```<code>site <- c(rep(1, 4), rep(2, 4))

colour <- c("red", "green", "red", "green", "red", "green", "red", "green")
number <- c(12, 24, 22, 14, 12, 16, 18, 17)

df <- data.frame(site, colour, number)
df$site <- as.factor(df$site)

ggplot(df, aes(site, number))+
  facet_wrap("colour")+
  geom_jitter(alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black")+
  theme(legend.position = "none")
</code>```

答:
Map color to your column name. If you want the color to be interpreted literally use an identity scale:</p>

```<code>ggplot(df, aes(site, number))+
  facet_wrap(colour)+
  geom_jitter(aes(colour = colour), alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black") +
  scale_color_identity() +
  theme(legend.position = "none")
</code>```

Body:
I want to compare the number of different coloured flowers (red and green) at two different sites. I have a boxplot in ggplot2 with a jitter plot in the background. I want the colour of the jitter points to be different according to the colour of the flowers. Not sure how to do this! Is there a way to colour code my facets depending on the colour of the flower?

Some sample data:

site <- c(rep(1, 4), rep(2, 4))

colour <- c("red", "green", "red", "green", "red", "green", "red", "green")
number <- c(12, 24, 22, 14, 12, 16, 18, 17)

df <- data.frame(site, colour, number)
df$site <- as.factor(df$site)

ggplot(df, aes(site, number))+
  facet_wrap("colour")+
  geom_jitter(alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black")+
  theme(legend.position = "none")

Body:
Map color to your column name. If you want the color to be interpreted literally use an identity scale:

ggplot(df, aes(site, number))+
  facet_wrap(colour)+
  geom_jitter(aes(colour = colour), alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black") +
  scale_color_identity() +
  theme(legend.position = "none")


问:
SSIS deployment very slow in Visual Studio 2015
My team shares a SSIS Visual Studio 2015 Project (via GIT, I know it's not ideal), any everytime I deploy this project to the SQL Server SSIS Catalog, it takes 20 minutes or more, from the third step ("changing protection level").

I've asked my colleague to try the same thing, under the same conditions. We are on the same network, using the same Visual Studio version, deploying to the same server and using the same git commit. In her case, the deployment finishes very quickly in a matter of seconds.

Mostly i'm the one who performs changes in this project and a few months ago my deployments were also super fast. It feels like I'm "cluttering" my Visual Studio environment,  but I don't know how or why.

Can I get a few hints?

答: I ended up reinstalling Visual Studio 2015 and that did the trick.</p>


问:
Bokeh: trigger callback if another callback is triggered
I am trying to make a basic search tool for my Bokeh application. The basic process is:

A user enters a search term into a TextInput widget.

The TextInput value is passed to a search function and that returns a list of (tuples) options for a MultiSelect widget.

I run my app using a local server:

```<code>bokeh serve --show my_app
</code>```

I cant get my MultiSelect options to update via a callback.

```<code>def createtab_search():

    # callback text_input
    def callback_text_input(attr, old, new):
        print("Previous label: " + old)
        print("Updated label: " + new)

    text_input = TextInput(value="search here", title="Search:")
    text_input.on_change("value", callback_text_input)

    # callback search results
    def callback_search_result(attr,old,new):
        search_results = search_function(text_input.value)
        options = [(k,k) for k in search_results.items()]
        multi_select.options = options

    # results dropdown
    multi_select = MultiSelect(title="Results:",
                           value=[],
                           options=[])
    multi_select.on_change("options",callback_search_result)

    # Layout setup
    layout = column(text_input,multi_select)

    #output tab
    tab = Panel(child = layout, title = 'Search')
    return tab
</code>```

答:
I solved this by calling the 2nd callback from within the first. So whenever I update the search term in TextInput, the search function is called and the MultiSelect widget options are re-populated.

```<code>def createtab_search():

    # callback text_input
    def callback_text_input(attr, old, new):
        callback_search_result(attr, old, new)

    text_input = TextInput(value="search here", title="Search:")
    text_input.on_change("value", callback_text_input)

    # callback search results
    def callback_search_result(attr,old,new):
        search_results = search_function(text_input.value)
        options = [(k,k) for k in search_results.items()]
        multi_select.options = options

    # results dropdown
    multi_select = MultiSelect(title="Results:",
                           value=[],
                           options=[])
    multi_select.on_change("options",callback_search_result)

    # Layout setup
    layout = column(text_input,multi_select)

    #output tab
    tab = Panel(child = layout, title = 'Search')
    return tab
</code>```

Body:
I am trying to make a basic search tool for my Bokeh application. The basic process is:

A user enters a search term into a TextInput widget.

The TextInput value is passed to a search function and that returns a list of (tuples) options for a MultiSelect widget.

I run my app using a local server:

bokeh serve --show my_app

I cant get my MultiSelect options to update via a callback.

def createtab_search():

    # callback text_input
    def callback_text_input(attr, old, new):
        print("Previous label: " + old)
        print("Updated label: " + new)

    text_input = TextInput(value="search here", title="Search:")
    text_input.on_change("value", callback_text_input)

    # callback search results
    def callback_search_result(attr,old,new):
        search_results = search_function(text_input.value)
        options = [(k,k) for k in search_results.items()]
        multi_select.options = options

    # results dropdown
    multi_select = MultiSelect(title="Results:",
                           value=[],
                           options=[])
    multi_select.on_change("options",callback_search_result)

    # Layout setup
    layout = column(text_input,multi_select)

    #output tab
    tab = Panel(child = layout, title = 'Search')
    return tab

Body:
I solved this by calling the 2nd callback from within the first. So whenever I update the search term in TextInput, the search function is called and the MultiSelect widget options are re-populated.

def createtab_search():

    # callback text_input
    def callback_text_input(attr, old, new):
        callback_search_result(attr, old, new)

    text_input = TextInput(value="search here", title="Search:")
    text_input.on_change("value", callback_text_input)

    # callback search results
    def callback_search_result(attr,old,new):
        search_results = search_function(text_input.value)
        options = [(k,k) for k in search_results.items()]
        multi_select.options = options

    # results dropdown
    multi_select = MultiSelect(title="Results:",
                           value=[],
                           options=[])
    multi_select.on_change("options",callback_search_result)

    # Layout setup
    layout = column(text_input,multi_select)

    #output tab
    tab = Panel(child = layout, title = 'Search')
    return tab


问:
How to use a function as a property of an object inside another function in javascript
I'm trying to create a function that will take object as a parameter and inside the object I want to have an object method just same way jQuery ajax works. My problem now is that I can't get that object method to work.

function myAjax({
  type,
  url,
  success
}) {
  var suc = "";
  typeof type === "undefined" ? type = "GET" : type = type;

  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      suc = this.responseText;
      //alert(this.responseText);
    }
  };
  req.open(type, url, false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded ");
  req.send("fname=chijioke&lname=francis");

  function success(suc) {}
  }

  myAjax({
    type: "post",
    url: "page.html",
    success: function(e) {
      alert(e);
    }
  });
```

<p>I want to do something similar to this jQuery ajax call</p>

<pre class="lang-js prettyprint-override"><code>$.ajax({
  type: "post",
  url: "index",
  data: {
    id: id
  },
  success: function(feedback) {
    alert(feedback);
  }
});
</code>```

I need to get the responseText through the success function but it is not working. I want this to work like that of jQuery ajax success, this is really for learning purpose.

答:
what you are trying to do is actually pretty common - callback functions. You pass a function as a parameter and simply call it inside.

In your implementation, you are doing

```<code>function success(suc){}
</code>```

This is actually just defining a method called success.. you need to do actually call the method like this

```<code>success(suc);
</code>```

Also, your line where you check to see if the type is undefined won't typically evaluate to true, as you should be checking if

```<code>type === undefined //"undefined" != undefined
</code>```

One more thing I would like to mention is that you are attempting to call the callback function at the end of your method, but you should actually be calling it in the onreadystatechange so that way it's being called when the request is completed, not when the method is completed.

```<code>    req.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
            suc = this.responseText;
            success(suc);
        }
    };
</code>```

Body:
I'm trying to create a function that will take object as a parameter and inside the object I want to have an object method just same way jQuery ajax works. My problem now is that I can't get that object method to work.

function myAjax({
  type,
  url,
  success
}) {
  var suc = "";
  typeof type === "undefined" ? type = "GET" : type = type;

  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      suc = this.responseText;
      //alert(this.responseText);
    }
  };
  req.open(type, url, false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded ");
  req.send("fname=chijioke&lname=francis");

  function success(suc) {}
  }

  myAjax({
    type: "post",
    url: "page.html",
    success: function(e) {
      alert(e);
    }
  });

I want to do something similar to this jQuery ajax call

$.ajax({
  type: "post",
  url: "index",
  data: {
    id: id
  },
  success: function(feedback) {
    alert(feedback);
  }
});

I need to get the responseText through the success function but it is not working. I want this to work like that of jQuery ajax success, this is really for learning purpose.

Body:
what you are trying to do is actually pretty common - callback functions. You pass a function as a parameter and simply call it inside.

In your implementation, you are doing

function success(suc){}

This is actually just defining a method called success.. you need to do actually call the method like this

success(suc);

Also, your line where you check to see if the type is undefined won't typically evaluate to true, as you should be checking if

type === undefined //"undefined" != undefined

One more thing I would like to mention is that you are attempting to call the callback function at the end of your method, but you should actually be calling it in the onreadystatechange so that way it's being called when the request is completed, not when the method is completed.

    req.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
            suc = this.responseText;
            success(suc);
        }
    };


问:
When a page delivers secure and non-secure items over https, are the secure items compromised?
I'm not 100% sure that I'm using the correct terminology or if I'm leaving out information that is required to answer. So please be patient with me.

My client wants to include a video feed from an outside source inside a members area of their website. The members area is delivered over https and the video feed is not. Does this compromise the secure data?

I know that some browsers alert the user that there are secure and non-secure data being loaded on the page. Frankly, my client is okay with that, but I don't want to move forward if the user account information (specifically, session, etc.) is compromised.

Thanks for any help.

答:
If your pages references unencrypted Javascript or Flash, you're totally unprotected; an attacker can substitute any Javascript he wants, and can steal non-HTTP-only cookies, or make arbitrary HTTP requests that impersonate the current user.

If you reference unencrypted CSS, you're still vulnerable; attackers can arbitrarily modify your layout, and can execute arbitrary code in IE and Firefox.

If you reference unencrypted images, you're mostly fine; all the attacker can do is see the Referer header and find out what page the user is seeing.  (He'll also get any non-SSL-only cookies for the image's domain).
The attacker can also  alter the images to suit his needs, which may be a concern.


问:
Find a row and its index then delete this row using index
I would looking for a way to basically delete, step by step, a specific row.

```<code>      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design
</code>```

After deleting some row because of NaN, id's are different than index.
So, I used :

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

```<code>app.index[app['prix'] == 'Everyone'].tolist()
</code>```

But the result give me [28].
Then I tried

```<code>app.loc[app.index==28]
</code>```

Same result.
app.index[28] will told me :

```<code>IndexError: index 28 is out of bounds for axis 0 with size 5
</code>```

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

```<code>app = app.reset_index()
</code>```

♣ Find the rows (and the index)

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

♣ Delete this row using the index

```<code>app = app.drop(4795)
</code>```

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

答:
Assuming you want to exclude the rows where prix equals "Everyone."

```<code>new_df = app.loc[app['prix']!='Everyone']
</code>```

new_df is a slice of app. You can make it a new object by using copy

```<code>new_df = app.loc[app['prix']!='Everyone'].copy()
</code>```

Body:
I would looking for a way to basically delete, step by step, a specific row.

      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design

After deleting some row because of NaN, id's are different than index.
So, I used :

app.loc[app['prix']=='Everyone',:]

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

app.index[app['prix'] == 'Everyone'].tolist()

But the result give me [28].
Then I tried

app.loc[app.index==28]

Same result.
app.index[28] will told me :

IndexError: index 28 is out of bounds for axis 0 with size 5

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

app = app.reset_index()

♣ Find the rows (and the index)

app.loc[app['prix']=='Everyone',:]

♣ Delete this row using the index

app = app.drop(4795)

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

Body:
Assuming you want to exclude the rows where prix equals "Everyone."

new_df = app.loc[app['prix']!='Everyone']

new_df is a slice of app. You can make it a new object by using copy

new_df = app.loc[app['prix']!='Everyone'].copy()


问:
Flask url parameter capture
```<code>import flask

app = flask.Flask(__name__)

@app.route("/")
def index():
    return "You need to login"

@app.route('/login', methods=['GET', 'POST'])
def login():
    query = flask.request.query_string   # query is printed in terminal
    login = flask.request.get('login')   # here getting AttributeError
    print query, login
    if flask.request.method == 'POST':
        return "User is {}, Password is {}".format(flask.request.form['login'],flask.request.form['password'])
    else:
        return flask.render_template("login.html")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
</code>```

When I pass the url in browser http://127.0.0.1:5000/login?login=hello&password=1234, it says:

```<code>AttributeError: 'Request' object has no attribute 'get'
</code>```

答: If you want to get all values in the MultiDict with the same key, then you should use list_of_values = flask.request.args.getlist('name_of_key').

Title: Flask url parameter capture

Body:
import flask

app = flask.Flask(__name__)

@app.route("/")
def index():
    return "You need to login"

@app.route('/login', methods=['GET', 'POST'])
def login():
    query = flask.request.query_string   # query is printed in terminal
    login = flask.request.get('login')   # here getting AttributeError
    print query, login
    if flask.request.method == 'POST':
        return "User is {}, Password is {}".format(flask.request.form['login'],flask.request.form['password'])
    else:
        return flask.render_template("login.html")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

When I pass the url in browser http://127.0.0.1:5000/login?login=hello&password=1234, it says:

AttributeError: 'Request' object has no attribute 'get'


问:
Pandas create a dataframe whose entries are relationships between rows of another dataframe?
Suppose I have the following table in a csv.

```<code> elementID | groupID | sequence
     abc   |    A    |    0
     dcv   |    A    |    1
     asd   |    B    |    1
     ccc   |    B    |    0
     abc   |    B    |    2
</code>```

I imported this table in Pandas as a DataFrame.

From this DataFrame I need to create another one where each entry represents two two sequential elements of elementID.

For example something like the following

```<code> elementID_1 | elementID_2 | groupID
     abc     |    dcv      |    A
     asd     |    abc      |    B
     ccc     |    asd      |    B
</code>```

At first I thought of a multi-row selection but could not find out how to do that.

So I decided to do step by step creating one column per time.
I created first the column elementID_2 as follows

```<code>new_df = pd.DataFrame()
new_df[["elementID_2", "sequence", "groupID"]] = old_df.loc[old_df.loc.sequence>1][["elementID", "sequence", "groupID"]]
</code>```

Now to create the elementID_1 column I would like to match the entries of the old dataframe having assequence value, the sequence value of the new DataFrame minus 1 and the same groupdID between the two DataFrame.

How can I do that?

Body:
Suppose I have the following table in a csv.

 elementID | groupID | sequence
     abc   |    A    |    0
     dcv   |    A    |    1
     asd   |    B    |    1
     ccc   |    B    |    0
     abc   |    B    |    2

I imported this table in Pandas as a DataFrame.

From this DataFrame I need to create another one where each entry represents two two sequential elements of elementID.

For example something like the following

 elementID_1 | elementID_2 | groupID
     abc     |    dcv      |    A
     asd     |    abc      |    B
     ccc     |    asd      |    B

At first I thought of a multi-row selection but could not find out how to do that.

So I decided to do step by step creating one column per time.
I created first the column elementID_2 as follows

new_df = pd.DataFrame()
new_df[["elementID_2", "sequence", "groupID"]] = old_df.loc[old_df.loc.sequence>1][["elementID", "sequence", "groupID"]]

Now to create the elementID_1 column I would like to match the entries of the old dataframe having assequence value, the sequence value of the new DataFrame minus 1 and the same groupdID between the two DataFrame.

How can I do that?

Body:
IIUC, you can do so by shift() on groups and dropna:

df.sort_values('sequence', inplace=True)
df['elementID_1'] = df.groupby('groupID').elementID.shift()
df.dropna()

Output:

+----+-------------+-----------+------------+---------------+
|    | elementID   | groupID   |   sequence | elementID_1   |
|----+-------------+-----------+------------+---------------|
|  1 | dcv         | A         |          1 | abc           |
|  2 | asd         | B         |          3 | ccc           |
|  4 | abc         | B         |          4 | asd           |
+----+-------------+-----------+------------+---------------+

Then you can drop sequence column and rename elementID to elementID_2.


答:
```<code>ggplot(df, aes(site, number))+
  facet_wrap(~colour)+
  geom_jitter(aes(col = colour), alpha = 0.3, show.legend = F) +
  geom_boxplot(alpha = 0, colour = "black")+
  scale_color_manual(values = c("green", "red"))
</code>```

Title: Change colour of jitter points according to facet_wrap


问:
How to enable ocsp stapling in existing NodeJS backend?
I am totally new to NodeJS and today I had to update a ssl certificate in an existing NodeJS backend. I have never done anything with node and the guy that has written the application does not work for the company anymore...

So far so good... updating the certificates was no problem, I only had to change the pathes. After restarting the node backend and checking the application I got an error in my browser because of the required ocsp stapling.

I have already enabled ocsp in apache and nginx but I have no idea what to do with node.

I already installed ocsp node module via npm.

Here is the app.js code:

var http = require('http');
var https = require('https');
var config = require('./config.js');
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');

// ssl options
if (config.https) {
    var options = {
        ca: fs.readFileSync(config.sslCa),
        key: fs.readFileSync(config.sslKey),
        cert: fs.readFileSync(config.sslCert)
    };
}

var app = express();
var server;
if (config.https) {
    server = https.createServer(options, app);
} else {
    server = http.Server(app);
}

var io = require('socket.io').listen(server);
require('./socketEvents')(io);
var rest = require('./restRoutes')(io);
var morgan = require('morgan');
var cors = require('cors');
var verifyToken = require('./verifyToken');
var fileManagement = require('./fileManagement')(io);
var authorization = require('./authorization');
var restFiles = require('./restFiles')(io);

// serve static files
app.use('/bundles', express.static(config.iboxWebDir + '/bundles'));

var multer = require('multer');

// path for diskStorage
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './files');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now())
    }
});

// multer function to store the file
var upload = multer({storage: storage});

// CORS OPTIONS
app.use(cors({credentials: true, origin: true, maxAge: 600}));
app.use(morgan('dev')); // use morgan to log requests to the console

app.use('/icons', express.static(__dirname + '/../' + 'icons'));

// icon files
app.use('/restfiles', restFiles);

// app.use(bodyParser.urlencoded({extended: true})); // parse json-request
app.post('/file/upload', verifyToken, upload.fields([{name: 'roomId'}, {name: 'threadId'}, {name: 'files'}]), fileManagement.postFile);

// configure body-parser
app.use(bodyParser.json()); // parse json-request
app.use(bodyParser.urlencoded({extended: true})); // parse urlencoded from requests

app.get('/file/get', verifyToken, fileManagement.getFile);
app.post('/file/get', verifyToken, fileManagement.getFile);
app.post('/file/remove', verifyToken, authorization.canRemoveFile, fileManagement.removeFile);

// add router for rest api
app.use('/rest', rest);

module.exports = server;```

Hopefully there is someone who can give me some help.

Thanks a lot!

Philip

答:
you can try this:

```<code>...
var ocsp = require('ocsp')
...
var app = express();
var server;
if (config.https) {
    var ocspCache = new ocsp.Cache()
    server = https.createServer(options, app);

    server.on('OCSPRequest', function(cert, issuer, callback) {
        ocsp.getOCSPURI(cert, function(err, uri) {
            if (err) return callback(error);
            var req = ocsp.request.generate(cert, issuer);
            var options = {
                url: uri,
                ocsp: req.data
            };
            ocspCache.request(req.id, options, callback);
        });
    });

    // eventually you can omit this
    var sslSessionCache = {};
    server.on('newSession', function(sessionId, sessionData, callback) {
        sslSessionCache[sessionId] = sessionData;
        callback();
    });
    server.on('resumeSession', function (sessionId, callback) {
        callback(null, sslSessionCache[sessionId]);
    });
} else {
    server = http.Server(app);
}
...
</code>```

I got the modification from here

https://github.com/nodejs/node-v0.x-archive/issues/8660

Best regards

Dietrich

Body:
I am totally new to NodeJS and today I had to update a ssl certificate in an existing NodeJS backend. I have never done anything with node and the guy that has written the application does not work for the company anymore...

So far so good... updating the certificates was no problem, I only had to change the pathes. After restarting the node backend and checking the application I got an error in my browser because of the required ocsp stapling.

I have already enabled ocsp in apache and nginx but I have no idea what to do with node.

I already installed ocsp node module via npm.

Here is the app.js code:

var http = require('http');
var https = require('https');
var config = require('./config.js');
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');

// ssl options
if (config.https) {
    var options = {
        ca: fs.readFileSync(config.sslCa),
        key: fs.readFileSync(config.sslKey),
        cert: fs.readFileSync(config.sslCert)
    };
}

var app = express();
var server;
if (config.https) {
    server = https.createServer(options, app);
} else {
    server = http.Server(app);
}

var io = require('socket.io').listen(server);
require('./socketEvents')(io);
var rest = require('./restRoutes')(io);
var morgan = require('morgan');
var cors = require('cors');
var verifyToken = require('./verifyToken');
var fileManagement = require('./fileManagement')(io);
var authorization = require('./authorization');
var restFiles = require('./restFiles')(io);

// serve static files
app.use('/bundles', express.static(config.iboxWebDir + '/bundles'));

var multer = require('multer');

// path for diskStorage
var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './files');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now())
    }
});

// multer function to store the file
var upload = multer({storage: storage});

// CORS OPTIONS
app.use(cors({credentials: true, origin: true, maxAge: 600}));
app.use(morgan('dev')); // use morgan to log requests to the console

app.use('/icons', express.static(__dirname + '/../' + 'icons'));

// icon files
app.use('/restfiles', restFiles);

// app.use(bodyParser.urlencoded({extended: true})); // parse json-request
app.post('/file/upload', verifyToken, upload.fields([{name: 'roomId'}, {name: 'threadId'}, {name: 'files'}]), fileManagement.postFile);

// configure body-parser
app.use(bodyParser.json()); // parse json-request
app.use(bodyParser.urlencoded({extended: true})); // parse urlencoded from requests

app.get('/file/get', verifyToken, fileManagement.getFile);
app.post('/file/get', verifyToken, fileManagement.getFile);
app.post('/file/remove', verifyToken, authorization.canRemoveFile, fileManagement.removeFile);

// add router for rest api
app.use('/rest', rest);

module.exports = server;

Hopefully there is someone who can give me some help.

Thanks a lot!

Philip

Body:
you can try this:

...
var ocsp = require('ocsp')
...
var app = express();
var server;
if (config.https) {
    var ocspCache = new ocsp.Cache()
    server = https.createServer(options, app);

    server.on('OCSPRequest', function(cert, issuer, callback) {
        ocsp.getOCSPURI(cert, function(err, uri) {
            if (err) return callback(error);
            var req = ocsp.request.generate(cert, issuer);
            var options = {
                url: uri,
                ocsp: req.data
            };
            ocspCache.request(req.id, options, callback);
        });
    });

    // eventually you can omit this
    var sslSessionCache = {};
    server.on('newSession', function(sessionId, sessionData, callback) {
        sslSessionCache[sessionId] = sessionData;
        callback();
    });
    server.on('resumeSession', function (sessionId, callback) {
        callback(null, sslSessionCache[sessionId]);
    });
} else {
    server = http.Server(app);
}
...

I got the modification from here

https://github.com/nodejs/node-v0.x-archive/issues/8660

Best regards

Dietrich


问:
How to search a string for values and convert values
I have an API that accepts a string that needs to be properly formatted before going into the server.

The format for going into the server is the following

```<code>"{Country ABR} {Day/Hour} {State ABR} {Title} {hrs.} ({Month Year}.)"
</code>```

Several Possibilities the client may send in :

```<code>"US Construction 7/70 hrs."

"IA Private hrs US.

"OIL US 8/70 hrs (Dec 2014).
</code>```

Several valid examples after converting user input are:

```<code>"US 7/70 MI Construction hrs."

"US IA Private hrs."

"US OIL 8/70 hrs. (Dec 2014)"
</code>```

the converter arranges the input into the correct order. hrs always ends with a period and rearranges ({Month Year}) outside the sentence as shown.

so far I have

```<code>       [TestMethod]
    public void TestMethod1()
    {
        var toConvert = "USA Construction 70/700 (Dec 2014) hrs";
        var converted = ConvertHOSRules(toConvert);

        Assert.AreEqual(converted, "USA 70/700 Construction hrs.(Dec 2014)");
    }

    private string ConvertHOSRules(string input)
    {
        //todo refactor
        string output = "";

        string country = Regex.Match(input, @"\b(USA|CAN|MEX)\b").Value +" ";
        string dateHours =  Regex.Match(input,@"\d{1,2}\/\d{1,3}").Value + " ";
        string hrs = Regex.Match(input, @"\b(hrs)\b").Value ;
        var date = Regex.Match(input, @"\(([a-zA-Z]+\s{1}[0-9]{4})\)").Value + " ";
        string title = input.Replace(country, "").Replace(date, "").Replace(dateHours, "").Replace(hrs, "");
        output = $"{country} {dateHours} {title} {hrs}.{date}";
        return output;

    }
</code>```

This is passing i need to refactor.. the + " " is like a null guard by lazy programmer

答:
This question is quite interesting, especially if we would want to design algorithms for it, because my guess is that our regular expressions would be rather unnecessary.

If we wish to do that with expressions, I would start with a simple expression such as listing possible countries and states in two capturing groups:

```<code>(US|UK|FR)
(CA|WA|IA|MO|MI)
</code>```

then our hours are well-structured:

```<code>(\d+\/\d+)
</code>```

so is the month (.+?) and year ([0-9]+):

```<code>\(((.+?)\s+([0-9]+))\)
</code>```

and here is where we would be facing problem with other keywords such as Construction and OIL, we could add a min 3 chars not to possibly conflict with states and countries:

```<code>([A-Z][a-z]{2,}|[A-Z]{3,})
</code>```

and last we would clean our string by collecting all spaces and other chars left, such as hrs. which is just repeating and we might not want to match or capture that.

```<code>(.*?)
</code>```

Finally, we would combine using alternation:

```<code>(US|UK|FR)|(CA|NY|IA|TX|MI)|(\d+\/\d+)|\(((.+?)\s+([0-9]+))\)|([A-Z][a-z]{2,}|[A-Z]{3,})|(.*?)
</code>```

DEMO

Test

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(US|UK|FR)|(CA|NY|IA|TX|MI)|(\d+\/\d+)|\(((.+?)\s+([0-9]+))\)|([A-Z][a-z]{2,}|[A-Z]{3,})|(.*?)";
        string input = @"US 7/70 MI Construction hrs.
US IA Private hrs.
US OIL 8/70 hrs. (Dec 2014)
UK 7/70 MI Construction hrs.
UK IA Private hrs.
UK OIL 8/70 hrs. (Dec 2014)
FR 7/70 MI Construction hrs.
FR IA Private hrs.
FR OIL 8/70 hrs. (Dec 2014)";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}
</code>```

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I have an API that accepts a string that needs to be properly formatted before going into the server.

The format for going into the server is the following

"{Country ABR} {Day/Hour} {State ABR} {Title} {hrs.} ({Month Year}.)"

Several Possibilities the client may send in :

"US Construction 7/70 hrs."

"IA Private hrs US.

"OIL US 8/70 hrs (Dec 2014).

Several valid examples after converting user input are:

"US 7/70 MI Construction hrs."

"US IA Private hrs."

"US OIL 8/70 hrs. (Dec 2014)"

the converter arranges the input into the correct order. hrs always ends with a period and rearranges ({Month Year}) outside the sentence as shown.

so far I have

       [TestMethod]
    public void TestMethod1()
    {
        var toConvert = "USA Construction 70/700 (Dec 2014) hrs";
        var converted = ConvertHOSRules(toConvert);

        Assert.AreEqual(converted, "USA 70/700 Construction hrs.(Dec 2014)");
    }

    private string ConvertHOSRules(string input)
    {
        //todo refactor
        string output = "";

        string country = Regex.Match(input, @"\b(USA|CAN|MEX)\b").Value +" ";
        string dateHours =  Regex.Match(input,@"\d{1,2}\/\d{1,3}").Value + " ";
        string hrs = Regex.Match(input, @"\b(hrs)\b").Value ;
        var date = Regex.Match(input, @"\(([a-zA-Z]+\s{1}[0-9]{4})\)").Value + " ";
        string title = input.Replace(country, "").Replace(date, "").Replace(dateHours, "").Replace(hrs, "");
        output = $"{country} {dateHours} {title} {hrs}.{date}";
        return output;

    }

This is passing i need to refactor.. the + " " is like a null guard by lazy programmer

Body:
This question is quite interesting, especially if we would want to design algorithms for it, because my guess is that our regular expressions would be rather unnecessary.

If we wish to do that with expressions, I would start with a simple expression such as listing possible countries and states in two capturing groups:

(US|UK|FR)
(CA|WA|IA|MO|MI)

then our hours are well-structured:

(\d+\/\d+)

so is the month (.+?) and year ([0-9]+):

\(((.+?)\s+([0-9]+))\)

and here is where we would be facing problem with other keywords such as Construction and OIL, we could add a min 3 chars not to possibly conflict with states and countries:

([A-Z][a-z]{2,}|[A-Z]{3,})

and last we would clean our string by collecting all spaces and other chars left, such as hrs. which is just repeating and we might not want to match or capture that.

(.*?)

Finally, we would combine using alternation:

(US|UK|FR)|(CA|NY|IA|TX|MI)|(\d+\/\d+)|\(((.+?)\s+([0-9]+))\)|([A-Z][a-z]{2,}|[A-Z]{3,})|(.*?)

DEMO

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(US|UK|FR)|(CA|NY|IA|TX|MI)|(\d+\/\d+)|\(((.+?)\s+([0-9]+))\)|([A-Z][a-z]{2,}|[A-Z]{3,})|(.*?)";
        string input = @"US 7/70 MI Construction hrs.
US IA Private hrs.
US OIL 8/70 hrs. (Dec 2014)
UK 7/70 MI Construction hrs.
UK IA Private hrs.
UK OIL 8/70 hrs. (Dec 2014)
FR 7/70 MI Construction hrs.
FR IA Private hrs.
FR OIL 8/70 hrs. (Dec 2014)";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

DEMO

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:


问:
How to implement Urban Airship for Push notification in iPhone?
I'm trying to use urbanairship push notification. But while creating instance of UAirship, it is showing error that UAirship is undeclared.i have implemented urbanairship upto http://urbanairship.com/docs/apns_test_client.html#prerequisite and after then i do not know what should i do ? Waiting for response. Thanks.</p>

答: Have you included UAirship.h and UAPush.h ?


问:
OpenCart 3 header image from module
I would like to add an Image as background by selecting from a module. The new extension is created under starter_module name.

Please, do not suggest to add image in css file.

The image set in module is not saving, this would be the issue, if you know the solution, please add in your comment.

Many thanks,

I added in: admin/view/template/extension/module/starter_module.twig

```<code><div class="form-group">
        <label class="col-sm-2 control-label" for="input-headbg">Header Image</label>
        <div class="col-sm-10">
        <a href="" id="thumb-headbg" data-toggle="image" class="img-thumbnail">
        <img src="{{ headbg }}" alt="" title="" data-placeholder="{{ placeholder }}" />
        </a>
        <input type="hidden" name="config_headbg" value="{{ config_headbg }}" id="input-headbg" />
    </div>
</div>

</code>```

In admin/controller/extension/module/starter_module.php

```<code>//Top page
// Module Image
$this->model_setting_setting->editSetting('config_headbg', $this->request->post);
// Module Image
// Module Image

if (isset($this->request->post['config_headbg'])) {
    $data['headbg'] = $this->request->post['config_headbg'];
} else {
    $data['headbg'] = $this->config->get('config_headbg');
}
$this->load->model('tool/image');

if (isset($this->request->post['config_headbg']) && is_file(DIR_IMAGE . $this->request->post['config_headbg'])) {
    $data['headbg'] = $this->model_tool_image->resize($this->request->post['config_headbg'], 100, 100);
} elseif ($this->config->get('config_headbg') && is_file(DIR_IMAGE . $this->config->get('config_headbg'))) {
    $data['headbg'] = $this->model_tool_image->resize($this->config->get('config_headbg'), 100, 100);
} else {
    $data['headbg'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);

// Module Image

</code>```

In catalog/controller/common/header.php

```<code>if (is_file(DIR_IMAGE . $this->config->get('config_headbg'))) {
    $data['headbg'] = $server . 'image/' . $this->config->get('config_headbg');
} else {
    $data['headbg'] = '';
}

</code>```

In catalog/view/theme/default/template/common/header.twig

```<code>
{{ headbg }}

</code>```

Many thanks,

The files you check here https://github.com/bblori/OpenCart3-Module-Header-Image

答:
I'm new to opencart but from what I see in your form the input is named headbg
<input type="hidden" name="headbg" value="{{ config_headbg }}" id="input-headbg" /> and in admin controller you check for config_headbg if (isset($this->request->post['config_headbg']))

Title: OpenCart 3 header image from module

Body:
I would like to add an Image as background by selecting from a module. The new extension is created under starter_module name.

Please, do not suggest to add image in css file.

The image set in module is not saving, this would be the issue, if you know the solution, please add in your comment.

Many thanks,

I added in: admin/view/template/extension/module/starter_module.twig

        Header Image

        <input type="hidden" name="config_headbg" value="{{ config_headbg }}" id="input-headbg" />

In admin/controller/extension/module/starter_module.php

//Top page
// Module Image
$this->model_setting_setting->editSetting('config_headbg', $this->request->post);
// Module Image
// Module Image

if (isset($this->request->post['config_headbg'])) {
    $data['headbg'] = $this->request->post['config_headbg'];
} else {
    $data['headbg'] = $this->config->get('config_headbg');
}
$this->load->model('tool/image');

if (isset($this->request->post['config_headbg']) && is_file(DIR_IMAGE . $this->request->post['config_headbg'])) {
    $data['headbg'] = $this->model_tool_image->resize($this->request->post['config_headbg'], 100, 100);
} elseif ($this->config->get('config_headbg') && is_file(DIR_IMAGE . $this->config->get('config_headbg'))) {
    $data['headbg'] = $this->model_tool_image->resize($this->config->get('config_headbg'), 100, 100);
} else {
    $data['headbg'] = $this->model_tool_image->resize('no_image.png', 100, 100);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);

// Module Image

In catalog/controller/common/header.php

if (is_file(DIR_IMAGE . $this->config->get('config_headbg'))) {
    $data['headbg'] = $server . 'image/' . $this->config->get('config_headbg');
} else {
    $data['headbg'] = '';
}

In catalog/view/theme/default/template/common/header.twig

{{ headbg }}

Many thanks,

The files you check here https://github.com/bblori/OpenCart3-Module-Header-Image