问:
MS Access Query for time In/Out attendance
I'm doing a project which involves time and attendance management. When I download data from the biometric reader, I got the records in the following format,

```<code>USERID  CHECKTIME
5001    12/09/2011  09:05:34
5002    12/09/2011  09:33:13
5001    12/09/2011  13:05:53
5002    12/09/2011  13:22:24
5001    12/09/2011  14:05:22
5002    12/09/2011  14:33:53
5001    12/09/2011  18:05:09
5002    12/09/2011  17:44:34
</code>```

This is the image

I want to show the above records as follows,
(the Log_In, LB_Out, LB_In, Log_Out, WorkTime and LunchBreak are based on 'time')

This is the image

Please help me out to make this query,

答:
You can group by userid and date and then use conditional aggregation:

```<code>select t.userid, datevalue(t.checktime) as [date],
  max(iif(t.counter = 0, t.checktime, null)) as Log_In,
  max(iif(t.counter = 1, t.checktime, null)) as LB_Out,
  max(iif(t.counter = 2, t.checktime, null)) as LB_In,
  max(iif(t.counter = 3, t.checktime, null)) as Log_Out,
  Format((Log_In - LB_Out) + (LB_In - Log_Out), "HH:mm:ss") as WorkTime,
  Format(LB_In - LB_Out, "HH:mm:ss") as LunchBreak
from (
  select t.*,
    (select count(*) from tablename where userid = t.userid and datevalue(checktime) = datevalue(t.checktime) and checktime < t.checktime) as counter
  from tablename as t
) as t
group by t.userid, datevalue(t.checktime)
</code>```

Results:

```<code>userid  date        Log_In                  LB_Out                  LB_In                   Log_Out                 WorkTime  LunchBreak
5001    12/9/2011   12/9/2011 9:05:34 am    12/9/2011 1:05:53 pm    12/9/2011 2:05:22 pm    12/9/2011 6:05:09 pm    08:00:06  00:59:29
5002    12/9/2011   12/9/2011 9:33:13 am    12/9/2011 1:22:24 pm    12/9/2011 2:33:53 pm    12/9/2011 5:44:34 pm    06:59:52  01:11:29
</code>```

Body:
I'm doing a project which involves time and attendance management. When I download data from the biometric reader, I got the records in the following format,

USERID  CHECKTIME
5001    12/09/2011  09:05:34
5002    12/09/2011  09:33:13
5001    12/09/2011  13:05:53
5002    12/09/2011  13:22:24
5001    12/09/2011  14:05:22
5002    12/09/2011  14:33:53
5001    12/09/2011  18:05:09
5002    12/09/2011  17:44:34

This is the image

I want to show the above records as follows,
(the Log_In, LB_Out, LB_In, Log_Out, WorkTime and LunchBreak are based on 'time')

This is the image

Please help me out to make this query,

Body:
You can group by userid and date and then use conditional aggregation:

select t.userid, datevalue(t.checktime) as [date],
  max(iif(t.counter = 0, t.checktime, null)) as Log_In,
  max(iif(t.counter = 1, t.checktime, null)) as LB_Out,
  max(iif(t.counter = 2, t.checktime, null)) as LB_In,
  max(iif(t.counter = 3, t.checktime, null)) as Log_Out,
  Format((Log_In - LB_Out) + (LB_In - Log_Out), "HH:mm:ss") as WorkTime,
  Format(LB_In - LB_Out, "HH:mm:ss") as LunchBreak
from (
  select t.*,
    (select count(*) from tablename where userid = t.userid and datevalue(checktime) = datevalue(t.checktime) and checktime < t.checktime) as counter
  from tablename as t
) as t
group by t.userid, datevalue(t.checktime)

Results:

userid  date        Log_In                  LB_Out                  LB_In                   Log_Out                 WorkTime  LunchBreak
5001    12/9/2011   12/9/2011 9:05:34 am    12/9/2011 1:05:53 pm    12/9/2011 2:05:22 pm    12/9/2011 6:05:09 pm    08:00:06  00:59:29
5002    12/9/2011   12/9/2011 9:33:13 am    12/9/2011 1:22:24 pm    12/9/2011 2:33:53 pm    12/9/2011 5:44:34 pm    06:59:52  01:11:29


来源: stackexchange

问:
SQL Server: JSON Auditing
I'm trying to build an auditing strategy using triggers.  I originally tried this:

Trigger Based Change Data capture

It worked pretty well: it produced a nicely-formatted JSON, that looked like this:

```<code>{
    "columns" :[
     {
        "name": "ID",
        "value:" : {
          "old": "1",
          "new": "2"
        }
     },
     {
        "name": "ModifiedOn",
        "value:" : {
          "old": "2020-02-14 16:00:00",
          "new": "2020-02-15 13:00:00"
        }
     }
    ]
}
</code>```

It even listed what columns were updated in the update trigger.  It worked well - until the system hit load.  Because the trigger selects info from system tables, it pretty much killed performance because of deadlocks.

I modified the script to include NOLOCK hints, but I'm also using a bulk upload library for EF Core; it uses temp tables, and technically 'modifies' the schema - so I was still running into deadlocks with sch-s and sch-m locks.

I modified the script to simply select the values in inserted/deleted into the audit tables but it's a lot harder to read.

The following (also found on SO) gets me close:

```<code>SELECT [name] = b.[key],
VALUE = CAST(b.[value] as NVARCHAR(MAX))
FROM inserted i,
cross apply
(SELECT * FROM OPENJSON((SELECT * FROM INSERTED FOR JSON PATH,
     WITHOUT_ARRAY_WRAPPER))) B
FOR JSON PATH
</code>```

But it only grabs the values from the first row.

Has anyone done anything similar to this?

I could have the script generate the statements if I have to 'hard-code' the columns, if necessary.

Thanks.

答:
```<code>declare @inserted table
(
id int primary key clustered,
colA int,
colB varchar(10),
colC uniqueidentifier,
colD date
)

insert into @inserted(id, ColA, colB, colC, colD)
values
(1, 100, 'ABC', newid(), getdate()),
(2, 200, 'DEF', newid(), getdate()),
(3, 300, 'KLM', newid(), getdate()),
(4, 400, 'XYZ', newid(), getdate());

select id, (select i.* for json path) as thejson
from @inserted as i;

declare @deleted table
(
id int primary key clustered,
colA int,
colB varchar(10),
colC uniqueidentifier,
colD date
)

insert into @deleted(id, ColA, colB, colC, colD)
values
(1, 100, 'ABC', newid(), getdate()),
(2, 200, 'DEF', newid(), getdate()),
(3, 300, 'KLM', newid(), getdate()),
(4, 400, 'XYZ', newid(), getdate());

select
    [name] = o.[key],
    VALUE = CAST(o.[value] as NVARCHAR(MAX))
from
(
select (select d.* for json path, WITHOUT_ARRAY_WRAPPER) as thejson
from @deleted as d
) as src
cross apply openjson(src.thejson) as o;
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL Server: JSON Auditing

Body:
I'm trying to build an auditing strategy using triggers.  I originally tried this:

Trigger Based Change Data capture

It worked pretty well: it produced a nicely-formatted JSON, that looked like this:

{
    "columns" :[
     {
        "name": "ID",
        "value:" : {
          "old": "1",
          "new": "2"
        }
     },
     {
        "name": "ModifiedOn",
        "value:" : {
          "old": "2020-02-14 16:00:00",
          "new": "2020-02-15 13:00:00"
        }
     }
    ]
}

It even listed what columns were updated in the update trigger.  It worked well - until the system hit load.  Because the trigger selects info from system tables, it pretty much killed performance because of deadlocks.

I modified the script to include NOLOCK hints, but I'm also using a bulk upload library for EF Core; it uses temp tables, and technically 'modifies' the schema - so I was still running into deadlocks with sch-s and sch-m locks.

I modified the script to simply select the values in inserted/deleted into the audit tables but it's a lot harder to read.

The following (also found on SO) gets me close:

SELECT [name] = b.[key],
VALUE = CAST(b.[value] as NVARCHAR(MAX))
FROM inserted i,
cross apply
(SELECT * FROM OPENJSON((SELECT * FROM INSERTED FOR JSON PATH,
     WITHOUT_ARRAY_WRAPPER))) B
FOR JSON PATH

But it only grabs the values from the first row.

Has anyone done anything similar to this?

I could have the script generate the statements if I have to 'hard-code' the columns, if necessary.

Thanks.


问:
how to make a new array from an existing array in php?
let's say if I have an array like this below.

```<code>$i = array(
    'arr1'  => array(
        'a11'   => 'ar11',
        'a12'   => 'ar12',
    ),
    'arr2'  => array(
        'a21'   => 'ar21',
        'a22'   => 'ar22',
        'a23'   => 'ar23',
    ),
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);
</code>```

I want a new array that created from this array like the one I mentioned below,

```<code>$j = array(
    'a11'   => 'ar11',
    'a12'   => 'ar12',
    'a21'   => 'ar21',
    'a22'   => 'ar22',
    'a23'   => 'ar23',
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);
</code>```

sofar I tried extracting the last two elements which aren't arrays I mention the code below

```<code>$ii = $i;
foreach($ii as $k => $v):
    if(is_array($v)):
        unset($ii[$k]);
    endif;
endforeach;
</code>```

this returns me the last two elements. but the way i tried extracting the other elements looks wired see below.

```<code>$i1 = $i['arr1'];
$i2 = $i['arr2'];
$i3 = array_merge($i1, $i2);
$final = array_merge($i3, $j);
</code>```

this looks simple because it has small amout of elemetns but i have large amount of elements in my project, any other ways to get this output?

答:
array_walk_recursive() is what you need:

```<code>$a = array(
    'arr1'=> array(
        'a11' => 'ar11',
        'a12' => 'ar12',
    ),
    'arr2'=> array(
        'a21' => 'ar21',
        'a22' => 'ar22',
        'a23' => 'ar23',
    ),
    'arr3' => 'arrr3',
    'arr4' => 'arrr4'
);

$b = array();
array_walk_recursive($a, function($val, $key) use(&$b)
{
    $b[$key] = $val;
});
</code>```

You can test it here.

Body:
let's say if I have an array like this below.

$i = array(
    'arr1'  => array(
        'a11'   => 'ar11',
        'a12'   => 'ar12',
    ),
    'arr2'  => array(
        'a21'   => 'ar21',
        'a22'   => 'ar22',
        'a23'   => 'ar23',
    ),
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

I want a new array that created from this array like the one I mentioned below,

$j = array(
    'a11'   => 'ar11',
    'a12'   => 'ar12',
    'a21'   => 'ar21',
    'a22'   => 'ar22',
    'a23'   => 'ar23',
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

sofar I tried extracting the last two elements which aren't arrays I mention the code below

$ii = $i;
foreach($ii as $k => $v):
    if(is_array($v)):
        unset($ii[$k]);
    endif;
endforeach;

this returns me the last two elements. but the way i tried extracting the other elements looks wired see below.

$i1 = $i['arr1'];
$i2 = $i['arr2'];
$i3 = array_merge($i1, $i2);
$final = array_merge($i3, $j);

this looks simple because it has small amout of elemetns but i have large amount of elements in my project, any other ways to get this output?

Body:
array_walk_recursive() is what you need:

$a = array(
    'arr1'=> array(
        'a11' => 'ar11',
        'a12' => 'ar12',
    ),
    'arr2'=> array(
        'a21' => 'ar21',
        'a22' => 'ar22',
        'a23' => 'ar23',
    ),
    'arr3' => 'arrr3',
    'arr4' => 'arrr4'
);

$b = array();
array_walk_recursive($a, function($val, $key) use(&$b)
{
    $b[$key] = $val;
});

You can test it here.


问:
Angular: Type ArrayBuffer is not assignable to type string
I'm trying to show selected image's preview before uploading it to server..

html

```<code><div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)">
            <p>drag one or more files to this dropzone</p>
            <img src="" id="imgPreview">
</div>
</code>```

ts

```<code>dropHandler(ev){

    console.log(ev);
    console.log("file dropped");
    event.preventDefault();
    if (ev.files && ev.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        var abc=<HTMLImageElement>document.getElementById('imgPreview');
        abc.src=e.target.result;
      };

      reader.readAsDataURL(ev.files[0]);
  }
</code>```

but abc.src=e.target.result seems to return an ArrayBuffer.How do i get url of the selected image as string using FileReader?

答:
I think you've got the principles correct. It works when I run a simpler version of your code with a file upload.

https://stackblitz.com/edit/angular-fxa49p

```<code><input type="file" #file (change)="onUpload(file.files[0])" />
<img *ngIf="src" [attr.src]="src" id="imgPreview">
</code>```

```<code>  onUpload(file): void {
    if (!file) {
      return;
    }

    const reader = new FileReader();
    reader.onload = e => {
      this.src = <string>e.target.result;
    };
    reader.readAsDataURL(file);
  }
</code>```

I had to cast the e.target.result to a string to keep the linter happy, but the javascript is fine.

NB the drop functionality wasn't working for me in Stackblitz, hence the file upload. It should be the same in principle as a file drop though as you're ultimately dealing with a File object.

Body:
I'm trying to show selected image's preview before uploading it to server..

html

drag one or more files to this dropzone

ts

dropHandler(ev){

    console.log(ev);
    console.log("file dropped");
    event.preventDefault();
    if (ev.files && ev.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        var abc=<HTMLImageElement>document.getElementById('imgPreview');
        abc.src=e.target.result;
      };

      reader.readAsDataURL(ev.files[0]);
  }

but abc.src=e.target.result seems to return an ArrayBuffer.How do i get url of the selected image as string using FileReader?

Body:
I think you've got the principles correct. It works when I run a simpler version of your code with a file upload.

https://stackblitz.com/edit/angular-fxa49p

<input type="file" #file (change)="onUpload(file.files[0])" />
<img *ngIf="src" [attr.src]="src" id="imgPreview">

  onUpload(file): void {
    if (!file) {
      return;
    }

    const reader = new FileReader();
    reader.onload = e => {
      this.src = <string>e.target.result;
    };
    reader.readAsDataURL(file);
  }

I had to cast the e.target.result to a string to keep the linter happy, but the javascript is fine.

NB the drop functionality wasn't working for me in Stackblitz, hence the file upload. It should be the same in principle as a file drop though as you're ultimately dealing with a File object.


问:
Autoencoder for Tabular Data with Discrete Values
I want to use an autoencoder for dimension reduction in Keras. The input is a table with discrete values 0,1,2,3,4 (each of these numbers show a category) in the columns. Each subject has a label 0/1 to show sick/healthy. Now I have two questions:

Which activation function should I use in the last layer? Shall I use a combination of sigmoid and ReLU?

I don't know if this kind of input variables need normalization (and if the answer is yes, how?)

答:
Which activation function should I use in the last layer? Shall I use a combination of sigmoid and ReLU?

The activation in the last layer should be sigmoid and use binary_crossentropy loss function for training.

I don't know if this kind of input variables need normalization (and if the answer is yes, how?)

It depends on the nature of discrete values you mentioned. As you know, inputs to a neural network represents the "intensity" of each neurons; higher values mean the neuron being more intensive/active. So, categorical values as input to a NN only makes sense if they map to a continuous range. For example if excellent=3, good=2, bad=1, terrible=0, it's okay to feed these values to a NN because it makes sense to calculate f(wx+b) (intensity of the neuron)  as a value of 1.5 means somewhere between bad and good.

However if the categorical values are pure nomial values without any relationship between them (for example: apple=1, orange=2, banana=3), it really doen't make sense to calculate the f(wx+b). In this case what does value 1.5 mean? For this type of data as input to a NN you should convert them to a binary encoding. For example if you have only 3 fruits you can encode this way:

```<code>apple  = [1, 0, 0]
orange = [0, 1, 0]
banana = [0, 0, 1]
</code>```

For this binary conversion, Keras has an utility function: to_categorical.

Body:
Which activation function should I use in the last layer? Shall I use a combination of sigmoid and ReLU?

The activation in the last layer should be sigmoid and use binary_crossentropy loss function for training.

I don't know if this kind of input variables need normalization (and if the answer is yes, how?)

It depends on the nature of discrete values you mentioned. As you know, inputs to a neural network represents the "intensity" of each neurons; higher values mean the neuron being more intensive/active. So, categorical values as input to a NN only makes sense if they map to a continuous range. For example if excellent=3, good=2, bad=1, terrible=0, it's okay to feed these values to a NN because it makes sense to calculate f(wx+b) (intensity of the neuron)  as a value of 1.5 means somewhere between bad and good.

However if the categorical values are pure nomial values without any relationship between them (for example: apple=1, orange=2, banana=3), it really doen't make sense to calculate the f(wx+b). In this case what does value 1.5 mean? For this type of data as input to a NN you should convert them to a binary encoding. For example if you have only 3 fruits you can encode this way:

apple  = [1, 0, 0]
orange = [0, 1, 0]
banana = [0, 0, 1]

For this binary conversion, Keras has an utility function: to_categorical.


问:
Idiom for handling size_t underflow in loop condition
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

```<code>for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}
</code>```

There's the --> "operator" trick, which looks strange if you're not used to it.

```<code>for (size_t i = len; i--> 0;) {
    use(a[i]);
}
</code>```

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

```<code>for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}
</code>```

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

```<code>for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}
</code>```

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

```<code>for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}
</code>```

As for the iterating backwards case, you can use signed integers but that may cause overflows.

```<code>for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}
</code>```

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

```<code>for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}
</code>```

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

答:
There are many possible answers for this question.  Which is best is opinion based.  I'll offer some options.

For iterating over all elements of an array in reverse order, using an unsigned index, one option is

```<code>for (size_t index = 0; index < len; ++index)
{
     size_t i = len - 1 - index;
     use(a[i]);
}
</code>```

or (more simply)

```<code>for (size_t i = 0; i < len; ++i)
{
     use(a[len - 1 - i]);
}
</code>```

In both cases, if len is zero, the loop body is not executed.  Although the loops increment rather than decrement,  both access elements in reverse order.   If you are frequently writing such loops, it is also not difficult to write a little inline function of the form

```<code>size_t index_in_reverse(size_t index, size_t len)
{
     return len - 1 - index;
}
</code>```

and do

```<code>for (size_t i = 0; i < len; ++i)
{
     use(index_in_reverse(i, len));
}
</code>```

To iterate forward over all elements of the loop in forward order, except the last, I'd make that explicit rather than trying to do it in the loop condition.

```<code>if (len > 0)
{
     size_t  shortened_len = len - 1;
     for (size_t i = 0; i < shortened_len; ++i)
         use(a[i]);
}
</code>```

The reason I introduce the variable shortened_len is to make the code self-documenting about the fact it is not iterating over the entire array.   I've seen too many cases where a condition of the form i < len - 1 is "corrected" by a subsequent developer to remove the - 1 because they believe it is a typo.

That may feel "clumsy" to the OP, but I suggest that

```<code>for (size_t i = 0; len > 0 && i < len-1; i++) {
   use(a[i]);
}
</code>```

is harder for a human to understand (putting multiple tests in a loop condition, forces a person maintaining the code to actually work out what both conditions do and, how they interact).    Given a choice between code that is "concise" or code that is "less concise but consumes less brainpower of an unacquainted human to understand" I will ALWAYS choose the latter.    Bear in mind that the user maintaining the code six months later may be yourself, and there are few thought processes more humbling than "What idiot wrote this??   Oh, it was me!".

Body:
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}

There's the --> "operator" trick, which looks strange if you're not used to it.

for (size_t i = len; i--> 0;) {
    use(a[i]);
}

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}

As for the iterating backwards case, you can use signed integers but that may cause overflows.

for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

Body:
There are many possible answers for this question.  Which is best is opinion based.  I'll offer some options.

For iterating over all elements of an array in reverse order, using an unsigned index, one option is

for (size_t index = 0; index < len; ++index)
{
     size_t i = len - 1 - index;
     use(a[i]);
}

or (more simply)

for (size_t i = 0; i < len; ++i)
{
     use(a[len - 1 - i]);
}

In both cases, if len is zero, the loop body is not executed.  Although the loops increment rather than decrement,  both access elements in reverse order.   If you are frequently writing such loops, it is also not difficult to write a little inline function of the form

size_t index_in_reverse(size_t index, size_t len)
{
     return len - 1 - index;
}

and do

for (size_t i = 0; i < len; ++i)
{
     use(index_in_reverse(i, len));
}

To iterate forward over all elements of the loop in forward order, except the last, I'd make that explicit rather than trying to do it in the loop condition.

if (len > 0)
{
     size_t  shortened_len = len - 1;
     for (size_t i = 0; i < shortened_len; ++i)
         use(a[i]);
}

The reason I introduce the variable shortened_len is to make the code self-documenting about the fact it is not iterating over the entire array.   I've seen too many cases where a condition of the form i < len - 1 is "corrected" by a subsequent developer to remove the - 1 because they believe it is a typo.

That may feel "clumsy" to the OP, but I suggest that

for (size_t i = 0; len > 0 && i < len-1; i++) {
   use(a[i]);
}

is harder for a human to understand (putting multiple tests in a loop condition, forces a person maintaining the code to actually work out what both conditions do and, how they interact).    Given a choice between code that is "concise" or code that is "less concise but consumes less brainpower of an unacquainted human to understand" I will ALWAYS choose the latter.    Bear in mind that the user maintaining the code six months later may be yourself, and there are few thought processes more humbling than "What idiot wrote this??   Oh, it was me!".


问:
php Json remove double quotes for key and how to change name of the key
Sample Json

```<code>data:[{"varExchange":"ftx","varPrice":482.3},{"varExchange":"ftx","varPrice":481.8}]
</code>```

I want to change the name of the key from "varExchange" to "name" and "varPrice" to "qty"

I need to remove the double quotes for key.

Output Like

```<code> data:[{name:"test","qty":482.3},{name:"test","qty":481.8}]
</code>```

Kindly help me to fix this.
Thanks

答:
First make proper input json array.

Then create new array as per your need for change the key

var data = [{"varExchange":"ftx","varPrice":482.3},{"varExchange":"ftx","varPrice":481.8}];
var new_data = [];
for(var k in data){

  new_data.push({name : data[k].varExchange, qty : data[k].varPrice });
}

console.log(new_data);```

Body:
Sample Json

data:[{"varExchange":"ftx","varPrice":482.3},{"varExchange":"ftx","varPrice":481.8}]

I want to change the name of the key from "varExchange" to "name" and "varPrice" to "qty"

I need to remove the double quotes for key.

Output Like

 data:[{name:"test","qty":482.3},{name:"test","qty":481.8}]

Kindly help me to fix this.
Thanks


问:
How to render incrementally images taken from the database
In a project which I am doing there is a part which involves rendering images taken from the database. One image is rendered without a problem, but when I try to incrementally render all the rows from the database, there starts to be a problem:

main.component.ts

```<code>homeDetails() {

this.info.getHomeDetails().subscribe(

     gethomedetails =>  {

                    this.id = gethomedetails[0].id;
                    this.picByte = gethomedetails[0].picByte;

                 // for ( let i=0; i<=gethomedetails.length; i++) {
                  // this.id = homedetails[0].id;
                   this.picByte = gethomedetails[i].picByte;
                  this.id = gethomedetails[i].id;
                  console.log("id" + this.id);
                 // this.picByte = homedetails[i].picByte;
                 // }
                  this.retrievedImage = 'data:image/jpeg;base64,' + this.picByte;
                 // }
                  console.log("retrievedimage" + this.retrievedImage);

                  // for (let i=0; i<=this.id; i++) {

                  //   console.log("id" + i);
                  // }

                  // for (let i=0; i<=this.id; i++) {

                  //   this.picByte = homedetails[i].picByte;

                  // this.retrievedImage = 'data:image/jpeg;base64,' + this.picByte;
                  // console.log("retrievedimage" + this.retrievedImage);
                  // }

                  // this.images = homedetails
      }
)

   // return this.domSanitizer.bypassSecurityTrustResourceUrl(this.retrievedImage);
  }
</code>```

main.component.html

```<code> <img [src]="retrievedImage">    works just for one file
</code>```

Could you please point me out how I should do it?

Thank you.

答:
You could do this in a simple manner:

```<code>homeDetails() {
  this.info
    .getHomeDetails()
    .subscribe(data =>
        this.images = data.map(data => (
          {
            id: data.id,
            src: 'data:image/jpeg;base64,' + data.picByte
          }
        )
    )
}
</code>```

And then in the HTML

```<code><div *ngFor="let image of images">
    <img [src]="image.src">
</div>
</code>```

Body:
In a project which I am doing there is a part which involves rendering images taken from the database. One image is rendered without a problem, but when I try to incrementally render all the rows from the database, there starts to be a problem:

main.component.ts

homeDetails() {

this.info.getHomeDetails().subscribe(

     gethomedetails =>  {

                    this.id = gethomedetails[0].id;
                    this.picByte = gethomedetails[0].picByte;

                 // for ( let i=0; i<=gethomedetails.length; i++) {
                  // this.id = homedetails[0].id;
                   this.picByte = gethomedetails[i].picByte;
                  this.id = gethomedetails[i].id;
                  console.log("id" + this.id);
                 // this.picByte = homedetails[i].picByte;
                 // }
                  this.retrievedImage = 'data:image/jpeg;base64,' + this.picByte;
                 // }
                  console.log("retrievedimage" + this.retrievedImage);

                  // for (let i=0; i<=this.id; i++) {

                  //   console.log("id" + i);
                  // }

                  // for (let i=0; i<=this.id; i++) {

                  //   this.picByte = homedetails[i].picByte;

                  // this.retrievedImage = 'data:image/jpeg;base64,' + this.picByte;
                  // console.log("retrievedimage" + this.retrievedImage);
                  // }

                  // this.images = homedetails
      }
)

   // return this.domSanitizer.bypassSecurityTrustResourceUrl(this.retrievedImage);
  }

main.component.html

     works just for one file

Could you please point me out how I should do it?

Thank you.

Body:
You could do this in a simple manner:

homeDetails() {
  this.info
    .getHomeDetails()
    .subscribe(data =>
        this.images = data.map(data => (
          {
            id: data.id,
            src: 'data:image/jpeg;base64,' + data.picByte
          }
        )
    )
}

And then in the HTML

<div *ngFor="let image of images">
    <img [src]="image.src">
</div>


问:
Qt: XML stream does not write string directly
My problem is the following: my program works with projects and saves their settings in an XML file. It also creates viewable HTML files using the same QXmlStreamWriter class. However, because XML is supposed to skip particular symbols, a lot of characters are not propery represented in the HTML file. Is there a way to write any QString directly into an HTML file using an XML stream? Something like writeRaw() function?

Because I could not find solution to this problem, I had to create a QTextStream(xml->device()) and write into the stream. However, the stream seems to work assynchronously and, dpeending on the situation, sometimes it writes its part of code only after XML stream has finished writing the whole file. In HTML terms, it means, that a part of the code appears after  tag. Is there any other solution?

I would be grateful for any help!

答:
Okay, I solved my issue.

In the documentaion it says that QString::QString(QByteArray&) converts a byte array to a strong using QString::fromAscii() function. I replaced this part with QString::fromUtf8(myByteArray), and it worked!

ContentLicense: CC BY-SA 3.0


问:
Specifying Kestrel port with command line arg for .NET Core 3.1
Here's my Program.CS

```<code>public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    // Set properties and call methods on options
                })
                .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
                config.AddCommandLine(args);
            });
    }
</code>```

I am running the app via the following command:

```<code>dotnet run --server.urls http://localhost:59708
</code>```

However, the app will only listen on port 59707, not port 59708. I am trying to set the port with command line args so that I can run multiple instances of the app on separate static ports

答:
Call .UseKestrel() like this:

```<code>.UseKestrel((ctx, opt) =>
{
    var ipAddress = IPAddress.Parse("127.0.0.1")
    var port = 80;
    opt.Listen(ipAddress, port);
    // for HTTPS
    //opt.Listen(ipAddress, httpsPort, listenOptions =>
    //{
    //    listenOptions.UseHttps("certificate.pfx", "password");
    //});
}
</code>```

You can easily figure out how to parse your command line arguments. Options are almost endless...

HTH

Body:
Here's my Program.CS

public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    // Set properties and call methods on options
                })
                .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
                config.AddCommandLine(args);
            });
    }

I am running the app via the following command:

dotnet run --server.urls http://localhost:59708

However, the app will only listen on port 59707, not port 59708. I am trying to set the port with command line args so that I can run multiple instances of the app on separate static ports

Body:
Call .UseKestrel() like this:

.UseKestrel((ctx, opt) =>
{
    var ipAddress = IPAddress.Parse("127.0.0.1")
    var port = 80;
    opt.Listen(ipAddress, port);
    // for HTTPS
    //opt.Listen(ipAddress, httpsPort, listenOptions =>
    //{
    //    listenOptions.UseHttps("certificate.pfx", "password");
    //});
}

You can easily figure out how to parse your command line arguments. Options are almost endless...

HTH


问:
How to get current offset of stream or file descriptor?
In Node.js, is there any way of getting the current offset of a file descriptor or stream? Presently, it is possible to set the offset of a file descriptor, but there seems to be no way to get it.

In C, getting the offset of a file stream is done via ftell, and a file descriptor via lseek(fd, 0, SEEK_CUR).

Example

If a Node.js program needs to check whether there is prior data in a file after opening it in append mode, a call to ftell would help in this case. This can be done in C as follows:

#include <stdio.h>

int main() {
    FILE* f = fopen("test.txt", "a");
    fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
    fclose(f);
}
```

<p>Running the above program three times, <code>test.txt</code> becomes:</p>

```First line
Subsequent line
Subsequent line
```

Prior Art

GitHub issue filed for old version of node. The discussion mentions bytesWritten and bytesEmitted, neither of which is equivalent to ftell (in the above C example, the bytes written when the file is first opened is always 0). https://github.com/nodejs/node-v0.x-archive/issues/1527.

The fs-ext NPM package. Exposes the low-level lseek for use in Node.js. https://www.npmjs.com/package/fs-ext.

答:
The fs.read has position parameter.

```<code>fs.read(fd, buffer, offset, length, position, callback)
</code>```

The position parameter is important here.

Will this suffice your need unless I am not able to understand your question correctly?

Body:
In Node.js, is there any way of getting the current offset of a file descriptor or stream? Presently, it is possible to set the offset of a file descriptor, but there seems to be no way to get it.

In C, getting the offset of a file stream is done via ftell, and a file descriptor via lseek(fd, 0, SEEK_CUR).

Example

If a Node.js program needs to check whether there is prior data in a file after opening it in append mode, a call to ftell would help in this case. This can be done in C as follows:

#include <stdio.h>

int main() {
    FILE* f = fopen("test.txt", "a");
    fprintf(f, ftell(f) ? "Subsequent line\n" : "First line\n");
    fclose(f);
}

Running the above program three times, test.txt becomes:

First line
Subsequent line
Subsequent line

Prior Art

GitHub issue filed for old version of node. The discussion mentions bytesWritten and bytesEmitted, neither of which is equivalent to ftell (in the above C example, the bytes written when the file is first opened is always 0). https://github.com/nodejs/node-v0.x-archive/issues/1527.

The fs-ext NPM package. Exposes the low-level lseek for use in Node.js. https://www.npmjs.com/package/fs-ext.

Body:
The fs.read has position parameter.

fs.read(fd, buffer, offset, length, position, callback)

The position parameter is important here.

Will this suffice your need unless I am not able to understand your question correctly?


问:
Problem while reading a smartcard in browser
I have been using the PCSC library for years to read smartcards and have never had a problem.
I entered the same code, which I do not report because it is too long and is 100% functional, in an ASPX page. If I run the web application from Visual Studio 2019 on localhost everything is fine, if I run it on the server with Windows server 2019 essential I receive this error:
The Smart card resource manager is not running.
I don't understand why this difference. Thanks to those who can help me.

P.S. I don't know Java, but only c#

UPDATE. The SCardSvr service is started on the server, but when I use the PCSC class the service stops on its own on the server. Strange behaviour.........

答:
UPDATE

Based on the new information the OP wants to connect a Smart Card Reader that resides on a remote computer (the client).

To the best of my knowledge this requires either a VNC or an RDP connection from the client to the server, use of the smart card redirection mechanism, and then opening the ASPX webpage from a web browser session started during the remote desktop connection.

My answer below is not applicable in this scenario at all.

OLD ANSWER

I would first look at the Services list on the server computer. Ensure that both Smart Card service and the Smart Card Device Enumeration Service are running when you attempt the request.

This problem may also occur due to insufficient privileges on behalf of the user account running the application pool for your ASPX page.

When you run the web page from Visual Studio 2019 it executes using derived credentials (most likely your own user account), and this account may have more privileges than the specified application pool user account on the Windows Server 2019. This applies especially if you use Application Pool Identities.

If the problem is caused by lack of privileges, then see this ServerFault answer for details on how to use the sc.exe tool to configure the privileges.

Also note jdweng's comment: if you have not installed the necessary drivers for the smart card reader to the Windows Server 2019 computer then you will need to do so in addition to configuring the privileges. Otherwise even though the ASPX page were able to access the Smart Card Resource Manager, the card reader itself has not registered there-in and thus cannot be used.


问:
Spyder isn't opening after update
I updated my Spyder to version 4.0.1 then this happens:

```<code>
(base) C:\Users\Mehdi_2>conda run spyder

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 3718, in main
    mainwindow = run_spyder(app, options, args)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 3559, in run_spyder
    main.setup()
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 1010, in setup
    from spyder.plugins.ipythonconsole.plugin import IPythonConsole
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\plugins\ipythonconsole
\plugin.py", line 34, in <module>
    from zmq.ssh import tunnel as zmqtunnel
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\ssh\__init__.py", line 1,
 in <module>
    from zmq.ssh.tunnel import *
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\ssh\tunnel.py", line 26,
in <module>
    import paramiko
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\__init__.py", line 3
1, in <module>
    from paramiko.transport import SecurityOptions, Transport
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\transport.py", line
70, in <module>
    from paramiko.sftp_client import SFTPClient
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\sftp_client.py", lin
e 43, in <module>
    from paramiko.sftp_file import SFTPFile
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\sftp_file.py", line
68
    self._close(async=True)
                    ^
SyntaxError: invalid syntax
</code>```

I tried to use spyder --reset

I tried to reboot my system (I have 32-bit Win7)

But none of them actually works for me. What should I do?

答: Thanks to @CarlosCordoba for his help in the comments. I uninstalled Anaconda then reinstalled it and now problem is solved.</p>

Title: Spyder isn't opening after update

Body:
I updated my Spyder to version 4.0.1 then this happens:

(base) C:\Users\Mehdi_2>conda run spyder

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 3718, in main
    mainwindow = run_spyder(app, options, args)
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 3559, in run_spyder
    main.setup()
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\app\mainwindow.py", li
ne 1010, in setup
    from spyder.plugins.ipythonconsole.plugin import IPythonConsole
  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\plugins\ipythonconsole
\plugin.py", line 34, in <module>
    from zmq.ssh import tunnel as zmqtunnel
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\ssh\__init__.py", line 1,
 in <module>
    from zmq.ssh.tunnel import *
  File "C:\ProgramData\Anaconda3\lib\site-packages\zmq\ssh\tunnel.py", line 26,
in <module>
    import paramiko
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\__init__.py", line 3
1, in <module>
    from paramiko.transport import SecurityOptions, Transport
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\transport.py", line
70, in <module>
    from paramiko.sftp_client import SFTPClient
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\sftp_client.py", lin
e 43, in <module>
    from paramiko.sftp_file import SFTPFile
  File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\sftp_file.py", line
68
    self._close(async=True)
                    ^
SyntaxError: invalid syntax

I tried to use spyder --reset

I tried to reboot my system (I have 32-bit Win7)

But none of them actually works for me. What should I do?


问:
Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory
There is no solution, as i have searched a lot on moving my uploaded image into directory  here is my php code :

```<code><?php
  //Profile Image upload script
  if (isset($_FILES['profilepic'])) {
   if (((@$_FILES["profilepic"]["type"]=="image/jpeg") || (@$_FILES["profilepic"]["type"]=="image/png") || (@$_FILES["profilepic"]["type"]=="image/gif"))&&(@$_FILES["profilepic"]["size"] < 1048576)) //1 Megabyte
  {
   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $rand_dir_name = substr(str_shuffle($chars), 0, 15);
   $dir = "userdata/profile_pics/$rand_dir_name";
   mkdir($dir);
   move_uploaded_file($_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name".$_FILES["profilepic"]["name"]);
    $profile_pic_name = $_FILES["profilepic"]["tmp_name"];
    echo $profile_pic_name;
    $profile_pic_query = mysqli_query($conn,"UPDATE users2 SET profile_pic='$rand_dir_name/$profile_pic_name' WHERE username='$user'");

  }
  else
  {
      $msg5 =  "Invailid File! Your image must be no larger than 1MB and it must be either a .jpg, .jpeg, .png or .gif";
  }
  }

?>
</code>```

but when I try to upload image,it creates the random folder in userdata/profile_pics but it doesn't move the file into random folder directory i have also created a custom php.ini file with file_uploads = On, but i recieve the following warning when i submit the form :-

Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /home/rahulkapoor90/public_html/note.php on line 26

Warning: move_uploaded_file(): Unable to move '/tmp/phpO592dd' to 'userdata/profile_pics/zAGC9wOhVyoe3R5' in /home/rahulkapoor90/public_html/note.php on line 26
/tmp/phpO592dd

答:
Wasted few hours to get the correct cause. You can try 2 things

Verify your destination folder

```<code>`$destdir="YOUR-COMPLETE-DESTINATION-FOLDER/uploads/";

if(is_dir($destdir) && is_writable($destdir))
    {echo "<strong>UPLOAD DIRECTORY EXIST & WRITABLE</strong>";}
else
    {echo "<strong>ISSUE WITH UPLOAD DIRECTORY</strong>";}`
</code>```

Confirm 2nd parameter of move_uploaded_file is a file name NOT A DIRECTORY NAME

In my case this turned to be the issue
    if(move_uploaded_file($tempname,"$destdir/".$_FILES['profilepic']['name']"))
        {echo 'FILE UPLOADED SUCCESSFULLY';}
    else
        {echo "FAILED TO UPLOAD";}

Body:
There is no solution, as i have searched a lot on moving my uploaded image into directory  here is my php code :

<?php
  //Profile Image upload script
  if (isset($_FILES['profilepic'])) {
   if (((@$_FILES["profilepic"]["type"]=="image/jpeg") || (@$_FILES["profilepic"]["type"]=="image/png") || (@$_FILES["profilepic"]["type"]=="image/gif"))&&(@$_FILES["profilepic"]["size"] < 1048576)) //1 Megabyte
  {
   $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   $rand_dir_name = substr(str_shuffle($chars), 0, 15);
   $dir = "userdata/profile_pics/$rand_dir_name";
   mkdir($dir);
   move_uploaded_file($_FILES["profilepic"]["tmp_name"],"userdata/profile_pics/$rand_dir_name".$_FILES["profilepic"]["name"]);
    $profile_pic_name = $_FILES["profilepic"]["tmp_name"];
    echo $profile_pic_name;
    $profile_pic_query = mysqli_query($conn,"UPDATE users2 SET profile_pic='$rand_dir_name/$profile_pic_name' WHERE username='$user'");

  }
  else
  {
      $msg5 =  "Invailid File! Your image must be no larger than 1MB and it must be either a .jpg, .jpeg, .png or .gif";
  }
  }

?>

but when I try to upload image,it creates the random folder in userdata/profile_pics but it doesn't move the file into random folder directory i have also created a custom php.ini file with file_uploads = On, but i recieve the following warning when i submit the form :-

Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /home/rahulkapoor90/public_html/note.php on line 26

Warning: move_uploaded_file(): Unable to move '/tmp/phpO592dd' to 'userdata/profile_pics/zAGC9wOhVyoe3R5' in /home/rahulkapoor90/public_html/note.php on line 26
/tmp/phpO592dd

Body:
Wasted few hours to get the correct cause. You can try 2 things

Verify your destination folder

`$destdir="YOUR-COMPLETE-DESTINATION-FOLDER/uploads/";

if(is_dir($destdir) && is_writable($destdir))
    {echo "<strong>UPLOAD DIRECTORY EXIST & WRITABLE</strong>";}
else
    {echo "<strong>ISSUE WITH UPLOAD DIRECTORY</strong>";}`

Confirm 2nd parameter of move_uploaded_file is a file name NOT A DIRECTORY NAME

In my case this turned to be the issue
    if(move_uploaded_file($tempname,"$destdir/".$_FILES['profilepic']['name']"))
        {echo 'FILE UPLOADED SUCCESSFULLY';}
    else
        {echo "FAILED TO UPLOAD";}


答:
I think its very simple..

Just convert the  JSON object to string by using json.stringify()

replace your substrings i.e.  "varExchange" with name and "varPrice" with qty.

and again you can cast it into object.

Title: php Json remove double quotes for key and how to change name of the key


问:
How to get Azure Pipelines to recognize JavaFX dependency with Gradle
I have been unable to get Azure Pipelines to run the way I am expecting.

The project codebase is in Java, version 8 and is using the JavaFX Library.

I am trying to introduce continuous integration via Azure Pipelines. To do this I decided to use Gradle to manage project dependencies.

Here is the gradle.build file I am using to declare project dependencies.

```<code>/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.1.1/userguide/tutorial_java_projects.html
 */

plugins {
    // Apply the java plugin to add support for Java
    id 'java'

    // Apply the application plugin to add support for building a CLI application.
    id 'application'
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenLocal()
    mavenCentral()
    jcenter()
}

dependencies {
    // This dependency is used by the application.
    implementation 'com.google.guava:guava:28.1-jre'
    implementation 'de.dynamicfiles.projects.gradle.plugins:javafx-gradle-plugin:8.8.2'

    // Use JUnit Jupiter API for testing.
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'

    // Use JUnit Jupiter Engine for testing.
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2'
}

application {
    // Define the main class for the application.
    mainClassName = 'main.java.application.App'
}

test {
    // Use junit platform for unit tests
    useJUnitPlatform()
}
</code>```

This is the error I except when I run my pipeline. This is a run from my computer.

```<code>Code\SNR-Project\Anature> ./gradlew build

>Downloading https://services.gradle.org/distributions/gradle-6.1.1-bin.zip
>.........10%.........20%.........30%..........40%.........50%
>.........60%..........70%.........80%.........90%.........100%
>
>Welcome to Gradle 6.1.1!
>
>Here are the highlights of this release:
>
> - Reusable dependency cache
> - Configurable compilation order between Groovy/Kotlin/Java/Scala
> - New sample projects in Gradle's documentation
>
>For more details see https://docs.gradle.org/6.1.1/release-notes.html
>
>Starting a Gradle Daemon (subsequent builds will be faster)
>
> Task :compileTestJava FAILED
>
>Code\SNR-Project\Anature\src\test\java\applicationTests\AppTest.java:16: error: >cannot find symbol
>        asserNotNull(classUnderTest.getGreeting(), "app should have a greeting");
>        ^
>  symbol:   method asserNotNull(String,String)
>  location: class AppTest
>1 error
>
>FAILURE: Build failed with an exception.
>
>* What went wrong:
>Execution failed for task ':compileTestJava'.
> Compilation failed; see the compiler error output for details.
>
>* Try:
>Run with --stacktrace option to get the stack trace. Run with --info or --debug >option to get more log output. Run with --scan to get full insights.
>
>* Get more help at https://help.gradle.org
>
>BUILD FAILED in 31s
>6 actionable tasks: 6 executed
</code>```

Here is the error I am getting in when I run the pipeline. This is a run in a Microsoft hosted VM.

```<code>>##[section]Starting: Gradle
>==============================================================================
>Task         : Gradle
>Description  : Build using a Gradle wrapper script
>Version      : 2.163.0
>Author       : Microsoft Corporation
>Help         : >https://learn.microsoft.com/azure/devops/pipelines/tasks/build/gradle
>==============================================================================
>SYSTEMVSSCONNECTION exists true
>[command]/home/vsts/work/1/s/Anature/gradlew --refresh-dependencies build
>Downloading https://services.gradle.org/distributions/gradle-6.1.1-bin.zip
>.........10%.........20%.........30%..........40%.........50%
>.........60%..........70%.........80%.........90%.........100%
>
>Welcome to Gradle 6.1.1!
>
>Here are the highlights of this release:
>  - Reusable dependency cache
>  - Configurable compilation order between Groovy/Kotlin/Java/Scala
>  - New sample projects in Gradle's documentation
>
> For more details see https://docs.gradle.org/6.1.1/release-notes.html
>
> Starting a Gradle Daemon (subsequent builds will be faster)
>
> > Task :compileJava
> /home/vsts/work/1/s/Anature/src/main/java/application/Player.java:5: error: >package javafx.scene.image does not exist
> import javafx.scene.image.Image;
>                          ^
> /home/vsts/work/1/s/Anature/src/main/java/application/Player.java:12: error: >cannot find symbol
>   private Image sprite;
>           ^
>   symbol:   class Image
>   location: class Player
> 2 errors
>
> > Task :compileJava FAILED
>
> FAILURE: Build failed with an exception.
>
> * What went wrong:
> Execution failed for task ':compileJava'.
> > Compilation failed; see the compiler error output for details.
>
> * Try:
> Run with --stacktrace option to get the stack trace. Run with --info or -->debug option to get more log output. Run with --scan to get full insights.
>
> * Get more help at https://help.gradle.org
>
> BUILD FAILED in 14s
> 1 actionable task: 1 executed
> Error: The process '/home/vsts/work/1/s/Anature/gradlew' failed with exit >code 1
>     at ExecState._setResult (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:816:25)
>     at ExecState.CheckComplete (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:799:18)
>     at ChildProcess.<anonymous> (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:721:19)
>     at emitTwo (events.js:106:13)
>     at ChildProcess.emit (events.js:191:7)
>     at maybeClose (internal/child_process.js:920:16)
>     at Process.ChildProcess._handle.onexit (internal/child_process.js:230:5)
> No test result files matching /home/vsts/work/1/s/**/TEST-*.xml were found, >so publishing JUnit test results is being skipped.
> ##[error]Error: The process '/home/vsts/work/1/s/Anature/gradlew' failed with >exit code 1
> ##[section]Finishing: Gradle
</code>```

So the issue is that in the Pipeline it's throwing an error saying that a JavaFX import does not exist. When in theory

```<code>./gradle build
</code>```

should be installing the required libraries on the Microsoft VM to run the code.

Just in case anyone is interested here is my azure-pipelines.yaml

```<code>trigger:
  - master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: Gradle@2
  inputs:
    gradleWrapperFile: 'Anature/gradlew'
    workingDirectory: 'Anature'
    options: '--refresh-dependencies'
    tasks: 'build'
    publishJUnitResults: true
    testResultsFiles: '**/TEST-*.xml'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    sonarQubeRunAnalysis: false
</code>```

Here you can see I am trying to force install all the dependencies but still am getting a

```<code>package javafx.scene.image does not exist
</code>```

Here are some reference links:

For Azure Gradle task.
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/build/gradle?view=azure-devops

Azure VM Specs:
https://github.com/actions/virtual-environments/blob/master/images/linux/Ubuntu1804-README.md

Gradle dependency information:
https://docs.gradle.org/current/userguide/declaring_dependencies.html

Update:

I had to first figure out what an azure pipeline VM had stock on it and why JavaFX wasn't working.

Here is a link to the download Java 1.8 version that comes stock on the Azure VM.

http://repos.azul.com/azure-only/zulu/packages/zulu-8/8u222/

Once you download the Zulu package for java you will see that JavaFX was not apart of the Java download like it is for the Java JDK.

答:
You may try to install openjfx to see whether the issue persists:

sudo apt-get install openjfx

Body:
I have been unable to get Azure Pipelines to run the way I am expecting.

The project codebase is in Java, version 8 and is using the JavaFX Library.

I am trying to introduce continuous integration via Azure Pipelines. To do this I decided to use Gradle to manage project dependencies.

Here is the gradle.build file I am using to declare project dependencies.

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * User Manual available at https://docs.gradle.org/6.1.1/userguide/tutorial_java_projects.html
 */

plugins {
    // Apply the java plugin to add support for Java
    id 'java'

    // Apply the application plugin to add support for building a CLI application.
    id 'application'
}

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenLocal()
    mavenCentral()
    jcenter()
}

dependencies {
    // This dependency is used by the application.
    implementation 'com.google.guava:guava:28.1-jre'
    implementation 'de.dynamicfiles.projects.gradle.plugins:javafx-gradle-plugin:8.8.2'

    // Use JUnit Jupiter API for testing.
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.5.2'

    // Use JUnit Jupiter Engine for testing.
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.2'
}

application {
    // Define the main class for the application.
    mainClassName = 'main.java.application.App'
}

test {
    // Use junit platform for unit tests
    useJUnitPlatform()
}

This is the error I except when I run my pipeline. This is a run from my computer.

Code\SNR-Project\Anature> ./gradlew build

>Downloading https://services.gradle.org/distributions/gradle-6.1.1-bin.zip
>.........10%.........20%.........30%..........40%.........50%
>.........60%..........70%.........80%.........90%.........100%
>
>Welcome to Gradle 6.1.1!
>
>Here are the highlights of this release:
>
> - Reusable dependency cache
> - Configurable compilation order between Groovy/Kotlin/Java/Scala
> - New sample projects in Gradle's documentation
>
>For more details see https://docs.gradle.org/6.1.1/release-notes.html
>
>Starting a Gradle Daemon (subsequent builds will be faster)
>
> Task :compileTestJava FAILED
>
>Code\SNR-Project\Anature\src\test\java\applicationTests\AppTest.java:16: error: >cannot find symbol
>        asserNotNull(classUnderTest.getGreeting(), "app should have a greeting");
>        ^
>  symbol:   method asserNotNull(String,String)
>  location: class AppTest
>1 error
>
>FAILURE: Build failed with an exception.
>
>* What went wrong:
>Execution failed for task ':compileTestJava'.
> Compilation failed; see the compiler error output for details.
>
>* Try:
>Run with --stacktrace option to get the stack trace. Run with --info or --debug >option to get more log output. Run with --scan to get full insights.
>
>* Get more help at https://help.gradle.org
>
>BUILD FAILED in 31s
>6 actionable tasks: 6 executed

Here is the error I am getting in when I run the pipeline. This is a run in a Microsoft hosted VM.

>##[section]Starting: Gradle
>==============================================================================
>Task         : Gradle
>Description  : Build using a Gradle wrapper script
>Version      : 2.163.0
>Author       : Microsoft Corporation
>Help         : >https://learn.microsoft.com/azure/devops/pipelines/tasks/build/gradle
>==============================================================================
>SYSTEMVSSCONNECTION exists true
>[command]/home/vsts/work/1/s/Anature/gradlew --refresh-dependencies build
>Downloading https://services.gradle.org/distributions/gradle-6.1.1-bin.zip
>.........10%.........20%.........30%..........40%.........50%
>.........60%..........70%.........80%.........90%.........100%
>
>Welcome to Gradle 6.1.1!
>
>Here are the highlights of this release:
>  - Reusable dependency cache
>  - Configurable compilation order between Groovy/Kotlin/Java/Scala
>  - New sample projects in Gradle's documentation
>
> For more details see https://docs.gradle.org/6.1.1/release-notes.html
>
> Starting a Gradle Daemon (subsequent builds will be faster)
>
> > Task :compileJava
> /home/vsts/work/1/s/Anature/src/main/java/application/Player.java:5: error: >package javafx.scene.image does not exist
> import javafx.scene.image.Image;
>                          ^
> /home/vsts/work/1/s/Anature/src/main/java/application/Player.java:12: error: >cannot find symbol
>   private Image sprite;
>           ^
>   symbol:   class Image
>   location: class Player
> 2 errors
>
> > Task :compileJava FAILED
>
> FAILURE: Build failed with an exception.
>
> * What went wrong:
> Execution failed for task ':compileJava'.
> > Compilation failed; see the compiler error output for details.
>
> * Try:
> Run with --stacktrace option to get the stack trace. Run with --info or -->debug option to get more log output. Run with --scan to get full insights.
>
> * Get more help at https://help.gradle.org
>
> BUILD FAILED in 14s
> 1 actionable task: 1 executed
> Error: The process '/home/vsts/work/1/s/Anature/gradlew' failed with exit >code 1
>     at ExecState._setResult (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:816:25)
>     at ExecState.CheckComplete (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:799:18)
>     at ChildProcess.<anonymous> (/home/vsts/work/_tasks/Gradle_8d8eebd8-2b94->4c97-85af-839254cc6da4/2.163.0/node_modules/azure-pipelines-task->lib/toolrunner.js:721:19)
>     at emitTwo (events.js:106:13)
>     at ChildProcess.emit (events.js:191:7)
>     at maybeClose (internal/child_process.js:920:16)
>     at Process.ChildProcess._handle.onexit (internal/child_process.js:230:5)
> No test result files matching /home/vsts/work/1/s/**/TEST-*.xml were found, >so publishing JUnit test results is being skipped.
> ##[error]Error: The process '/home/vsts/work/1/s/Anature/gradlew' failed with >exit code 1
> ##[section]Finishing: Gradle

So the issue is that in the Pipeline it's throwing an error saying that a JavaFX import does not exist. When in theory

./gradle build

should be installing the required libraries on the Microsoft VM to run the code.

Just in case anyone is interested here is my azure-pipelines.yaml

trigger:
  - master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: Gradle@2
  inputs:
    gradleWrapperFile: 'Anature/gradlew'
    workingDirectory: 'Anature'
    options: '--refresh-dependencies'
    tasks: 'build'
    publishJUnitResults: true
    testResultsFiles: '**/TEST-*.xml'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    sonarQubeRunAnalysis: false

Here you can see I am trying to force install all the dependencies but still am getting a

package javafx.scene.image does not exist

Here are some reference links:

For Azure Gradle task.
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/build/gradle?view=azure-devops

Azure VM Specs:
https://github.com/actions/virtual-environments/blob/master/images/linux/Ubuntu1804-README.md

Gradle dependency information:
https://docs.gradle.org/current/userguide/declaring_dependencies.html

Update:

I had to first figure out what an azure pipeline VM had stock on it and why JavaFX wasn't working.

Here is a link to the download Java 1.8 version that comes stock on the Azure VM.

http://repos.azul.com/azure-only/zulu/packages/zulu-8/8u222/

Once you download the Zulu package for java you will see that JavaFX was not apart of the Java download like it is for the Java JDK.


问:
How to user predicates(which requires KVC) to CF object like ABRecord?
I'm devleloping an ABAddressBook based application.
I want to use predicates to evaluate or compare the objects in abaddressbook. But it seems like ABAddreesBook is a Core Fundation framework and does not support KVC. Does this mean that I can't use predicates in my application?

Or is there any other way to do things like predicates?

答:
The short answer is: you can't.

The long answer is: you can, but it'd be a lot of work.  I'd probably do something like this:

Recurse through all the NSExpressions of the predicate to aggregate all the -keyPath strings and store them in an array.  These will be the properties of the ABRecord objects that you'll be querying.

Iterate through your array of ABRecord objects and create a dictionary to represent each one.  This dictionary would have the recordID as well as the ABRecordCopyValue() value of each of the "keypaths" you want, keyed to the property name.

These dictionaries would be aggregated in an array.

This new array (of dictionaries) would be filtered with the predicate

After filtering, the reduced array of dictionaries would converted back into an array of ABRecord objects and returned.

This sounds like an interesting problem.  I'll think about this a bit more and perhaps come back and edit my answer.


问:
Xcode change/remove comment template
Recently I've been learning how to program C. For most of the time, I have been using the C version of Eclipse. Recently, I tried out Xcode. I am using a Mac running Mac OS X Lion - Xcode version 4.1.

There is one grievance I have: at the top of every file that I create, there is this little section of comments that I wish to remove or better yet, change.

When I create a file, something like this is put at the top of the file by default:

```<code>//
//  FILE.c
//  PROJECT NAME
//
//  Created by Martin Tuskevicius on DATE.
//  Copyright YEAR ORGANIZATION (my school name for some reason). All rights reserved.
//
</code>```

Obviously the things in capitals would be replaced with an actual value. For those of you have use, or have used Xcode, for programming C - do you know a way of how to change or remove these default comments?

I really appreciate any help.
Thanks!

答:
Please do not edit files inside Xcode, that will break the application signature and will cause Xcode to refuse to start up after the next restart or so.

Create an IDETemplateMacros.plist file containing a dictionary with a FILEHEADER key (string) instead.

You can put the file in

for all users on a single project by dropping it in your project's or workspace's xcshareddata folder (e.g. MyAppWorkspace.xcworkspace/xcshareddata/IDETemplateMacros.plist)

for yourself for a single project by copying it into e.g MyAppWorkspace.xcworkspace/xcuserdata/YOURNAMEHERE.xcuserdatad

global for all projects that you open in your account by dropping the file in ~/Library/Developer/Xcode/UserData/

Title: Xcode change/remove comment template

Body:
Recently I've been learning how to program C. For most of the time, I have been using the C version of Eclipse. Recently, I tried out Xcode. I am using a Mac running Mac OS X Lion - Xcode version 4.1.

There is one grievance I have: at the top of every file that I create, there is this little section of comments that I wish to remove or better yet, change.

When I create a file, something like this is put at the top of the file by default:

//
//  FILE.c
//  PROJECT NAME
//
//  Created by Martin Tuskevicius on DATE.
//  Copyright YEAR ORGANIZATION (my school name for some reason). All rights reserved.
//

Obviously the things in capitals would be replaced with an actual value. For those of you have use, or have used Xcode, for programming C - do you know a way of how to change or remove these default comments?

I really appreciate any help.
Thanks!


问:
How to delete from multiple tables in MySQL?
I am trying to delete from a few tables at once. I've done a bit of research, and came up with this

```<code>DELETE FROM `pets` p,
            `pets_activities` pa
      WHERE p.`order` > :order
        AND p.`pet_id` = :pet_id
        AND pa.`id` = p.`pet_id`
</code>```

However, I am getting this error

Uncaught Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'p, pets_activities pa...

I've never done a cross table delete before, so I'm inexperienced and stuck for now!

What am I doing wrong?

答: I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.

Body:
I am trying to delete from a few tables at once. I've done a bit of research, and came up with this

DELETE FROM `pets` p,
            `pets_activities` pa
      WHERE p.`order` > :order
        AND p.`pet_id` = :pet_id
        AND pa.`id` = p.`pet_id`

However, I am getting this error

Uncaught Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'p, pets_activities pa...

I've never done a cross table delete before, so I'm inexperienced and stuck for now!

What am I doing wrong?


问:
Cascading Parsers in Haskell
My parser type is

```<code>newtype Parser a = Parser { parse :: String -> Maybe (a,String) }
</code>```

I have two parsers :

1) a = (satisfy isAlpha)  that knows how to match the first alpha  numeric character in a string.

Running parse a "k345" gives Just ('k',"345")

2) b = many (satisfy isDigit) that  knows how to match any number of digits. Running parse b "1234 abc" gives Just ("1234"," abc")

Now I want to combine those two parsers and match a singe alphanumeric character followed by any number of digits.

I tried:

parse (a *> b) "k1234 7"   and got Just ("1234"," 7 "). Looks like the 'k' matched by the first parser a is gone from the output. How do I fix this problem ?

Thanks!

答:
It looks like this is working fine :

```<code>parse  (fmap  (:)  (satisfy isAlpha)  <*>  many (satisfy isDigit))   "k1234 7"
</code>```

And gives back what I wanted

```<code>Just ("k1234"," 7")
</code>```

Title: Cascading Parsers in Haskell

Body:
My parser type is

newtype Parser a = Parser { parse :: String -> Maybe (a,String) }

I have two parsers :

1) a = (satisfy isAlpha)  that knows how to match the first alpha  numeric character in a string.

Running parse a "k345" gives Just ('k',"345")

2) b = many (satisfy isDigit) that  knows how to match any number of digits. Running parse b "1234 abc" gives Just ("1234"," abc")

Now I want to combine those two parsers and match a singe alphanumeric character followed by any number of digits.

I tried:

parse (a *> b) "k1234 7"   and got Just ("1234"," 7 "). Looks like the 'k' matched by the first parser a is gone from the output. How do I fix this problem ?

Thanks!

Body:
It looks like this is working fine :

parse  (fmap  (:)  (satisfy isAlpha)  <*>  many (satisfy isDigit))   "k1234 7"

And gives back what I wanted

Just ("k1234"," 7")


问:
Merge a collection using the same key values
I have two collections with data to combine:

```<code>//1
  [
     [
       "date" => "2019-02-15",
       "clicks" => 1,
     ],
   ]
//2
[
     [
       "date" => "2019-02-15",
       "users" => 1,
     ],
   ]
</code>```

it is necessary that the collection elements (arrays) that have the same values for a particular key are combined

答:
$collectionOne = new Collection(['foo']);

$collectionTwo = new Collection(['bar']);

$collection = $collectionOne->merge($collectionTwo);

Body:
I have two collections with data to combine:

//1
  [
     [
       "date" => "2019-02-15",
       "clicks" => 1,
     ],
   ]
//2
[
     [
       "date" => "2019-02-15",
       "users" => 1,
     ],
   ]

it is necessary that the collection elements (arrays) that have the same values for a particular key are combined


问:
How to package a wheel for a library meant to run on python3.8 32bits on windows10?

Initial question (2020-02-15)

I'm building a python library: my_custom_library, with standard requirements (NumPy, pandas, librosa ...) and custom functions.

I would like to build a wheel of my_custom_library to then pip install this library on python3.8 32bits on windows10 on a machine with no access to internet (flash drive transfert). This install should be a "true" windows10 install and should not require WSL.

I would consider the packaging a success if I could produce one file my_custom_library-0.0.0-win32.whl similar to numpy-1.18.1-cp38-cp38-win32.whl on https://pypi.org/project/numpy/#files. This package is meant to stay private, I don't want to publish anything on pypi.

What is the best practice to build the wheel of my_custom_library for windows10 ?

What is the shortest list of commands to do that ?

From what I saw, it seems I need to build the wheel on the same OS as the OS where the wheel will be installed.

Can I build the wheel on a linux machine (ubuntu 18.04LTS) and install it on windows10 ?

If it's possible, what is the shortest list of commands to do that ?

Requirements (2020-02-17)

my_custom_library will import many well-known libraries including:

```<code>librosa==0.7.1
matplotlib==3.1.1
numpy==1.16.4
opencv-python==4.1.2.30
pandas==0.24.2
scikit-learn==0.21.3
scipy==1.3.2
</code>```

答:
Can I build the wheel on a linux machine (ubuntu 18.04LTS) and install it on windows10 ?

Pure Python library — yes. Actually a pure Python library doesn't need to be platform-specific at all, you can build a universal wheel or use sdist (source distribution).

But if the library has code written in C/C++ then no, you have to build it on an exact platform (processor architecture, minimal OS version, exact Python version). You can build 32-bit library on a 64-bit Windows using 32-bit Python. But not the other way around — you cannot build 64-bit library on a 32-bit Windows.

Body:
Initial question (2020-02-15)

I'm building a python library: my_custom_library, with standard requirements (NumPy, pandas, librosa ...) and custom functions.

I would like to build a wheel of my_custom_library to then pip install this library on python3.8 32bits on windows10 on a machine with no access to internet (flash drive transfert). This install should be a "true" windows10 install and should not require WSL.

I would consider the packaging a success if I could produce one file my_custom_library-0.0.0-win32.whl similar to numpy-1.18.1-cp38-cp38-win32.whl on https://pypi.org/project/numpy/#files. This package is meant to stay private, I don't want to publish anything on pypi.

What is the best practice to build the wheel of my_custom_library for windows10 ?

What is the shortest list of commands to do that ?

From what I saw, it seems I need to build the wheel on the same OS as the OS where the wheel will be installed.

Can I build the wheel on a linux machine (ubuntu 18.04LTS) and install it on windows10 ?

If it's possible, what is the shortest list of commands to do that ?

Requirements (2020-02-17)

my_custom_library will import many well-known libraries including:

librosa==0.7.1
matplotlib==3.1.1
numpy==1.16.4
opencv-python==4.1.2.30
pandas==0.24.2
scikit-learn==0.21.3
scipy==1.3.2


问:
Multiple controllers using unity's new input system
i'm trying to use the new unity's input system with multiple controllers.

I've tried creating input actions for each character but that didn't work.
all the characters are moving at the same time. it looks like the characters does not care about the controller but care about the input regardless the controller. maybe i need to wait for the final release of the input system. But, i really don't want to use the old system because i think it's going to be removed when the new input system is fully released.

答:
There is a component called PlayerInputManager which is used to "detect" when a new controller is connected / disconnected.

You have to provide it a prefab of the object (e.g. a character) you want to spawn whenever a player joins. This spawned prefab should have a PlayerInput component, which will be automatically registered on the input system as the controller you just plugged.
Now, each controller will control a different character.

By default, your inputs will be forwarded to your character via the PlayerInput component using SendMessage() but you can also use other options.

Check out the Input System Documentation


问:
codeigniter HMVC issue
I installed the codeigniter HMVC plugin and it's working fine for me but when I try to load any plugin I get the error

An Error Was Encountered

  Unable to locate the file: captcha_pi.php

Even if this file exists. I added one more plugin but it's the same. Do plugins work with HMVC?

答:
The problem is that captcha is not a plugin, it's a helper (the reference guide example loads it as a plugin).

So, all you need to do is:

```<code>$this->load->helper('captcha');
</code>```

instead of:

```<code>$this->load->plugin('captcha');
</code>```

Title: codeigniter HMVC issue

Body:
The problem is that captcha is not a plugin, it's a helper (the reference guide example loads it as a plugin).

So, all you need to do is:

$this->load->helper('captcha');

instead of:

$this->load->plugin('captcha');


问:
Concatenating on Windows throws "Invalid data found when processing input" while it works on Mac and Linux
I need to run a command with a nightly build of FFMPEG to report a bug on the concat protocol. I found it difficult to compile from source with libx264 support on Linux, and I want to spare my Mac computer, so I use the nightly build on Windows from Zeranoe.

I call this command to concatenate the files:

```<code>ffmpeg -safe 0 concat -i files_to_combine -vcodec libx264 show.mp4
</code>```

where files_to_combine is:

```<code>file ./short_DSC_0013.MOV
file ./short_DSC_0014.MOV
file ./short_DSC_0015.MOV
file ./short_DSC_0016.MOV
file ./short_DSC_0017.MOV
file ./short_DSC_0018.MOV
file ./short_DSC_0019.MOV
</code>```

I call this command from the directory containing the video files and files_to_combine.

On Windows with a nightly build, I get the error:

```
files_to_combine: Invalid data found when processing input
```

I changed file ./DSC_0013.MOV to these options, all with the same error:

```<code>file 'short_DSC_0013.MOV'
file '.\short_DSC_0013.MOV'
file 'F:\short_DSC_0013.MOV'
</code>```

How can I debug this error, or what is the syntax for concatenating on Windows with a nightly build?

Update with log-level 48

I ran the same command with -v 48 and got:

```
F:\brain squids>C:\Users\migue\Desktop\ffmpeg-20200211-f15007a-win64-static\bin\ffmpeg.exe -v 48 -i files_to_combine -vcodec libx264 show.mp4
ffmpeg version git-2020-02-11-f15007a Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.2.1 (GCC) 20200122
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt --enable-amf
  libavutil      56. 39.100 / 56. 39.100
  libavcodec     58. 68.102 / 58. 68.102
  libavformat    58. 38.100 / 58. 38.100
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 75.100 /  7. 75.100
  libswscale      5.  6.100 /  5.  6.100
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
Splitting the commandline.
Reading option '-v' ... matched as option 'v' (set logging level) with argument '48'.
Reading option '-i' ... matched as input url with argument 'files_to_combine'.
Reading option '-vcodec' ... matched as option 'vcodec' (force video codec ('copy' to copy stream)) with argument 'libx264'.
Reading option 'show.mp4' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option v (set logging level) with argument 48.
Successfully parsed a group of options.
Parsing a group of options: input url files_to_combine.
Successfully parsed a group of options.
Opening an input file: files_to_combine.
[NULL @ 0000021c781784c0] Opening 'files_to_combine' for reading
[file @ 0000021c78179580] Setting default whitelist 'file,crypto,data'
[AVIOContext @ 0000021c781817c0] Statistics: 182 bytes read, 0 seeks
files_to_combine: Invalid data found when processing input
```

The contents of files_to_combine is:

```
file 'short_DSC_0013.MOV'
file 'short_DSC_0014.MOV'
file 'short_DSC_0015.MOV'
file 'short_DSC_0016.MOV'
file 'short_DSC_0017.MOV'
file 'short_DSC_0018.MOV'
file 'short_DSC_0019.MOV'
```

Update because of wrong command

I had mistyped the command. The right command has a -f in front of concat, which I found because the accepted answer was able to make the command work in a similar environment:

```<code>ffmpeg -safe 0 -f concat -i files_to_combine -vcodec libx264 show.mp4
</code>```

答:
I tested it successfully on Windows 10:

(ffmpeg version N-95216-ge6625ca41f)

Videos 01.mp4, 02.mp4and .txt are in C:\Users\drake7\Desktop\

Content of files_to_combine.txt:

_

```<code>file 'C:\Users\drake7\Desktop\01.mp4'
file 'C:\Users\drake7\Desktop\02.mp4'
</code>```

Note: 02.mp4 is a copy of 01.mp4. For this quick test I wanted to keep it really simple.

.txt created with right-click > New > Text Document

(With my windows command prompt I am in C:\Users\drake7\Desktop\ffmpeg\bin)

```<code>"ffmpeg.exe" -f concat -safe 0 -i "C:\Users\drake7\Desktop\files_to_combine.txt" -vcodec libx264 "C:\Users\drake7\Desktop\show.mp4"
</code>```

Body:
I need to run a command with a nightly build of FFMPEG to report a bug on the concat protocol. I found it difficult to compile from source with libx264 support on Linux, and I want to spare my Mac computer, so I use the nightly build on Windows from Zeranoe.

I call this command to concatenate the files:

ffmpeg -safe 0 concat -i files_to_combine -vcodec libx264 show.mp4

where files_to_combine is:

file ./short_DSC_0013.MOV
file ./short_DSC_0014.MOV
file ./short_DSC_0015.MOV
file ./short_DSC_0016.MOV
file ./short_DSC_0017.MOV
file ./short_DSC_0018.MOV
file ./short_DSC_0019.MOV

I call this command from the directory containing the video files and files_to_combine.

On Windows with a nightly build, I get the error:

files_to_combine: Invalid data found when processing input

I changed file ./DSC_0013.MOV to these options, all with the same error:

file 'short_DSC_0013.MOV'
file '.\short_DSC_0013.MOV'
file 'F:\short_DSC_0013.MOV'

How can I debug this error, or what is the syntax for concatenating on Windows with a nightly build?

Update with log-level 48

I ran the same command with -v 48 and got:

F:\brain squids>C:\Users\migue\Desktop\ffmpeg-20200211-f15007a-win64-static\bin\ffmpeg.exe -v 48 -i files_to_combine -vcodec libx264 show.mp4
ffmpeg version git-2020-02-11-f15007a Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.2.1 (GCC) 20200122
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt --enable-amf
  libavutil      56. 39.100 / 56. 39.100
  libavcodec     58. 68.102 / 58. 68.102
  libavformat    58. 38.100 / 58. 38.100
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 75.100 /  7. 75.100
  libswscale      5.  6.100 /  5.  6.100
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100
Splitting the commandline.
Reading option '-v' ... matched as option 'v' (set logging level) with argument '48'.
Reading option '-i' ... matched as input url with argument 'files_to_combine'.
Reading option '-vcodec' ... matched as option 'vcodec' (force video codec ('copy' to copy stream)) with argument 'libx264'.
Reading option 'show.mp4' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option v (set logging level) with argument 48.
Successfully parsed a group of options.
Parsing a group of options: input url files_to_combine.
Successfully parsed a group of options.
Opening an input file: files_to_combine.
[NULL @ 0000021c781784c0] Opening 'files_to_combine' for reading
[file @ 0000021c78179580] Setting default whitelist 'file,crypto,data'
[AVIOContext @ 0000021c781817c0] Statistics: 182 bytes read, 0 seeks
files_to_combine: Invalid data found when processing input

The contents of files_to_combine is:

file 'short_DSC_0013.MOV'
file 'short_DSC_0014.MOV'
file 'short_DSC_0015.MOV'
file 'short_DSC_0016.MOV'
file 'short_DSC_0017.MOV'
file 'short_DSC_0018.MOV'
file 'short_DSC_0019.MOV'

Update because of wrong command

I had mistyped the command. The right command has a -f in front of concat, which I found because the accepted answer was able to make the command work in a similar environment:

ffmpeg -safe 0 -f concat -i files_to_combine -vcodec libx264 show.mp4

Body:
I tested it successfully on Windows 10:

(ffmpeg version N-95216-ge6625ca41f)

Videos 01.mp4, 02.mp4and .txt are in C:\Users\drake7\Desktop\

Content of files_to_combine.txt:

_

file 'C:\Users\drake7\Desktop\01.mp4'
file 'C:\Users\drake7\Desktop\02.mp4'

Note: 02.mp4 is a copy of 01.mp4. For this quick test I wanted to keep it really simple.

.txt created with right-click > New > Text Document

(With my windows command prompt I am in C:\Users\drake7\Desktop\ffmpeg\bin)

"ffmpeg.exe" -f concat -safe 0 -i "C:\Users\drake7\Desktop\files_to_combine.txt" -vcodec libx264 "C:\Users\drake7\Desktop\show.mp4"


问:
Find data inside the nested ORM in Django
```<code>class Post(models.Model):
    POST_TYPE =(
        ("video","video"),
        ("pic","pic"),
    )
    upload_by = models.ForeignKey(User,on_delete=models.CASCADE)
    caption = models.TextField()
    post_type = models.CharField(max_length=100,choices=POST_TYPE)
    media = models.FileField(upload_to='posts/')
    created_at = models.DateTimeField(auto_now_add=True)

class PostLikes(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)
    like_by = models.ForeignKey(User,on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is My models.py file and i want to find that if current login user is liked the post or not like this in my templates. I'm doing this in my templates file

```<code>{% if request.user in i.postlikes_set.all%}
</code>```

but i know it's wrong can anybody solve this problem?
I want to do this in my templates

```<code><a class="post-like-btn" href="#" {% if request.user in i.postlikes_set.all%} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}>
</code>```

答:
IMHO the check whether a user likes a Post or not is something to be done in a view.

Looking at your post I think you are displaying a list of Posts in your template where each item is either liked or not liked by the user. What you could do is annotate each post with this information in the view and then use this information in your template. E.g.

```<code>#views.py

from django.db.models import OuterRef, Exists

def list_posts(request):
    user = request.user

    my_likes = PostLikes.objects.filter(
        post = OuterRef('pk'),
        like_by = user
    )

    posts = Post.objects.annotate(like_by_user=Exists(my_likes))

    context = {'posts': posts}

    return render(request, 'yourtemplate.html', context)
</code>```

And then in your template you could do

```<code><a class="post-like-btn" href="#" {% if i.like_by_user %} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}
</code>```

Body:
class Post(models.Model):
    POST_TYPE =(
        ("video","video"),
        ("pic","pic"),
    )
    upload_by = models.ForeignKey(User,on_delete=models.CASCADE)
    caption = models.TextField()
    post_type = models.CharField(max_length=100,choices=POST_TYPE)
    media = models.FileField(upload_to='posts/')
    created_at = models.DateTimeField(auto_now_add=True)

class PostLikes(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)
    like_by = models.ForeignKey(User,on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

This is My models.py file and i want to find that if current login user is liked the post or not like this in my templates. I'm doing this in my templates file

{% if request.user in i.postlikes_set.all%}

but i know it's wrong can anybody solve this problem?
I want to do this in my templates

Body:
IMHO the check whether a user likes a Post or not is something to be done in a view.

Looking at your post I think you are displaying a list of Posts in your template where each item is either liked or not liked by the user. What you could do is annotate each post with this information in the view and then use this information in your template. E.g.

#views.py

from django.db.models import OuterRef, Exists

def list_posts(request):
    user = request.user

    my_likes = PostLikes.objects.filter(
        post = OuterRef('pk'),
        like_by = user
    )

    posts = Post.objects.annotate(like_by_user=Exists(my_likes))

    context = {'posts': posts}

    return render(request, 'yourtemplate.html', context)

And then in your template you could do

<a class="post-like-btn" href="#" {% if i.like_by_user %} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}


问:
How to fetch only first 4 months of data from past 3 years via SQL query?
I would like to fetch the first 4 months of data in the past 3 years with a SQL query. Could someone please help me with this?</p>

答:
You can use DATE_ADD() function with month and year  datepart arguments

```<code>SELECT *
  FROM tab
 WHERE CAST( date_inserted  AS DATE)
       BETWEEN CAST( DATEADD(year, -3, GETDATE()) AS DATE)
           AND CAST( DATEADD(month, 4, DATEADD(year, -3, GETDATE())) AS DATE)
</code>```

Demo

where GETDATE() represents the current timestamp value of the DBMS

Body:
You can use DATE_ADD() function with month and year  datepart arguments

SELECT *
  FROM tab
 WHERE CAST( date_inserted  AS DATE)
       BETWEEN CAST( DATEADD(year, -3, GETDATE()) AS DATE)
           AND CAST( DATEADD(month, 4, DATEADD(year, -3, GETDATE())) AS DATE)

Demo

where GETDATE() represents the current timestamp value of the DBMS


问:
Regex Match containing string between 2 characters
I'm trying to match a string in an HTTP page between ><.

I'm having trouble with the first > as it also matches subsequent chars. eg. in this example

```<code><a href="https://stackoverflow.com" class="-logo js-gps-track"
                        data-gps-track="top_nav.click({is_current:false, location:3, destination:8})">
                        <span class="-img _glyph">Stack Overflow</span>
                    </a>
</code>```

I would only want to match Stack Overflow. I've currently got \>([^\>].*Stack Overflow.*)\<
but that matches everything after the first > ie

```<code>><span class="-img _glyph">Stack Overflow<
</code>```

Any help would be great

答:
Try using lookbehind and lookahead assertions, as in this regex: (?<=>)Stack Overflow(?=<)

const text = `
                        Stack Overflow
                    `;
const regex = /(?<=>)Stack Overflow(?=<)/g;
const found = text.match(regex);

console.log(found);```

Body:
I'm trying to match a string in an HTTP page between ><.

I'm having trouble with the first > as it also matches subsequent chars. eg. in this example

                        Stack Overflow

I would only want to match Stack Overflow. I've currently got \>([^\>].*Stack Overflow.*)\<
but that matches everything after the first > ie

>Stack Overflow<

Any help would be great

Body:
Try using lookbehind and lookahead assertions, as in this regex: (?<=>)Stack Overflow(?=<)

const text = `<a href="https://stackoverflow.com" class="-logo js-gps-track"
                        data-gps-track="top_nav.click({is_current:false, location:3, destination:8})">
                        <span class="-img _glyph">Stack Overflow</span>
                    </a>`;
const regex = /(?<=>)Stack Overflow(?=<)/g;
const found = text.match(regex);

console.log(found);


问:
Create Json Arrays and List with SharedPreferences
I have been using shared_preferences to create and write in Json Files. The Problem i facing is i dont know how to create a Json Array and a List in shared_preferences.

I want to save and read a Json List.

```<code>  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key));
  }

  save(String key, value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(key, json.encode(value));
  }

  remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }
} ```

```

答:
Example on DartPad.

Save a list to SharedPreferences with setStringList:

```<code>  const String key = "users";

  List<User> users = [User(name: "tester")];
  List<String> jsonList = users.map((user) => user.toJson()).toList();
  SharedPreferences prefs = await SharedPreferences.getInstance();

  prefs.setStringList(key, jsonList);

</code>```

Read a list from SharedPreferences with getStringList:

```<code>  jsonList = prefs.getStringList(key);

  users = jsonList.map((json) => User.fromJson(json)).toList();
</code>```

The user class with json convert: JSON and serialization

```<code>class User {
  String name;
  int age;

  User({
    this.name,
    this.age,
  });

  factory User.fromJson(String str) => User.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory User.fromMap(Map<String, dynamic> json) => User(
        name: json["name"],
        age: json["age"],
      );

  Map<String, dynamic> toMap() => {
        "name": name,
        "age": age,
      };
}
</code>```

Body:
I have been using shared_preferences to create and write in Json Files. The Problem i facing is i dont know how to create a Json Array and a List in shared_preferences.

I want to save and read a Json List.

  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key));
  }

  save(String key, value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(key, json.encode(value));
  }

  remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }
} ```

Body:
Example on DartPad.

Save a list to SharedPreferences with setStringList:

  const String key = "users";

  List<User> users = [User(name: "tester")];
  List<String> jsonList = users.map((user) => user.toJson()).toList();
  SharedPreferences prefs = await SharedPreferences.getInstance();

  prefs.setStringList(key, jsonList);

Read a list from SharedPreferences with getStringList:

  jsonList = prefs.getStringList(key);

  users = jsonList.map((json) => User.fromJson(json)).toList();

The user class with json convert: JSON and serialization

class User {
  String name;
  int age;

  User({
    this.name,
    this.age,
  });

  factory User.fromJson(String str) => User.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory User.fromMap(Map<String, dynamic> json) => User(
        name: json["name"],
        age: json["age"],
      );

  Map<String, dynamic> toMap() => {
        "name": name,
        "age": age,
      };
}