问:
How to combine css with selectors
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

```<code>body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
</code>```

or

```<code>@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}
</code>```

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

答:
You can do your code cleaner using modern sass(scss). The code will be:</p>

```<code>body{
   #gform_wrapper_14{
      .gform_footer{
         input[type=submit] {
            border-radius:0px;
            background:#e89d53;
         }
      }
   }
   #gform_wrapper_15{
      @extend #gform_wrapper_14;
   }
   #gform_wrapper_17{
      @extend #gform_wrapper_14;
   }
}
</code>```

Title: How to combine css with selectors

Body:
I need to clean up my CSS file and remove some bloat.  I know it's possible to combine classes and ids by separating them with commas.  However, I'm not sure how to go about combining them when they have more complex selectors like the ones below.

Any help would be appreciated.  Thank you.

body #gform_wrapper_14 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_15 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}
body #gform_wrapper_17 .gform_footer input[type=submit] {
    border-radius:0px;
    background:#e89d53;
}

or

@media only screen and (min-width: 641px) {
    body #gform_wrapper_14 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_15 {
      max-width: 80%;
      margin: 0 auto;
     }
    body #gform_wrapper_17 {
      max-width: 80%;
      margin: 0 auto;
     }
    .hor-address {
        width:500px;
    }
}

Clarification:  I have multiple #gform_wrapper_xx objects (generated by 3rd party Wordpress plugin) and but I don't want to change all of them.  I just want to change these 3.

Body:
You can do your code cleaner using modern sass(scss). The code will be:

body{
   #gform_wrapper_14{
      .gform_footer{
         input[type=submit] {
            border-radius:0px;
            background:#e89d53;
         }
      }
   }
   #gform_wrapper_15{
      @extend #gform_wrapper_14;
   }
   #gform_wrapper_17{
      @extend #gform_wrapper_14;
   }
}


来源: stackexchange

问:
C# Load/Unload plugins
Is there anyway to have ClassLibrary plugins which can be loaded/unloaded. The only way I have found is using an AppDomain but that defeats the purpose as the plugin cannot use the hosts API.</p>

答:
Yes I've done this with 1.1 2.0 and 3.5.  Plus MS now has MEF which is probably what you want.

http://msdn.microsoft.com/en-us/magazine/ee291628.aspx

ContentLicense: CC BY-SA 3.0

Title: C# Load/Unload plugins


问:
How to pass input values to Scheduled Jenkins pipeline job?
I have a Jenkins Pipeline which doesn't have any build parameter. But has input template inside. So, when a job is started using Build now, it gets triggered and waits for user input through Input Requested and the options are populated as choices.

This is working fine, when i run manually.
But, I want to enable default values for input choice variable, so that when a scheduled job starts, it will not wait for user input (through Input Requested) and continue to use default values.

My input template looks like this.

```<code>env.cluster_to_select = input(
                        id: 'cluster_to_select', message: 'Select a choice',
                        parameters: [
                                 choice(name: 'clusters',
                                       choices: env.list_files, //can take from populated string
                                       description: 'Based on cluster selection, nodes are shown'
                                        )
                        ]
                )
</code>```

How to know if the job is triggered via scheduler and pass default values for input.

答:
You can wrap the input in a timeout block, which itself should be in a try block. Then catch the exception, check whether it timed out or was aborted by a user, and proceed accordingly with the default parameters or abort the build.

```<code>env.cluster_to_select = try {
                            timeout(time: 120, unit: 'SECONDS') {
                                input(
                                    id: 'cluster_to_select', message: 'Select a choice',
                                    parameters: [
                                        choice(name: 'clusters',
                                            choices: env.list_files, //can take from populated string
                                            description: 'Based on cluster selection, nodes are shown'
                                            )
                                        ]
                                    )
                                }
                            }   catch(err) { // timeout reached or input aborted by user
                                def user = err.getCauses()[0].getUser()
                                if (user.toString() == 'SYSTEM') { // SYSTEM is timeout
                                    echo('Using default parameters')
                                } else {
                                    currentBuild.result = 'ABORTED'
                                    error("Pipeline aborted by: [${user}]")
                                }
                            }
</code>```

See Pipeline: How to add an input step, with timeout, that continues if timeout is reached, using a default value.

ContentLicense: CC BY-SA 4.0

Body:
I have a Jenkins Pipeline which doesn't have any build parameter. But has input template inside. So, when a job is started using Build now, it gets triggered and waits for user input through Input Requested and the options are populated as choices.

This is working fine, when i run manually.
But, I want to enable default values for input choice variable, so that when a scheduled job starts, it will not wait for user input (through Input Requested) and continue to use default values.

My input template looks like this.

env.cluster_to_select = input(
                        id: 'cluster_to_select', message: 'Select a choice',
                        parameters: [
                                 choice(name: 'clusters',
                                       choices: env.list_files, //can take from populated string
                                       description: 'Based on cluster selection, nodes are shown'
                                        )
                        ]
                )

How to know if the job is triggered via scheduler and pass default values for input.

Body:
You can wrap the input in a timeout block, which itself should be in a try block. Then catch the exception, check whether it timed out or was aborted by a user, and proceed accordingly with the default parameters or abort the build.

env.cluster_to_select = try {
                            timeout(time: 120, unit: 'SECONDS') {
                                input(
                                    id: 'cluster_to_select', message: 'Select a choice',
                                    parameters: [
                                        choice(name: 'clusters',
                                            choices: env.list_files, //can take from populated string
                                            description: 'Based on cluster selection, nodes are shown'
                                            )
                                        ]
                                    )
                                }
                            }   catch(err) { // timeout reached or input aborted by user
                                def user = err.getCauses()[0].getUser()
                                if (user.toString() == 'SYSTEM') { // SYSTEM is timeout
                                    echo('Using default parameters')
                                } else {
                                    currentBuild.result = 'ABORTED'
                                    error("Pipeline aborted by: [${user}]")
                                }
                            }

See Pipeline: How to add an input step, with timeout, that continues if timeout is reached, using a default value.


问:
HTML Input Time but No Hour Rollover
I'm looking for an HTML element that stores time, but not the time of day, just hours:minutes:seconds.  So if something took 40 hours, 10 minutes, I want to be able to enter 40:10:00. I tried using an input time element in my html as below, but it operates as a clock, only letting you enter times of day (roll over at 12 hours, AM/PM label, etc.).  Is there an element that I can use for this?  Or is it possible to adjust the input/time properties so it behaves this way (looking over the properties I don't think so; there is a max setting but it didn't work for me)?

Alternatively I'm planning on using three input-number fields with max/min settings to simulate the idea, but that's obviously tougher to handle.  If there is a better solution please let me know.  Thank you.

```<code><!DOCTYPE html>
<html>
<body>
<input type="time" id="myTime" value="22:15:00">

</body>
</html>
</code>```

答:
how about this input type time, using min and max? </p>

```<code><input type="time" id="appt" name="appt"
       min="09:00" max="18:00" required>
</code>```

Title: HTML Input Time but No Hour Rollover

Body:
I'm looking for an HTML element that stores time, but not the time of day, just hours:minutes:seconds.  So if something took 40 hours, 10 minutes, I want to be able to enter 40:10:00. I tried using an input time element in my html as below, but it operates as a clock, only letting you enter times of day (roll over at 12 hours, AM/PM label, etc.).  Is there an element that I can use for this?  Or is it possible to adjust the input/time properties so it behaves this way (looking over the properties I don't think so; there is a max setting but it didn't work for me)?

Alternatively I'm planning on using three input-number fields with max/min settings to simulate the idea, but that's obviously tougher to handle.  If there is a better solution please let me know.  Thank you.

<!DOCTYPE html>

<input type="time" id="myTime" value="22:15:00">

Body:
how about this input type time, using min and max?

<input type="time" id="appt" name="appt"
       min="09:00" max="18:00" required>


问:
How to filter and select multiple columns in pandas
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

```<code>dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]
</code>```

答:
```<code>import pandas as pd

dw = pd.DataFrame([
  {'Name': 'A', 'Year of Rank':1992, 'Rank': 1},
  {'Name': 'El Toro', 'Year of Rank':1993, 'Rank': 2},
  {'Name': 'C', 'Year of Rank':1994, 'Rank': 3}])

dw[dw.Name == 'El Toro'][['Name', 'Year of Rank']]
</code>```

Like this?

Next time you try provide more context like a dummy dataframe.

Body:
I can't select and filter multiple columns together in Pandas. 'Name' and 'Year of Rank' are column names. Thank you!

dw[dw.Name=='El Toro' & dw['Name', 'Year of Rank']]

Body:
import pandas as pd

dw = pd.DataFrame([
  {'Name': 'A', 'Year of Rank':1992, 'Rank': 1},
  {'Name': 'El Toro', 'Year of Rank':1993, 'Rank': 2},
  {'Name': 'C', 'Year of Rank':1994, 'Rank': 3}])

dw[dw.Name == 'El Toro'][['Name', 'Year of Rank']]

Like this?

Next time you try provide more context like a dummy dataframe.


问:
'Node' undeclared (first use in this function) in DevC++
I have following code to insert an element in LinkedList. I havebeen following tutorials and I am unable to spot error in this code.

I am using DEVC++ and it gives me a compile time error that says:
    [Error] 'Node' undeclared (first use in this function)

```<code> #include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct Node{
 int data;
 struct Node* next;
};
struct Node* head;  //global variable
int main(){
    head = NULL;  //empty list
    int n, i, x;
    printf("How many numbers would you like to enter");
    scanf("%d", &n);
    for(i=0; i<n; i++){
        printf("Enter the number you want to add to list:");
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}

void Insert(int x){
Node* temp= (Node*)malloc(sizeof(struct Node)); //I get error here
temp->data = x;
//temp->next = NULL; //redundant
//if(head!= NULL){
temp->next = head;  //temp.next will point to null when head is null nd otherwise what head was pointing to
//}
head = temp;
}

void Print(){
    struct Node* temp1 = head;  //we dont want tomodify head so store it in atemp. bariable and then traverse
    while(temp1 != NULL){
         printf(" %d", temp1->data);
         temp1= temp1->next;
    }
    printf("\n");
}
</code>```

答: Change Node* temp= (Node*)malloc(sizeof(struct Node)) to struct Node* temp = (struct Node*)malloc(sizeof(struct Node))

Body:
I have following code to insert an element in LinkedList. I havebeen following tutorials and I am unable to spot error in this code.

I am using DEVC++ and it gives me a compile time error that says:
    [Error] 'Node' undeclared (first use in this function)

 #include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct Node{
 int data;
 struct Node* next;
};
struct Node* head;  //global variable
int main(){
    head = NULL;  //empty list
    int n, i, x;
    printf("How many numbers would you like to enter");
    scanf("%d", &n);
    for(i=0; i<n; i++){
        printf("Enter the number you want to add to list:");
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}

void Insert(int x){
Node* temp= (Node*)malloc(sizeof(struct Node)); //I get error here
temp->data = x;
//temp->next = NULL; //redundant
//if(head!= NULL){
temp->next = head;  //temp.next will point to null when head is null nd otherwise what head was pointing to
//}
head = temp;
}

void Print(){
    struct Node* temp1 = head;  //we dont want tomodify head so store it in atemp. bariable and then traverse
    while(temp1 != NULL){
         printf(" %d", temp1->data);
         temp1= temp1->next;
    }
    printf("\n");
}


问:
text-file manipulation in bash
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

```<code>cat data.txt | dot -Tpng > image.png
</code>```

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

答:
You could execute your commands using a list {…}:

```<code>{ echo 'digraph {'; cat data.txt; echo '}'; } | dot -Tpng > image.png
</code>```

Title: text-file manipulation in bash

Body:
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

cat data.txt | dot -Tpng > image.png

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

Body:
You could execute your commands using a list {…}:

{ echo 'digraph {'; cat data.txt; echo '}'; } | dot -Tpng > image.png


问:
Presto: How to read from s3 an entire bucket that is partitioned in sub-folders?
I need to read using presto from s3 an entire dataset that sits in "bucket-a". But, inside the bucket, the data was saved in sub-folders by year. So I have a bucket that looks like that:

Bucket-a>2017>data

Bucket-a>2018>more data

Bucket-a>2019>more data

All the above data is the same table but saved this way in s3. Notice that in the bucket-a itself there is no data, just inside each folder.

What I have to do is read all the data from the bucket as a single table adding a year as column or partition.

I tried doing this way, but didn't work:

```<code>CREATE TABLE hive.default.mytable (
  col1 int,
  col2 varchar,
  year int
)
WITH (
  format = 'json',
  partitioned_by = ARRAY['year'],
  external_location = 's3://bucket-a/'--also tryed 's3://bucket-a/year/'

)
</code>```

and also

```<code>CREATE TABLE hive.default.mytable (
  col1 int,
  col2 varchar,
  year int
)
WITH (
  format = 'json',
  bucketed_by = ARRAY['year'],
  bucket_count = 3,
  external_location = 's3://bucket-a/'--also tryed's3://bucket-a/year/'
)
</code>```

All of the above didn't work.

I have seen people writing with partitions to s3 using presto, but what I'm trying to do is the opposite: read from s3 data that is already splitted in folders as single table.

Thanks.

答:
If your folders were following Hive partition folder naming convention (year=2019/), you could declare the table as partitioned and just use system. sync_partition_metadata procedure in Presto.

Now, your folders do not follow the convention, so you need to register each one individually as a partition using system.register_partition procedure (will be available in Presto 330, about to be released). (The alternative to register_partition is to run appropriate ADD PARTITION in Hive CLI.)

Body:
I need to read using presto from s3 an entire dataset that sits in "bucket-a". But, inside the bucket, the data was saved in sub-folders by year. So I have a bucket that looks like that:

Bucket-a>2017>data

Bucket-a>2018>more data

Bucket-a>2019>more data

All the above data is the same table but saved this way in s3. Notice that in the bucket-a itself there is no data, just inside each folder.

What I have to do is read all the data from the bucket as a single table adding a year as column or partition.

I tried doing this way, but didn't work:

CREATE TABLE hive.default.mytable (
  col1 int,
  col2 varchar,
  year int
)
WITH (
  format = 'json',
  partitioned_by = ARRAY['year'],
  external_location = 's3://bucket-a/'--also tryed 's3://bucket-a/year/'

)

and also

CREATE TABLE hive.default.mytable (
  col1 int,
  col2 varchar,
  year int
)
WITH (
  format = 'json',
  bucketed_by = ARRAY['year'],
  bucket_count = 3,
  external_location = 's3://bucket-a/'--also tryed's3://bucket-a/year/'
)

All of the above didn't work.

I have seen people writing with partitions to s3 using presto, but what I'm trying to do is the opposite: read from s3 data that is already splitted in folders as single table.

Thanks.


问:
Find the cycle time of a ticket number for different intervals
```<code>TicketNo    ActionDate                  OldStatus    NewStatus      CycleTime/Sec
1001        2014-02-14 10:17:05.000     Assigned     InProgress     -
1001        2014-03-05 02:03:44.000     InProgress   Reply          1611999
1001        2014-03-11 10:00:14.000     Reply        Resolved       546990
1002        2015-03-20 04:44:14.000     InProgress   Reply          -
1002        2015-03-21 05:40:02.000     Reply        Resolved       89748
</code>```

I have to calculate cycle time for every change in status of the ticket.

In the example above, i am trying to calculate the seconds from action date when the ticket is routed from old status to new status.

I tried using ranking function but did not get the output in wanted.

select
*
,row_number() over (partition by a.ticketno, a.oldstatus  order by a. actiondate ) rn

from Ticketing a

I would really appreciate if anyone can suggest some ideas how to solve this calculation.

答:
The easiest way to do this is using LAG. You can read more about the LAG function here. https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver15

Here is a fully functioning example.

```<code>declare @Something table
(
    TicketNo int
    , ActionDate datetime
    , OldStatus varchar(50)
    , NewStatus varchar(50)
)

insert @Something values
(1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

select s.*
    , CycleTimeSeconds = datediff(second, lag(ActionDate, 1) over(partition by TicketNo order by ActionDate), s.ActionDate)
from @Something s
</code>```

--EDIT--

Here is a version that will work with Sql Server 2008 (You really should consider upgrading since that version is no longer supported).

```<code>select s.*
    , CycleTimeSeconds = datediff(second, MyLag.ActionDate, s.ActionDate)
from @Something s
outer apply
(
    select top 1 ActionDate
    from @Something s2
    where s2.TicketNo = s.TicketNo
        and s2.ActionDate < s.ActionDate
    order by ActionDate desc
) MyLag
</code>```

Body:
TicketNo    ActionDate                  OldStatus    NewStatus      CycleTime/Sec
1001        2014-02-14 10:17:05.000     Assigned     InProgress     -
1001        2014-03-05 02:03:44.000     InProgress   Reply          1611999
1001        2014-03-11 10:00:14.000     Reply        Resolved       546990
1002        2015-03-20 04:44:14.000     InProgress   Reply          -
1002        2015-03-21 05:40:02.000     Reply        Resolved       89748

I have to calculate cycle time for every change in status of the ticket.

In the example above, i am trying to calculate the seconds from action date when the ticket is routed from old status to new status.

I tried using ranking function but did not get the output in wanted.

select
*
,row_number() over (partition by a.ticketno, a.oldstatus  order by a. actiondate ) rn

from Ticketing a

I would really appreciate if anyone can suggest some ideas how to solve this calculation.

Body:
The easiest way to do this is using LAG. You can read more about the LAG function here. https://learn.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver15

Here is a fully functioning example.

declare @Something table
(
    TicketNo int
    , ActionDate datetime
    , OldStatus varchar(50)
    , NewStatus varchar(50)
)

insert @Something values
(1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

select s.*
    , CycleTimeSeconds = datediff(second, lag(ActionDate, 1) over(partition by TicketNo order by ActionDate), s.ActionDate)
from @Something s

--EDIT--

Here is a version that will work with Sql Server 2008 (You really should consider upgrading since that version is no longer supported).

select s.*
    , CycleTimeSeconds = datediff(second, MyLag.ActionDate, s.ActionDate)
from @Something s
outer apply
(
    select top 1 ActionDate
    from @Something s2
    where s2.TicketNo = s.TicketNo
        and s2.ActionDate < s.ActionDate
    order by ActionDate desc
) MyLag


问:
VBA macro if cell contains a specific value then return specific texts to a certain range
I have an Excel file that tracks engine status from Sales and Production departments. Columns A - M in the workbook contain data necessary to deem the engine status. Columns N - AR are used to track engine status with the following column order: Sales, Production, Day 1, Status. That repeats till Day 8 (i.e. Sales, Production, Day 8, Status).

Sample file

Column AV is called "MB51 Shipped" and column AY is "Title Transfer".

I'd like to create a macro so that:

1) If Shippep in column AV, then the empty remaining Days will have Rollup in both Sales and Production columns.

See print screen here

Ex: in the attached print screen (the column may be slightly different from the sample file but the concept is the same), note that data was entered up to Day 6 (columns AH - AK) and a user put Shipped in column AV after entering Day 6's status. Here, I'd like the macro to return Rollup for every empty Sales and Production cell after Day 6 as highlighted in black from the screenshot.

Another example, if after entering Day 2's status (columns R - U), the user puts Shipped, then every Sales and Production cell after that will return Rollup.

2) If the last entered Sales cell says Title Transfer then return x in column AY (51st column)

See print screen here

So in my print screen, the last entered Sales cell having Title Transfer status is column Z of Day 4, the macro should then  return an x in column AY as shown in the screenshot.

I don't have any programming knowledge so any help is greatly appreciated! Thank you!!!!

答:
A very rough draft, but you can add this code to your Worksheet_Change(ByVal Target As Range) event

Like this:

Code:

```<code>Dim lastColumn As Long
Dim counter As Long

Application.EnableEvents = False

' Check if header is "MB51 Shipped"
If Me.Cells(1, Target.Column).Value = "MB51 Shipped" Then

    ' Get last column based on first row
    lastColumn = Me.Cells(1, Me.Columns.Count).End(xlToLeft).Column

    ' Check all cells in row and find matches for Sales and Production
    For counter = 1 To lastColumn

        ' Check if header match and cell is not empty
        If (Me.Cells(1, counter).Value = "Sales" or Me.Cells(1, counter).Value = "Production") And Me.Cells(Target.Row, counter).Value = vbNullString Then

            Me.Cells(Target.Row, counter).Value = "RollUp"

        End If

    Next counter

End If

Application.EnableEvents = True
</code>```

Let me know if it works

Body:
A very rough draft, but you can add this code to your Worksheet_Change(ByVal Target As Range) event

Like this:

Code:

Dim lastColumn As Long
Dim counter As Long

Application.EnableEvents = False

' Check if header is "MB51 Shipped"
If Me.Cells(1, Target.Column).Value = "MB51 Shipped" Then

    ' Get last column based on first row
    lastColumn = Me.Cells(1, Me.Columns.Count).End(xlToLeft).Column

    ' Check all cells in row and find matches for Sales and Production
    For counter = 1 To lastColumn

        ' Check if header match and cell is not empty
        If (Me.Cells(1, counter).Value = "Sales" or Me.Cells(1, counter).Value = "Production") And Me.Cells(Target.Row, counter).Value = vbNullString Then

            Me.Cells(Target.Row, counter).Value = "RollUp"

        End If

    Next counter

End If

Application.EnableEvents = True

Let me know if it works


问:
Writing values as an arbitrary amount of bits into a byte buffer in C++
Hey, I need to pack bit values into a byte buffer in C++.  My Buffer class has a char array and a position, similar to Java's ByteBuffer.  I need a good way to pack bits into this buffer, like so:

```<code>void put_bits(int amount, uint32_t value);
</code>```

It needs to support up to 32 bits.  I've seen a solution implemented in Java (that requires start/end access methods before bits can be packed) but I'm not sure how to do this in C++ because the endianness and other low level factors aren't hidden like they are in Java.

I have an inline function declared as endianness() which returns 0 (defined as BIG_ENDIAN) or 1 (defined as LITTLE_ENDIAN) that can be used, but I'm just not sure how to properly pack bits into a byte buffer.

This is the Java version of what I need to implement:

```<code>public void writeBits(int numBits, int value) {
    int bytePos = bitPosition >> 3;
    int bitOffset = 8 - (bitPosition & 7);
    bitPosition += numBits;

    for(; numBits > bitOffset; bitOffset = 8) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos++] |= (value >> (numBits-bitOffset)) & bitMaskOut[bitOffset];

        numBits -= bitOffset;
    }
    if(numBits == bitOffset) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos] |= value & bitMaskOut[bitOffset];
    }
    else {
        buffer[bytePos] &= ~ (bitMaskOut[numBits]<<(bitOffset - numBits));
        buffer[bytePos] |= (value&bitMaskOut[numBits]) << (bitOffset - numBits);
    }
}
</code>```

Which requires these two methods as well:

```<code>public void initBitAccess() {
    bitPosition = currentOffset * 8;
}

public void finishBitAccess() {
    currentOffset = (bitPosition + 7) / 8;
}
</code>```

How should I go about solving this?  Thanks.

EDIT: I also still need to be able to write normal bytes before and after writing bits.

答:
As long as you use the byte buffer only as such, you can translate the Java code one-to-one. It only gets dangerous if you interpret a byte pointer as another type and try to store a complete int in the byte buffer.

You don't even need the endianness function in this case, since you store a byte in a byte buffer, and there is nothing to convert or adjust size or whatever.

Body:
Hey, I need to pack bit values into a byte buffer in C++.  My Buffer class has a char array and a position, similar to Java's ByteBuffer.  I need a good way to pack bits into this buffer, like so:

void put_bits(int amount, uint32_t value);

It needs to support up to 32 bits.  I've seen a solution implemented in Java (that requires start/end access methods before bits can be packed) but I'm not sure how to do this in C++ because the endianness and other low level factors aren't hidden like they are in Java.

I have an inline function declared as endianness() which returns 0 (defined as BIG_ENDIAN) or 1 (defined as LITTLE_ENDIAN) that can be used, but I'm just not sure how to properly pack bits into a byte buffer.

This is the Java version of what I need to implement:

public void writeBits(int numBits, int value) {
    int bytePos = bitPosition >> 3;
    int bitOffset = 8 - (bitPosition & 7);
    bitPosition += numBits;

    for(; numBits > bitOffset; bitOffset = 8) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos++] |= (value >> (numBits-bitOffset)) & bitMaskOut[bitOffset];

        numBits -= bitOffset;
    }
    if(numBits == bitOffset) {
        buffer[bytePos] &= ~ bitMaskOut[bitOffset];
        buffer[bytePos] |= value & bitMaskOut[bitOffset];
    }
    else {
        buffer[bytePos] &= ~ (bitMaskOut[numBits]<<(bitOffset - numBits));
        buffer[bytePos] |= (value&bitMaskOut[numBits]) << (bitOffset - numBits);
    }
}

Which requires these two methods as well:

public void initBitAccess() {
    bitPosition = currentOffset * 8;
}

public void finishBitAccess() {
    currentOffset = (bitPosition + 7) / 8;
}

How should I go about solving this?  Thanks.

EDIT: I also still need to be able to write normal bytes before and after writing bits.


问:
SQL SUM() function not working properly with multiple tables in query
I am trying to pull the sum of hours worked worked and compare it to the sum of hours paid for each individual employee. These are stored in two different tables. When I query the tables separately into 2 different tables they work perfect. When I place them in the same query the results are way off.

Sample Data-PayrollTransactions:
PayrollTransactions

PayrollTime

This is the query that does not work:

```<code>SELECT Emp_No, Sum(Regular_Hours) AS PaidRegHours, Sum(Overtime_Hours) AS PaidOTHours, Sum(Reg_Hours) AS ClockedRegHours, Sum(OT_Hrs) AS ClockedOTHours
FROM PayrollTransactions, PayrollTime
WHERE Employee_No = Emp_No
GROUP BY Emp_No;
</code>```

The result it pulls for 1 employee is 1000 PaidRegHours. When doing a query just from PayrollTransactions as such:

```<code>SELECT Employee_No, Sum(Regular_Hours) AS PaidRegHours, Sum(Overtime_Hours) AS PaidOTHours
FROM PayrollTransactions
GROUP BY Employee_No;
</code>```

the result for that same employee is 200 PaidRegHours, which is correct. This same problem exists for all my computed fields. I am unsure how to fix this problem. Thanks for your help!

Desired Results:
DesiredOutput

答:
Classic problem of JOIN multiples. By querying these two tables that share a many-to-many relationship on employee, you return multiple pairings (i.e., duplicates, triplets, quadruples) that are then aggregated, turning actual 200 to 1,000 summed hours. Instead, consider joining one-to-one pairs which can be achieved by joining aggregates of both tables.

Below uses subqueries but can also use stored queries. Also, the explicit JOIN is used (current ANSI SQL standard) and not implicit join as you currently have with WHERE.

```<code>SELECT p.Employee_No, p.PaidRegHours, p.PaidOTHours, t.ClockedRegHours, t.ClockedOTHours
FROM
   (SELECT Employee_No,
           Sum(Regular_Hours) AS PaidRegHours,
           Sum(Overtime_Hours) AS PaidOTHours
    FROM PayrollTransactions
    GROUP BY Employee_No) p
INNER JOIN
   (SELECT Emp_No,
           Sum(Reg_Hours) AS ClockedRegHours,
           Sum(OT_Hrs) AS ClockedOTHours
    FROM PayrollTime
    GROUP BY Emp_No) t
  ON p.Employee_No = t.Emp_No
</code>```

Alternatively, with stored queries which sometimes can be more efficient with Access' engine:

```<code>SELECT p.Employee_No, p.PaidRegHours, p.PaidOTHours, t.ClockedRegHours, t.ClockedOTHours
FROM qryPayrollTransactionsAgg p
INNER JOIN qryPayrollTimeAgg t
  ON p.Employee_No = t.Emp_No
</code>```

Body:
I am trying to pull the sum of hours worked worked and compare it to the sum of hours paid for each individual employee. These are stored in two different tables. When I query the tables separately into 2 different tables they work perfect. When I place them in the same query the results are way off.

Sample Data-PayrollTransactions:
PayrollTransactions

PayrollTime

This is the query that does not work:

SELECT Emp_No, Sum(Regular_Hours) AS PaidRegHours, Sum(Overtime_Hours) AS PaidOTHours, Sum(Reg_Hours) AS ClockedRegHours, Sum(OT_Hrs) AS ClockedOTHours
FROM PayrollTransactions, PayrollTime
WHERE Employee_No = Emp_No
GROUP BY Emp_No;

The result it pulls for 1 employee is 1000 PaidRegHours. When doing a query just from PayrollTransactions as such:

SELECT Employee_No, Sum(Regular_Hours) AS PaidRegHours, Sum(Overtime_Hours) AS PaidOTHours
FROM PayrollTransactions
GROUP BY Employee_No;

the result for that same employee is 200 PaidRegHours, which is correct. This same problem exists for all my computed fields. I am unsure how to fix this problem. Thanks for your help!

Desired Results:
DesiredOutput

Body:
Classic problem of JOIN multiples. By querying these two tables that share a many-to-many relationship on employee, you return multiple pairings (i.e., duplicates, triplets, quadruples) that are then aggregated, turning actual 200 to 1,000 summed hours. Instead, consider joining one-to-one pairs which can be achieved by joining aggregates of both tables.

Below uses subqueries but can also use stored queries. Also, the explicit JOIN is used (current ANSI SQL standard) and not implicit join as you currently have with WHERE.

SELECT p.Employee_No, p.PaidRegHours, p.PaidOTHours, t.ClockedRegHours, t.ClockedOTHours
FROM
   (SELECT Employee_No,
           Sum(Regular_Hours) AS PaidRegHours,
           Sum(Overtime_Hours) AS PaidOTHours
    FROM PayrollTransactions
    GROUP BY Employee_No) p
INNER JOIN
   (SELECT Emp_No,
           Sum(Reg_Hours) AS ClockedRegHours,
           Sum(OT_Hrs) AS ClockedOTHours
    FROM PayrollTime
    GROUP BY Emp_No) t
  ON p.Employee_No = t.Emp_No

Alternatively, with stored queries which sometimes can be more efficient with Access' engine:

SELECT p.Employee_No, p.PaidRegHours, p.PaidOTHours, t.ClockedRegHours, t.ClockedOTHours
FROM qryPayrollTransactionsAgg p
INNER JOIN qryPayrollTimeAgg t
  ON p.Employee_No = t.Emp_No


问:
How to recursively explore python nested dictionaries?
I'm curious if there is a way to recursively explore nested dictionaries in python. By this I mean, say we have an example such as the below:

d = {'a':{'b':{'c':[1,2,3]}}}
```

What code would be necessary to get the contents of the innermost dictionary {'c':[1,2,3]}, traversing through a and b? In this case, it's not too much effort to write d['a']['b']['c'] but what if there was an arbitrarily large number of nested dictionaries, such that this was impossible/overly cumbersome.

My gut instinct is that I would need to create a general tree class with key and payload attributes, parsing the dictionary and storing it in my object, which I could design to be parsed using DFS, BFS, etc.

答:
Here's a recursive approach. The idea is to check if the current's dictionary value is an instance of a dict, if it is call the same function with the values as input, otherwise return the dictionary:

```<code>def get_inner_dict(d):
    for _, v in d.items():
        if isinstance(v, dict):
            return get_inner_dict(v)
        else:
            return d
</code>```

```<code>get_inner_dict(d)
# {'c': [1, 2, 3]}
</code>```

Body:
I'm curious if there is a way to recursively explore nested dictionaries in python. By this I mean, say we have an example such as the below:

d = {'a':{'b':{'c':[1,2,3]}}}

What code would be necessary to get the contents of the innermost dictionary {'c':[1,2,3]}, traversing through a and b? In this case, it's not too much effort to write d['a']['b']['c'] but what if there was an arbitrarily large number of nested dictionaries, such that this was impossible/overly cumbersome.

My gut instinct is that I would need to create a general tree class with key and payload attributes, parsing the dictionary and storing it in my object, which I could design to be parsed using DFS, BFS, etc.

Body:
Here's a recursive approach. The idea is to check if the current's dictionary value is an instance of a dict, if it is call the same function with the values as input, otherwise return the dictionary:

def get_inner_dict(d):
    for _, v in d.items():
        if isinstance(v, dict):
            return get_inner_dict(v)
        else:
            return d

get_inner_dict(d)
# {'c': [1, 2, 3]}


问:
Saving, loading, and predicting from a TensorFlow Estimator model (2.0)
Is there a guide anywhere for serializing and restoring Estimator models in TF2? The documentation is very spotty, and much of it not updated to TF2. I've yet to see a clear ands complete example anywhere of an Estimator being saved, loaded from disk and used to predict from new inputs.

TBH, I'm a bit baffled by how complicated this appears to be. Estimators are billed as simple, relatively high-level ways of fitting standard models, yet the process for using them in production seems very arcane. For example, when I load a model from disk via tf.saved_model.load(export_path) I get an AutoTrackable object:

<tensorflow.python.training.tracking.tracking.AutoTrackable at 0x7fc42e779f60>

Its not clear why I don't get my Estimator back. It looks like there used to be a useful-sounding function tf.contrib.predictor.from_saved_model, but since contrib is gone, it does not appear to be in play anymore (except, it appears, in TFLite).

Any pointers would be very helpful. As you can see, I'm a bit lost.

答:
maybe the author doesn't need the answer anymore but I was able to save and load a DNNClassifier using TensorFlow 2.1

# training.py
from pathlib import Path
import tensorflow as tf

....
# Creating the estimator
estimator = tf.estimator.DNNClassifier(
    model_dir= < model_dir >,
    hidden_units = [1000, 500],
    feature_columns = feature_columns,  # this is a list defined earlier
    n_classes = 2,
    optimizer = 'adam'
)

feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)
export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
servable_model_path = Path(estimator.export_saved_model( < model_dir >, export_input_fn).decode('utf8'))
print(f'Model saved at {servable_model_path}')

```
<p>For loading, you found the correct method, you just need to retrieve the <code>predict_fn</code></p>
<pre class="lang-py prettyprint-override"><code># testing.py
import tensorflow as tf
import pandas as pd

def predict_input_fn(test_df):
    '''Convert your dataframe using tf.train.Example() and tf.train.Features()'''
    examples = []
    ....
    return tf.constant(examples)

test_df = pd.read_csv('test.csv', ...)

# Loading the estimator
predict_fn = tf.saved_model.load(<model_dir>).signatures['predict']
# Predict
predictions = predict_fn(examples=predict_input_fn(test_df))
</code>```

Hope that this can help other people too (:

Body:
maybe the author doesn't need the answer anymore but I was able to save and load a DNNClassifier using TensorFlow 2.1

# training.py
from pathlib import Path
import tensorflow as tf

....
# Creating the estimator
estimator = tf.estimator.DNNClassifier(
    model_dir= < model_dir >,
    hidden_units = [1000, 500],
    feature_columns = feature_columns,  # this is a list defined earlier
    n_classes = 2,
    optimizer = 'adam'
)

feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)
export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
servable_model_path = Path(estimator.export_saved_model( < model_dir >, export_input_fn).decode('utf8'))
print(f'Model saved at {servable_model_path}')

For loading, you found the correct method, you just need to retrieve the predict_fn

# testing.py
import tensorflow as tf
import pandas as pd

def predict_input_fn(test_df):
    '''Convert your dataframe using tf.train.Example() and tf.train.Features()'''
    examples = []
    ....
    return tf.constant(examples)

test_df = pd.read_csv('test.csv', ...)

# Loading the estimator
predict_fn = tf.saved_model.load(<model_dir>).signatures['predict']
# Predict
predictions = predict_fn(examples=predict_input_fn(test_df))

Hope that this can help other people too (:


问:
How to concatenate indefinite number of arrays of Javascript objects
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

```<code>  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group
</code>```

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

答:
The most efficient way I can think of is

```<code>const users = [...new Set([...actor_groups].flatMap(el => el.user))]
</code>```

I used this example:

```<code>const actor_groups = [{user: ['ok','boom']}, {user: 'er'}]
console.log([...new Set([...actor_groups].flatMap(el => el.user))])
//output: ["ok", "boom", "er"]
</code>```

Body:
I have an array of Groups s.t. each Group has many Users

I want to return all (unique) Users for a given array of Groups.

So far, I have

  let actor = await User.query().findById(req.user.id).eager('groups') // find the actor requesting

let actor_groups = actor.groups // find all groups of actor

  if (actor_groups.length > 1)
    var actor_groups_users = actor_groups[0].user
    for (let i = 0; i < actor_groups.length; i++) {
      const actor_groups_users = actor_groups_users.concat(actor_groups[i]);
    }
    console.log('actor groups users is', actor_groups_users);
  else
    // return users from the first (only) group

which returns the error: actor_groups_users is not defined

Feels like a roundabout way to do this. Is there a way to just combine actor_groups into a single combined group?

Body:
The most efficient way I can think of is

const users = [...new Set([...actor_groups].flatMap(el => el.user))]

I used this example:

const actor_groups = [{user: ['ok','boom']}, {user: 'er'}]
console.log([...new Set([...actor_groups].flatMap(el => el.user))])
//output: ["ok", "boom", "er"]


问:
AND Operator cannot work with bool and string
I have a LINQ2SQL statement where I am using two criteria:

```<code>var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"
</code>```

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

答:
You mean == in place of =; the assignment expression (as opposed to the equality operator) is confusing things; instead of returning a bool, the result of r.Status = "I" is a string... "I"

```<code>var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select r.ID;
</code>```

(not quite sure what to make of the last part of your select, so I omitted it)

Body:
I have a LINQ2SQL statement where I am using two criteria:

var query1 = from r in dt.Test
                                where r.ID == 92
                                && r.Status = '"I"
                                select r.ID && r.Status = "I"

But its giving me an err that AND (&&) operator cannot work with string and bool. Whats the turnaround for this?

Body:
You mean == in place of =; the assignment expression (as opposed to the equality operator) is confusing things; instead of returning a bool, the result of r.Status = "I" is a string... "I"

var query1 = from r in dt.Test
             where r.ID == 92 && r.Status == "I"
             select r.ID;

(not quite sure what to make of the last part of your select, so I omitted it)


问:
Preserve Colors of a PNG Image inside of a Button and List SwiftUI
The colors of the image are changed when it is nested in List and Button View.

struct ContentView: View {
    var body:some View{
        List{
            Button(action:{}){
                Image("img")
            }
        }
    }
}
```

答:
You need to set the rendering mode to original to avoid the blue tint by default that appears on any view that is a Swift UI Button</p>

```<code>struct ContentView: View {
    var body:some View{
        List{
            Button(action:{}){
                Image("img")
                  .renderingMode(.original)
            }
        }
    }
}
</code>```

Body:
You need to set the rendering mode to original to avoid the blue tint by default that appears on any view that is a Swift UI Button

struct ContentView: View {
    var body:some View{
        List{
            Button(action:{}){
                Image("img")
                  .renderingMode(.original)
            }
        }
    }
}


问:
How to calculate the SUM of rows values for one column of a table created using TCPDF?
Please could you help me to calculate and display the SUM VALUE of the rows of a column named "prime" in my table which is created in a PDF report using TCPDF (the data is being extracted from my database).
Thank you in advance. I would be very grateful if you could help me.
A better description of my result table in this link
The main part of my code is this:

```<code>    <?php
set_time_limit(0);
tcpdf();

 // create new PDF document
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// set default monospaced font
//$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
//$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';

// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);

// ---------------------------------------------------------

// add a page
$pdf->AddPage();

$pdf->SetXY(16, 10);

// set document information
$pdf->SetCreator(PDF_CREATOR);
//$pdf->SetAuthor('Nicola Asuni');
//$pdf->SetSubject('TCPDF Tutorial');
//$pdf->SetKeywords('TCPDF, PDF, example, navettes, guide');
// set default header data
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.'', PDF_HEADER_STRING);
 $pdf->setPrintHeader(false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->setRTL(true);

$pdf->SetFont('xzar', '', 10);

    $sql= "SELECT * FROM nav_agent WHERE matricule='$mat'";
    $query = $this->db->query($sql);

$saut=0;
$tbl = '<table cellspacing="0" cellpadding="1" border="1">
   <thead>
        <tr>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">الإذن </th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">التنقل</th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="2">التوقيت</th>
            <th style="border: 1px double #000000; text-align:center;"  colspan="4"> </th>
       </tr>

<tr>
<td style="border: 1px double #000000; text-align:center;">العدد</td>
<td style="border: 1px double #000000; text-align:center;">التاريخ</td>
<td style="border: 1px double #000000; text-align:center;">من</td>
<td style="border: 1px double #000000; text-align:center;">إلى</td>
<td style="border: 1px double #000000; text-align:center;">الإنطلاق</td>
<td style="border: 1px double #000000; text-align:center;">الرجوع</td>
<td style="border: 1px double #000000; text-align:center;">المدة المقضاة (بالساعة)</td>
<td style="border: 1px double #000000; text-align:center;"> مبلغ منحة التنقل </td>
<td style="border: 1px double #000000; text-align:center;">رقم السيارة</td>
</tr>
';

$prime=0;
foreach ($query->result() as $row){

 $sql1 = "SELECT * FROM fiche_nav WHERE id_navette='$row->id_navette'";

  $query1 = $this->db->query($sql1);
foreach ($query1->result() as $row1){

$delai = strtotime($row1->heureret) - strtotime($row1->heuredep);
$time_h = ($delai/60)/60;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant1 = 15.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant1 = 9.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant1 = 6.750;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant2 = 35.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant2 = 25.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant2 = 18.000;

if ( $time_h <= 7 )
$prime = 0;
else

    if ( $time_h >7 && $time_h <= 14 )
$prime = 0.5 * $montant1;

else

    if ( $time_h >14 && $time_h < 24 )
$prime = $montant1;

else

    if ( $time_h >=24 )
$prime = $montant2;

$tbl=$tbl. '<tr>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->datedep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->lieudep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->destination .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->heuredep .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $row1->heureret .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $time_h .'</td>
<td style="border: 0px solid #000000; text-align:center">'. $prime .'</td>
<td style="border: 0px solid #000000; text-align:center;"> '.$row1->matriculevoiture .' </td>

<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
<td style="border: 0px solid #000000; text-align:center"></td>
</tr>
' ;

}

}

$tbl=$tbl.' </thead></table> ';

$pdf->writeHTML($tbl, true, false, false, false, '');

  // WHAT SHALL I ADD HERE TO CALCULATE the TOTAL VALUE i.e SUM OF "$PRIME" ROWS?

// close and output PDF document
 $date_auj=date('dmY',NOW());
    $strr = "Rapport-".$date_auj.".pdf";
$pdf->Output($strr, 'I');
//ob_end_clean();
//$pdf->Output($strr, 'I');

//============================================================+
// END OF FILE
//============================================================+
?>
</code>```

答:
After the line

```<code>$prime=0;
</code>```

Add another var let’s name it $sumPrimes

```<code>$sumPrimes =0;
</code>```

And after your last else when you assign your $prime:

```<code>else
    if ( $time_h >=24 )
$prime = $montant2;
</code>```

You could calculate the sum like that:

```<code>$sumPrimes += $prime;
</code>```

After your foreach and before you close the table:

```<code>$tbl=$tbl.' </thead></table> ';
</code>```

You can print the $sumPrimes.

Body:
Please could you help me to calculate and display the SUM VALUE of the rows of a column named "prime" in my table which is created in a PDF report using TCPDF (the data is being extracted from my database).
Thank you in advance. I would be very grateful if you could help me.
A better description of my result table in this link
The main part of my code is this:

    <?php
set_time_limit(0);
tcpdf();

 // create new PDF document
$pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// set default monospaced font
//$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
//$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';

// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);

// ---------------------------------------------------------

// add a page
$pdf->AddPage();

$pdf->SetXY(16, 10);

// set document information
$pdf->SetCreator(PDF_CREATOR);
//$pdf->SetAuthor('Nicola Asuni');
//$pdf->SetSubject('TCPDF Tutorial');
//$pdf->SetKeywords('TCPDF, PDF, example, navettes, guide');
// set default header data
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.'', PDF_HEADER_STRING);
 $pdf->setPrintHeader(false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

$pdf->setRTL(true);

$pdf->SetFont('xzar', '', 10);

    $sql= "SELECT * FROM nav_agent WHERE matricule='$mat'";
    $query = $this->db->query($sql);

$saut=0;
$tbl = '

            الإذن
            التنقل
            التوقيت

العدد
التاريخ
من
إلى
الإنطلاق
الرجوع
المدة المقضاة (بالساعة)
 مبلغ منحة التنقل
رقم السيارة

';

$prime=0;
foreach ($query->result() as $row){

 $sql1 = "SELECT * FROM fiche_nav WHERE id_navette='$row->id_navette'";

  $query1 = $this->db->query($sql1);
foreach ($query1->result() as $row1){

$delai = strtotime($row1->heureret) - strtotime($row1->heuredep);
$time_h = ($delai/60)/60;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant1 = 15.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant1 = 9.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant1 = 6.750;

if ($val_grade == 'A1' or   $val_grade == 'A2')
    $montant2 = 35.000;
    else
        if ($val_grade == 'A3' or   $val_grade == 'B'
         or     $val_grade =='ouv cat 8' or $val_grade =='ouv cat 9' or $val_grade =='ouv cat 10')

    $montant2 = 25.000;
    else
        if ($val_grade == 'C' or    $val_grade == 'D'
         or     $val_grade =='ouv cat 1' or $val_grade =='ouv cat 2' or $val_grade =='ouv cat 3'
         or $val_grade =='ouv cat 4' or $val_grade =='ouv cat 5' or $val_grade =='ouv cat 6' or $val_grade =='ouv cat 7')

    $montant2 = 18.000;

if ( $time_h <= 7 )
$prime = 0;
else

    if ( $time_h >7 && $time_h <= 14 )
$prime = 0.5 * $montant1;

else

    if ( $time_h >14 && $time_h < 24 )
$prime = $montant1;

else

    if ( $time_h >=24 )
$prime = $montant2;

$tbl=$tbl. '

'. $row1->datedep .'
'. $row1->lieudep .'
'. $row1->destination .'
'. $row1->heuredep .'
'. $row1->heureret .'
'. $time_h .'
'. $prime .'
 '.$row1->matriculevoiture .'

' ;

}

}

$tbl=$tbl.'

 ';

$pdf->writeHTML($tbl, true, false, false, false, '');

  // WHAT SHALL I ADD HERE TO CALCULATE the TOTAL VALUE i.e SUM OF "$PRIME" ROWS?

// close and output PDF document
 $date_auj=date('dmY',NOW());
    $strr = "Rapport-".$date_auj.".pdf";
$pdf->Output($strr, 'I');
//ob_end_clean();
//$pdf->Output($strr, 'I');

//============================================================+
// END OF FILE
//============================================================+
?>

Body:
After the line

$prime=0;

Add another var let’s name it $sumPrimes

$sumPrimes =0;

And after your last else when you assign your $prime:

else
    if ( $time_h >=24 )
$prime = $montant2;

You could calculate the sum like that:

$sumPrimes += $prime;

After your foreach and before you close the table:

$tbl=$tbl.' </thead></table> ';

You can print the $sumPrimes.


问:
Advanced conditions with class-validator (possible)?
I have TypeScript NestJS project.

I need to validate incoming DTO to my API. It can be described as "creating of project" where we have type of building (House, Flat, Garden) and depending on that type we need to define:

House: FLOORS including ROOMS

Flat: ROOMS

Garden: nothing (it is one "room")

Example of house type:

```<code>{
  type: HOUSE,
  floors: [
    {
      name: "1st floor",
      rooms: [
        {
          name: "bedroom"
        }
      ]
    }
  ]
}
</code>```

Example of flat type:

```<code>{
  type: FLAT,
  rooms: [
    {
      name: "bedroom"
    }
  ]
}
</code>```

I've done this in past with help of AJV, but now as we migrated to NestJS, we started using class-validator.

My question is, if I can make those advanced conditionals (eg. when type is FLAT, then expect ROOMS only, but not FLOORS) in class-validator?

答: With class-validator you have the options of Conditional Validation and of Group Validation, or you could always create a custom pipe and use AJV as you are used to. For the conditional validation you could create validations based on type and then let class-validator take care of the rest

Body:
I have TypeScript NestJS project.

I need to validate incoming DTO to my API. It can be described as "creating of project" where we have type of building (House, Flat, Garden) and depending on that type we need to define:

House: FLOORS including ROOMS

Flat: ROOMS

Garden: nothing (it is one "room")

Example of house type:

{
  type: HOUSE,
  floors: [
    {
      name: "1st floor",
      rooms: [
        {
          name: "bedroom"
        }
      ]
    }
  ]
}

Example of flat type:

{
  type: FLAT,
  rooms: [
    {
      name: "bedroom"
    }
  ]
}

I've done this in past with help of AJV, but now as we migrated to NestJS, we started using class-validator.

My question is, if I can make those advanced conditionals (eg. when type is FLAT, then expect ROOMS only, but not FLOORS) in class-validator?


问:
Using global variable in my class causing unexpected syntax
I have a class that requires a variable that is defined out of the scope of it. So i tried using global but, this causes this error:

syntax error, unexpected 'global' (T_GLOBAL), expecting function (T_FUNCTION)

I am unsure if I have put it in the wrong place or using the global keyword incorrectly.

My code looks like this:

```<code>$data = new testClass();

class System
{
    private $values;
    global $data;

    public function __construct()
    {

    }
    public function test()
    {
        return $data->get();
    }
}
$system = new System();
echo $system->test();
</code>```

So i was wondering how do I get the $data variable to be defined in my class? My use of global seems to be incorrect, I also put the global declaration in the __contrust() function but that didn't work either.

答: First things first... This could just be a simple "bad PHP syntax" issue.  Look for forgotten ; or in my case... Forgetting that functions actually need the word function : )

Body:
I have a class that requires a variable that is defined out of the scope of it. So i tried using global but, this causes this error:

syntax error, unexpected 'global' (T_GLOBAL), expecting function (T_FUNCTION)

I am unsure if I have put it in the wrong place or using the global keyword incorrectly.

My code looks like this:

$data = new testClass();

class System
{
    private $values;
    global $data;

    public function __construct()
    {

    }
    public function test()
    {
        return $data->get();
    }
}
$system = new System();
echo $system->test();

So i was wondering how do I get the $data variable to be defined in my class? My use of global seems to be incorrect, I also put the global declaration in the __contrust() function but that didn't work either.


问:
iOS webview: Prompt an user to download image using only JavaScript
I'm experimenting with letting the iPhone user draw using the canvas and then having a link to download the work.

I can get the image to load on a "new page" via:

```<code>window.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
</code>```

Whereby the user can "copy" the image and paste it in an email.
The user can also take a screen shot using the native iPhone ability.

What I would prefer is to do something like this:

```<code>window.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
</code>```

Unfortunately that leads to a "Safari can't download this file" error.

Any ideas from here? I would like the ability to not have to download this file serverside just to offer it up to the user again.

答: Safari does not allow file downloads. You would just have to display the image, and let them hold down their finger on it and click the save button (to save to camera roll).</p>

Body:
I'm experimenting with letting the iPhone user draw using the canvas and then having a link to download the work.

I can get the image to load on a "new page" via:

window.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

Whereby the user can "copy" the image and paste it in an email.
The user can also take a screen shot using the native iPhone ability.

What I would prefer is to do something like this:

window.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

Unfortunately that leads to a "Safari can't download this file" error.

Any ideas from here? I would like the ability to not have to download this file serverside just to offer it up to the user again.


问:
How to change the background-color of a Bootstrap card-header?
I'm trying to change the background-color of a bootstrap card-header, but when I add background-color: #00AA9E it seems to somehow destroy the look of the header..? Has anyone ever seen this before? Does it have something to do with the fact that the card is nested? Is it a bug in bootstrap?

Before  background-color: #00AA9E

After  background-color: #00AA9E

答:
I know it's years later, but I figured I'd add my answer since the accepted answer is a roundabout way of doing this and there is a more straightforward way to do it.  Applying !important to the setting(s) in your css class will cause them to override all settings set in another css class on the same element.  Hope this helps someone.

.ph-card-header {
    color: white !important;
    background-color: navy !important;
}
```


问:
Is there a way to avoid preprocessor macros when taking an argument from the compiler?
I am writing a library that needs to do some compile time calculations, and builds an array of compile time constants. The issue is I need a way to specify the max size of this array... The only way I know of is to make it a configurable option passed to the compiler.

Then you can use it with preprocessor directives for example:

```<code>#ifndef MAX_SIZE
    constexpr auto maxSize = 42; // Some default value if no MAX_SIZE is specified
#else
    constexpr auto maxSize = MAX_SIZE;
#endif
</code>```

To set the max size when compiling with gcc, you can compile the code with the option -DMAX_SIZE=<desired_size>.

The issue I have with this is it involves using preprocessor macros to get the MAX_SIZE argument from the compiler. Preprocessor macros are considered evil for many reasons (that I will not get into here because that isn't the point of the question).

Is there any way to achieve this functionality without using preprocessor macros? (I have up to C++20 available so feel free to go wild with your solutions -- well mostly, some of it isn't implemented yet by gcc 10)

答:
There are other ways, but you probably don't want to use them.  What you're doing is a good use of the preprocessor.  Though I'd write something like:

```<code>#ifndef MAX_SIZE
#define MAX_SIZE 42
#endif
constexpr size_t maxSize = MAX_SIZE;
</code>```

That way the actual code part, variable type, name, etc., need only be written once.  Also consider:

```<code>#indef MAX_SIZE
#error "You need to define MAX_SIZE to compile this code, e.g. -DMAX_SIZE=42"
#endif
</code>```

That way someone doesn't use the default when they didn't want to, because they didn't know to define it, or something in the build system made the -D flag get lost somewhere.

But there are other ways and one can avoid preprocessor macros!

Generate the source code itself.  While this might seem complex, and often is, there are ways to make it less so.  Structure the code so that the part which must be generated is small.  For instance, derive other values from a single definition of maxSize instead of generating all the code that needs to know the size.  There are also systems that can already do to this in some cases.  For example, if one is using CMake, create a header.h.in file like this:

```<code>constexpr size_t maxSize = @MAXSIZE@;
</code>```

And then put this into a CMakeLists.txt file:

```<code>set(MAXSIZE 42)
configure_file(header.h.in header.h @ONLY ESCAPE_QUOTES)
</code>```

When the project is built, cmake will turn header.h.in to header.h with @MAXSIZE@ changed to 42.
This didn't use the C++ preprocessor, but we effectively used the CMake preprocessor to preprocess a file before compiling it, so really, is it any different?  It's just a different preprocessor language (which is not nearly as good as the C/C++ preprocessor language).

Another way is with link time constants.  A linker symbol is normally the name of a function or global variable.  Something with static storage duration.  The value of the symbol is the address of the object.  But one can, in the commands to the linker, define any symbol you want.  Here's an example C file:

```<code>#include <stdio.h>
char array1[1];
extern array2[];
int main(void) { printf("%p %p\n", array1, array2); return 0; }
</code>```

Compile with gcc as gcc example.c -Wl,--defsym=array2=0xf00d.

Just as it prints the address of array1, it will print 0xf00d as the address of array2.  And so we have injected a constant into our code without using any preprocessor, neither C's nor CMake's.

But this value is not known to the compiler, only to the linker.  It's not an "integer constant expression" and can't be used in certain places, like case labels or the size of an object with static storage duration.  Because the compiler needs to know the exact value of those to compile the code.  The compiler generated the code for the printf call without knowing the exact value of array1 or array2.  It couldn't do that for a case statement label.  This is really while "integer constant expressions" exists in the C/C++ standards, and are not the same as expressions that are constant and have an integer type.

Body:
I am writing a library that needs to do some compile time calculations, and builds an array of compile time constants. The issue is I need a way to specify the max size of this array... The only way I know of is to make it a configurable option passed to the compiler.

Then you can use it with preprocessor directives for example:

#ifndef MAX_SIZE
    constexpr auto maxSize = 42; // Some default value if no MAX_SIZE is specified
#else
    constexpr auto maxSize = MAX_SIZE;
#endif

To set the max size when compiling with gcc, you can compile the code with the option -DMAX_SIZE=<desired_size>.

The issue I have with this is it involves using preprocessor macros to get the MAX_SIZE argument from the compiler. Preprocessor macros are considered evil for many reasons (that I will not get into here because that isn't the point of the question).

Is there any way to achieve this functionality without using preprocessor macros? (I have up to C++20 available so feel free to go wild with your solutions -- well mostly, some of it isn't implemented yet by gcc 10)

Body:
There are other ways, but you probably don't want to use them.  What you're doing is a good use of the preprocessor.  Though I'd write something like:

#ifndef MAX_SIZE
#define MAX_SIZE 42
#endif
constexpr size_t maxSize = MAX_SIZE;

That way the actual code part, variable type, name, etc., need only be written once.  Also consider:

#indef MAX_SIZE
#error "You need to define MAX_SIZE to compile this code, e.g. -DMAX_SIZE=42"
#endif

That way someone doesn't use the default when they didn't want to, because they didn't know to define it, or something in the build system made the -D flag get lost somewhere.

But there are other ways and one can avoid preprocessor macros!

Generate the source code itself.  While this might seem complex, and often is, there are ways to make it less so.  Structure the code so that the part which must be generated is small.  For instance, derive other values from a single definition of maxSize instead of generating all the code that needs to know the size.  There are also systems that can already do to this in some cases.  For example, if one is using CMake, create a header.h.in file like this:

constexpr size_t maxSize = @MAXSIZE@;

And then put this into a CMakeLists.txt file:

set(MAXSIZE 42)
configure_file(header.h.in header.h @ONLY ESCAPE_QUOTES)

When the project is built, cmake will turn header.h.in to header.h with @MAXSIZE@ changed to 42.
This didn't use the C++ preprocessor, but we effectively used the CMake preprocessor to preprocess a file before compiling it, so really, is it any different?  It's just a different preprocessor language (which is not nearly as good as the C/C++ preprocessor language).

Another way is with link time constants.  A linker symbol is normally the name of a function or global variable.  Something with static storage duration.  The value of the symbol is the address of the object.  But one can, in the commands to the linker, define any symbol you want.  Here's an example C file:

#include <stdio.h>
char array1[1];
extern array2[];
int main(void) { printf("%p %p\n", array1, array2); return 0; }

Compile with gcc as gcc example.c -Wl,--defsym=array2=0xf00d.

Just as it prints the address of array1, it will print 0xf00d as the address of array2.  And so we have injected a constant into our code without using any preprocessor, neither C's nor CMake's.

But this value is not known to the compiler, only to the linker.  It's not an "integer constant expression" and can't be used in certain places, like case labels or the size of an object with static storage duration.  Because the compiler needs to know the exact value of those to compile the code.  The compiler generated the code for the printf call without knowing the exact value of array1 or array2.  It couldn't do that for a case statement label.  This is really while "integer constant expressions" exists in the C/C++ standards, and are not the same as expressions that are constant and have an integer type.


问:
Count Distinct XML Pattern in Notepad++ or in Linux Grep
Its a  silly question, but I can't find the answer yet.

In my XML i've got the below lines:

```<code><BLAH><BLAH><BLAH>
<ABC>123456</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>
</code>```

Distinct count of patterns in <ABC>*</ABC> is 3.

Basically I want to count unique values between <ABC> and </ABC> 3  when I do a find & count in notepad++ or in Linux grep command.

答:
Assuming that the input has a format as shown in the example, you can use the code below.

That means every combination of corresponding <ABC> and </ABC> tags must be in one line with a text-only value in between.

```<code>grep -o '<ABC>[^<]*</ABC>' input.xml |sort -u|wc -l
</code>```

The command may not work if the input is formatted in other ways or if the value between <ABC> and </ABC> contains other tags.

With the example input from the question it will print

3
```

<p>It even works when there is more than one pair of <code><ABC></code> and <code></ABC></code> in a line.</p>

<p>With </p>

<pre class="lang-none prettyprint-override"><code><BLAH><BLAH><BLAH>
<ABC>123456</ABC>foo<ABC>1234567</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>
</code>```

it prints

4
```

Body:
Its a  silly question, but I can't find the answer yet.

In my XML i've got the below lines:

<BLAH><BLAH><BLAH>
<ABC>123456</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>

Distinct count of patterns in <ABC>*</ABC> is 3.

Basically I want to count unique values between <ABC> and </ABC> 3  when I do a find & count in notepad++ or in Linux grep command.

Body:
Assuming that the input has a format as shown in the example, you can use the code below.

That means every combination of corresponding <ABC> and </ABC> tags must be in one line with a text-only value in between.

grep -o '<ABC>[^<]*</ABC>' input.xml |sort -u|wc -l

The command may not work if the input is formatted in other ways or if the value between <ABC> and </ABC> contains other tags.

With the example input from the question it will print

3

It even works when there is more than one pair of <ABC> and </ABC> in a line.

With

<BLAH><BLAH><BLAH>
<ABC>123456</ABC>foo<ABC>1234567</ABC>
<ABC>123456</ABC>
<ABC>adfadfaf</ABC>
<ABC>gdsgdhghd</ABC>
</BLAH></BLAH></BLAH>

it prints

4


问:
How can I avoid scoping problems related to React hooks

The Problem

I have a recurring problem that seems to happen whenever I try and do anything remotely complicated and async using hooks.

The timeline which causes the issue goes something like this:

Define some state in a hook s

Make an async call to get some data d and use it to set state s

Make a subsequent call based on d, and use it to update s

The problem is that at 3.; when I want to update the state s, it at that point is the s as it was defined in the scope at which the function was defined, ie. it has no concept of the latest updated state, only that which it knew about when the function was defined.

My Half-Solutions

I have been able to get around this using a few things, a couple of things which tend to work:

Denormalise state (probably a good idea anyway) such that we avoid as much as possible having to update existing items in state

Run the update after an timeout; use setTimeout to force the update to happen in the next render cycle

Forget using state hooks at all, manage state externally and pass everything in as props

These aren't always (or ever) either good or desirable solutions. I'm guessing I'm missing something fundamental here but I haven't been able to find anything about this online, and I haven't yet had any viable suggestions from my colleagues.

TL:DR

Functions defined within the body of a React functional component will be defined with the scope to which they have access at that time. This isn't always the latest state. How can I get around the problem?

An arbitrary example to demonstrate what it is I'm talking about:

const getUsers = () => Promise.resolve({
  1: {
    name: 'Mr 1',
    favouriteColour: null,
  },
  2: {
    name: 'Ms 2',
    favouriteColour: null,
  },
});

const getFavouriteColorForUser = (id) => Promise.resolve({ id, color: Math.random() > 0.5 ? 'red' : 'blue' });

const App = () => {
  const [users, setUsers] = React.useState({});

  const handleClick = () => {
    getUsers()
      .then(data => {
        setUsers(data);
        return Promise.resolve(data);
      })
      .then(data => {
        return Promise.all(Object.keys(data).map(getFavouriteColorForUser));
      })
      .then(data => {
        const updatedUsers = {
          ...users,
          ...data.reduce(
            (p, c) => ({
              ...p,
              [c.id]: {
                ...users[c.id],
                favouriteColor: c.color
              },
            }),
            {}
          )
        };

        console.log('users:');
        console.dir(users);
        console.log('color data:');
        console.dir(data);
        console.log('updatedUsers:');
        console.dir(updatedUsers);

        setUsers(updatedUsers);
      })
  }

  return (

      {Object.keys(users).map(k => users[k]).map(user => (

{user.name}'s favourite colour is {user.favouriteColour}

      ))}
      <button onClick={handleClick}>Get Users</button>

  );
}

ReactDOM.render(<App />, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

答:
setState has a variant where you pass it a function. That function is guaranteed to be called with the most recent value from the state. You can use that to calculate your next state:</p>

```<code>.then(data => {
  setUsers(previousUsers => {
    const updatedUsers = {
      ...previousUsers, // <--- using previousUsers, not users
      ...data.reduce(
        (p, c) => ({
          ...p,
          [c.id]: {
            ...previousUsers[c.id], // <--- using previousUsers, not users
            favouriteColor: c.color
          },
        }), {})
    };

    return updatedUsers;
  })
})
</code>```

Body:
setState has a variant where you pass it a function. That function is guaranteed to be called with the most recent value from the state. You can use that to calculate your next state:

.then(data => {
  setUsers(previousUsers => {
    const updatedUsers = {
      ...previousUsers, // <--- using previousUsers, not users
      ...data.reduce(
        (p, c) => ({
          ...p,
          [c.id]: {
            ...previousUsers[c.id], // <--- using previousUsers, not users
            favouriteColor: c.color
          },
        }), {})
    };

    return updatedUsers;
  })
})


问:
Can I link a predefined string to an input in Google Spreadsheets
I want to make an inventory program (while I have few to zero programming skills)
The Goal is to create barcodes for the devices that are borrowable.
1. When some1 wants to borrow a device there is a staff member who scans the barcode and fills in a google form.(name, quantity, barcode(s)
2. The google form links to a spreadsheet where the magic happens.
3. The magic happens. I mean my spreadsheet manages incoming and outgoing devices and there is a sheet where I can see which device has not come back to me yet.

This is all working fine. Except for the following problem.
I want that when Google Spreadsheet sees the barcode in the cell it changes it into a string (the name of the device e.g. Chromebook)

My questions:
1. Is this possible
2. HOW? :)

UPDATE

Spreadsheet: https://docs.google.com/spreadsheets/d/1jX-ufX6M7sMAvifzZUKeERR3XzQBNxMu5GpnfqvK8kE/edit#gid=1502342008

The barcodes are printed and pasted on every device. We have Champtek handheld scanners to scan the barcodes. And that part seems to work. The scanned content shows in forms. When the form is submitted it shows in google spreadsheets but then I need to link the device name to the barcode somehow.

If you need more info, please reply

Thanks in advance!
(I'm a teacher in a school in Belgium trying to digitalise a few things)

答:
You want a barcode replaced by the name of the device to which the barcode belong? So that you know which kind of device is borrowed or returned but not which specific device is borrowed or returned?

```<code>function barcodes(){

var ss = SpreadsheetApp.getActiveSpreadsheet();
var barcodesSheet = ss.getSheetByName("Barcodes");
var barcodeValues = barcodesSheet.getRange("A1:C").getValues().filter(function(row){return row[0] !== ""});

var firstSheet = ss.getSheetByName("Form Responses Check-Out");
var firstSheetRange = firstSheet.getRange(1,1,firstSheet.getLastRow(),firstSheet.getLastColumn());
var firstSheetValues = firstSheetRange.getValues();

  for(var i=0;i<firstSheetValues.length;i++){

    var firstSheetRow = firstSheetValues[i];

      for(var f=3;f<firstSheetRow.length;f++){

      var barcode = firstSheetRow[f];

        for(var b=0;b<barcodeValues.length;b++){

          if(barcodeValues[b][0] == barcode){

            var device = barcodeValues[b][2];

            firstSheet.getRange(i+1,f+1).setValue(device);

          }

        }

      }

  }

}
</code>```

If I where you I would add the name of the device to the barcode (AAA-aaa-111, Chromebook).

How do you import the barcode into the Google Form?

I don't think this answers your question since yoy want to know how to change a barcode (how doe a barcode look like in a Google Spreadsheet cell) into a string? Sorry.

Body:
You want a barcode replaced by the name of the device to which the barcode belong? So that you know which kind of device is borrowed or returned but not which specific device is borrowed or returned?

function barcodes(){

var ss = SpreadsheetApp.getActiveSpreadsheet();
var barcodesSheet = ss.getSheetByName("Barcodes");
var barcodeValues = barcodesSheet.getRange("A1:C").getValues().filter(function(row){return row[0] !== ""});

var firstSheet = ss.getSheetByName("Form Responses Check-Out");
var firstSheetRange = firstSheet.getRange(1,1,firstSheet.getLastRow(),firstSheet.getLastColumn());
var firstSheetValues = firstSheetRange.getValues();

  for(var i=0;i<firstSheetValues.length;i++){

    var firstSheetRow = firstSheetValues[i];

      for(var f=3;f<firstSheetRow.length;f++){

      var barcode = firstSheetRow[f];

        for(var b=0;b<barcodeValues.length;b++){

          if(barcodeValues[b][0] == barcode){

            var device = barcodeValues[b][2];

            firstSheet.getRange(i+1,f+1).setValue(device);

          }

        }

      }

  }

}

If I where you I would add the name of the device to the barcode (AAA-aaa-111, Chromebook).

How do you import the barcode into the Google Form?

I don't think this answers your question since yoy want to know how to change a barcode (how doe a barcode look like in a Google Spreadsheet cell) into a string? Sorry.


问:
moment-timezone.js – Getting Error When Running in Jest Test
I got an error using moment-timezone.js. It runs perfectly on a web page, but when I try to implement the test for it, the test result always returns an error like below.

This is the code I use on the web page:

```<code>import moment from 'moment-timezone';

class TimezoneCityItem extends React.Component {

  componentDidMount(){
    this.setState({
      time: moment.tz(this.props.timezone)
    })
  }

  render(){
    return (
      <div>{this.state.time.format('HH:mm')}</div>
    )
  }
}
</code>```

This is timezoneListDummyData:

```<code>const timezoneList = [
  { name: 'los-angeles', title: 'Los Angeles', timezone: 'America/Los_Angeles' },
  { name: 'washington', title: 'Washington', timezone: 'America/New_York' },
  { name: 'london', title: 'London', timezone: 'Europe/London' },
  { name: 'dubai', title: 'Dubai', timezone: 'Asia/Dubai' },
  { name: 'hongkong', title: 'Hongkong', timezone: 'Asia/Hong_Kong' },
];

export default timezoneList;
</code>```

this is code I use on my test file

```<code>import React from 'react';
import { shallow } from 'enzyme';
import TimezoneCityItem from '../TimezoneCity.item';
import timezoneList from '/lib/timezoneListDummyData'; // It just an array list of timezone

describe('<TimezoneCityItem />', () => {
   test('Should render TimezoneCityItem correctly', () => {
       const wrapper = shallow(<TimezoneCityItem {...timezoneList[0]} />);
       expect(wrapper).toMatchSnapshot();
   });
});
</code>```

This is the version of the packages:

```<code>"moment": "~2.18.1",
"moment-timezone": "~0.5.13",
</code>```

This is the error message:

```<code>Test suite failed to run
TypeError: Cannot read property 'split' of undefined

  at node_modules/moment-timezone/moment-timezone.js:36:34
  at Object.<anonymous>.moment (node_modules/moment-timezone/moment-timezone.js:14:20)
  at Object.<anonymous> (node_modules/moment-timezone/moment-timezone.js:18:2)
  at Object.<anonymous> (node_modules/moment-timezone/index.js:1:120)
  at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.item.jsx:3:49)
  at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.jsx:3:47)
  at Object.<anonymous> (imports/ui/components/mainLayout/MainLayout.jsx:6:47)
  at Object.<anonymous> (imports/ui/components/mainLayout/__tests__/MainLayout.test.js:3:19)
      at Generator.next (<anonymous>)
      at new Promise (<anonymous>)
      at Generator.next (<anonymous>)
      at <anonymous>
</code>```

答:
I was running into this same problem; here's an example of how I mocked moment:

let diffMins = updateThreshold + 1;
jest.mock('moment', () => {
  const mMoment = {
    diff: jest.fn(() => diffMins),
  };
  const fn = jest.fn(() => mMoment);
  fn.version = '2.24';
  fn.tz = jest.fn();
  fn.fn = jest.fn();
  return fn;
});```

Body:
I got an error using moment-timezone.js. It runs perfectly on a web page, but when I try to implement the test for it, the test result always returns an error like below.

This is the code I use on the web page:

import moment from 'moment-timezone';

class TimezoneCityItem extends React.Component {

  componentDidMount(){
    this.setState({
      time: moment.tz(this.props.timezone)
    })
  }

  render(){
    return (

{this.state.time.format('HH:mm')}

    )
  }
}

This is timezoneListDummyData:

const timezoneList = [
  { name: 'los-angeles', title: 'Los Angeles', timezone: 'America/Los_Angeles' },
  { name: 'washington', title: 'Washington', timezone: 'America/New_York' },
  { name: 'london', title: 'London', timezone: 'Europe/London' },
  { name: 'dubai', title: 'Dubai', timezone: 'Asia/Dubai' },
  { name: 'hongkong', title: 'Hongkong', timezone: 'Asia/Hong_Kong' },
];

export default timezoneList;

this is code I use on my test file

import React from 'react';
import { shallow } from 'enzyme';
import TimezoneCityItem from '../TimezoneCity.item';
import timezoneList from '/lib/timezoneListDummyData'; // It just an array list of timezone

describe('<TimezoneCityItem />', () => {
   test('Should render TimezoneCityItem correctly', () => {
       const wrapper = shallow(<TimezoneCityItem {...timezoneList[0]} />);
       expect(wrapper).toMatchSnapshot();
   });
});

This is the version of the packages:

"moment": "~2.18.1",
"moment-timezone": "~0.5.13",

This is the error message:

Test suite failed to run
TypeError: Cannot read property 'split' of undefined

  at node_modules/moment-timezone/moment-timezone.js:36:34
  at Object.<anonymous>.moment (node_modules/moment-timezone/moment-timezone.js:14:20)
  at Object.<anonymous> (node_modules/moment-timezone/moment-timezone.js:18:2)
  at Object.<anonymous> (node_modules/moment-timezone/index.js:1:120)
  at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.item.jsx:3:49)
  at Object.<anonymous> (imports/ui/components/mainLayout/TimezoneCity.jsx:3:47)
  at Object.<anonymous> (imports/ui/components/mainLayout/MainLayout.jsx:6:47)
  at Object.<anonymous> (imports/ui/components/mainLayout/__tests__/MainLayout.test.js:3:19)
      at Generator.next (<anonymous>)
      at new Promise (<anonymous>)
      at Generator.next (<anonymous>)
      at <anonymous>


问:
Web Application - User Authentication Across Domains
A client of ours has approached us to develop an application, and as usual the scope grows day by day.

Initially it started as a dedicated app confined within their corporate network.  User Authentication was established by aquiring the user's Windows login and using a SQLServer Database to host the access rights.  All quite straight forward.

They now want the following:

- Application to be Web Based

- Application to be hosted outside of the corporate network

- User authentication to work in the same way (no using passwords, just windows logins)

To complicate it further, they want the various functions of the application to to be usable by another application which just fires of HTTP requests.

- User logs in to corporate network

- User launches corporate application

- User processes customer details

- User clicks a button

- Corporate Application fires a HTTP request to our hosted web app

- HTTP request included necessary authentication and customer details

- User authentication is completed 'automatically' (No human involvement)

- Customer data is transmitted securely

They are very keen for us to do this for them as our initial approach was very much what they wanted.  They still want us to do this even though such hosted web apps are not our speciallity.  So I now approach the experts;

- Does anyone have any advice on how to approach this?

- Does anyone have any warning about the possible pitfalls to avoid?

答:
Depending on how your app is constructed, you can fiddle with the machineKey in your web.config to allow for AJAX calls with single-sign-on (SSO).
This would involve an small asp.net app within the corporate network just to dish out authentication tokens and redirect to your hosted app.

If the two apps share the same machineKey then the asp.net authentication system will happily allow users into your hosted app.

There are problems with this approach:

You introduce another dependency into your system (the authentication app within the corporate network.) It'll be a simple app, but you will face problems when trying to diagnose problems if you don't have access.

You need your hosted service to the in the same domain as the authentication app (so the authentication ticket in the HTTP cookie gets passed around.)

You'll also need an SSL certificate for your hosted service to secure the information. (Not really a downside per-se, you'd probably want to do this anyway.)

Because you and your client will have a shared machineKey, you will tie down an instance of your app to that particular client.

OwnerDisplayName: Dems

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: blowdart

OwnerDisplayName: ninj


问:
How to pass a lambda as an extra of an Intent?
I'm new to kotlin and Android, and i was looking into recyclerView but ran into a few hiccups.

Basically i have,

+ 2 Activities, MainActivity containig a recyclerView and fullDetails activity that opens with onClick on each ticket of the recyclerView,
Activity A & Activity B

The Fab show show a function unique to each item, like a Toast as in this example.

+An ArrayList of objects,tempMenuList of options class,

+The class contains a few strings an a lambda variable actionOfItem as i want to have individual functions for each object,

+I'm trying to pass the lambda through an intent as serializable throught the OnClick Listener like this:

```<code>val intent=Intent(context,fullDetails::class.java)
intent.putExtra("action",Runnable{tempMenuList[position].actionOfItem} as java.io.Serializable)
</code>```

+On Activity B, I get the lambda like this and try to call the function, as this was crashing my app, I made a seperate actions class for the lambda's so that i can write getSerializable() as an object of actions class.

```<code>val action=bundle.getSerializable("function") as actions?
fabShow.setOnClickListener{
          action?.action
    }
</code>```

Now the app loads the MainActivity,but Crashes when The OnClickListner of the RecyclerView is pressed.

I know my naming is super bad and confusing and i don't use comments,

but is there any way to pass a unique function for each object through an intent?
Edit 1: I read that i can do this using SharedPreferences, but it isn't reccommended.

Here's the Logcat:

```<code>java.lang.ClassCastException: com.example.androidreferenceapp.MainActivity$menuAdapter$onBindViewHolder$1$1 cannot be cast to java.io.Serializable
    at com.example.androidreferenceapp.MainActivity$menuAdapter$onBindViewHolder$1.onClick(MainActivity.kt:58)
    at android.view.View.performClick(View.java:6605)
    at android.view.View.performClickInternal(View.java:6582)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25897)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6762)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

Here's the full Source Code if that helps

答:
Runnables aren't Serializable. You can't simply cast whatever to Serializable to make it serializeable--it's an interface you have to implement. And you can't serialize object references, so it would be impossible to do this with a function.

Your data (tempMenuList in this case) should be in a ViewModel. The Activities should be converted into Fragments that are both housed in the same Activity. The first Fragment can simply pass the Int index of the item in the list via the Intent, and the second Fragment can retrieve the item and its action from the ViewModel.

Body:
I'm new to kotlin and Android, and i was looking into recyclerView but ran into a few hiccups.

Basically i have,

+ 2 Activities, MainActivity containig a recyclerView and fullDetails activity that opens with onClick on each ticket of the recyclerView,
Activity A & Activity B

The Fab show show a function unique to each item, like a Toast as in this example.

+An ArrayList of objects,tempMenuList of options class,

+The class contains a few strings an a lambda variable actionOfItem as i want to have individual functions for each object,

+I'm trying to pass the lambda through an intent as serializable throught the OnClick Listener like this:

val intent=Intent(context,fullDetails::class.java)
intent.putExtra("action",Runnable{tempMenuList[position].actionOfItem} as java.io.Serializable)

+On Activity B, I get the lambda like this and try to call the function, as this was crashing my app, I made a seperate actions class for the lambda's so that i can write getSerializable() as an object of actions class.

val action=bundle.getSerializable("function") as actions?
fabShow.setOnClickListener{
          action?.action
    }

Now the app loads the MainActivity,but Crashes when The OnClickListner of the RecyclerView is pressed.

I know my naming is super bad and confusing and i don't use comments,

but is there any way to pass a unique function for each object through an intent?
Edit 1: I read that i can do this using SharedPreferences, but it isn't reccommended.

Here's the Logcat:

java.lang.ClassCastException: com.example.androidreferenceapp.MainActivity$menuAdapter$onBindViewHolder$1$1 cannot be cast to java.io.Serializable
    at com.example.androidreferenceapp.MainActivity$menuAdapter$onBindViewHolder$1.onClick(MainActivity.kt:58)
    at android.view.View.performClick(View.java:6605)
    at android.view.View.performClickInternal(View.java:6582)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25897)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6762)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Here's the full Source Code if that helps


问:
Dexie.js seems to consume more space than necessary
We are using Dexie.js to save some binary data client-side. The binary data can be from 5-20MB.

The strange thing is when we download a file, much more space is consumed than the file size itself.

For example, downloading an 8.5MB file results in a Dexie DB of 57MB is this normal?

I ask because before long our users have downloaded a few files of around 100MB total and chrome will crash with an indexeddb of over 1GB.

Thanks

答: Okay, so I have realised what the issue was. I had set an index on the binary data field. I think this had led to some serious overhead. Setting the index was a mistake I have removed it and now storing the 8.5MB file results in 11.4MB of storage used.</p>