问:
Rownum for a column with lag
I have this query

```<code>SELECT CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee
ORDER   BY emp_id;
</code>```

And it shows me result like this: Resultset

I want to add row number (first column SN) for Employee ID for in between rows I want to set it as null, for e.g. For Employee ID -> S/N 2-> F904 (SN should be null). How can I do that?

答:
Use dense_rank() to enumerate rows:

```<code>select case lag(emp_id) over( order by emp_id ) when emp_id then null
            else '<'||dense_rank() over (order by emp_id)||'>'
       end sn,
       nullif(emp_id, lag(emp_id) over( order by emp_id )) empid,
       row_number() over (partition by emp_id order by emp_id) rn,
       family_mem_id memid,
       case lag(emp_id) over(order by emp_id) when emp_id then null
            else (sum(amount_paid) over(partition by emp_id))
       end total
  FROM  Employee order by emp_id;
</code>```

dbfiddle and sample output:

```<code>SN   EMPID     RN MEMID      TOTAL
---- ----- ------ ----- ----------
<1>  101        1 F901         200
                2 F904
<2>  102        1 F901         135
                2 F901
<3>  103        1 F901         185
                2 F901
                3 F901
</code>```

Title: Rownum for a column with lag

Body:
I have this query

SELECT CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee
ORDER   BY emp_id;

And it shows me result like this: Resultset

I want to add row number (first column SN) for Employee ID for in between rows I want to set it as null, for e.g. For Employee ID -> S/N 2-> F904 (SN should be null). How can I do that?

Body:
Use dense_rank() to enumerate rows:

select case lag(emp_id) over( order by emp_id ) when emp_id then null
            else '<'||dense_rank() over (order by emp_id)||'>'
       end sn,
       nullif(emp_id, lag(emp_id) over( order by emp_id )) empid,
       row_number() over (partition by emp_id order by emp_id) rn,
       family_mem_id memid,
       case lag(emp_id) over(order by emp_id) when emp_id then null
            else (sum(amount_paid) over(partition by emp_id))
       end total
  FROM  Employee order by emp_id;

dbfiddle and sample output:

SN   EMPID     RN MEMID      TOTAL
---- ----- ------ ----- ----------
<1>  101        1 F901         200
                2 F904
<2>  102        1 F901         135
                2 F901
<3>  103        1 F901         185
                2 F901
                3 F901


来源: stackexchange

问:
Is there any taskbar API to apply registry changes immediately?
When I/We change the taskbar settings with right click on taskbar > taskbar settings the changes apply immediately but when I make changes in registry settings I have to reset explorer.exe to apply the changes.

Is there any API to apply registry changes immediately? or another idea?

答:
As far as I know there is no easy way in general, since each application has to implement some way to notice registry changes. So if the application only reads the registry key at startup you are out of luck, but there is an event system in Windows to notify (willing) applications about registry changes. Have a look at this

```<code>SendNotifyMessage( HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0 );
</code>```

Other maybe helpful links:

Force update start menu after registry change

How to refresh explorer after a registry change

Documentation of the WMI System Registry Provider

ContentLicense: CC BY-SA 4.0

Body:
As far as I know there is no easy way in general, since each application has to implement some way to notice registry changes. So if the application only reads the registry key at startup you are out of luck, but there is an event system in Windows to notify (willing) applications about registry changes. Have a look at this

SendNotifyMessage( HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0 );

Other maybe helpful links:

Force update start menu after registry change

How to refresh explorer after a registry change

Documentation of the WMI System Registry Provider


问:
Error converting String to java.sql.LocalDateTime
I tried converting string to LocalDateTime. Here is my code

```<code>String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
</code>```

But doing so I am getting the following errors

```<code>The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)
</code>```

Can someone suggest me what to do

答:
Your code is mostly right. First, be sure you're importing the correct packages:

```<code>import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
</code>```

Second, your first line has a typo (-) in the first character of the String val and is missing a semicolon:

```<code>// Remove - from the String and put ; at the end
// String val = "-2015-07-18T13:32:56.971-0400"
String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
//Print to test:
System.out.println(dateTime);
//Result on the console: 2015-07-18T13:32:56.971
</code>```

Body:
I tried converting string to LocalDateTime. Here is my code

String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);

But doing so I am getting the following errors

The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)

Can someone suggest me what to do

Body:
Your code is mostly right. First, be sure you're importing the correct packages:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

Second, your first line has a typo (-) in the first character of the String val and is missing a semicolon:

// Remove - from the String and put ; at the end
// String val = "-2015-07-18T13:32:56.971-0400"
String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
//Print to test:
System.out.println(dateTime);
//Result on the console: 2015-07-18T13:32:56.971


问:
Is there a function in R to combine two legends of a graph that's build from multiple dataframes?
I am trying to merge the legends of a plot, but I can't figure out how. I looked up many examples, but in these examples people build the plots from one dataframe. My plot is build from four dataframes. I tried merging these dateframes with the merge and rbind function, but I can't figure out how to do it correctly.

Is it possible to merge the legends without merging the dataframes?

This is my code

```<code>fig_ObjPlur_ASSenTD <- ggplot(subset(gazetarget_ObjPlur_ASS)) +
      geom_line(data=gazetarget_ObjPlur_ASS,aes(x=Time, y=Targetgaze, color="Target", linetype="ASS"), size=1) +
      geom_line(data=gazeother_ObjPlur_ASS,aes(x=Time, y=Othergaze, color="Distractor",linetype="ASS"), size=1) +
      geom_line(data=gazetarget_ObjPlur_TD,aes(x=Time, y=Targetgaze, color="Target", linetype="TD"), size=1) +
      geom_line(data=gazeother_ObjPlur_TD,aes(x=Time, y=Othergaze, color="Distractor", linetype="TD"), size=1) +

    scale_color_manual(name = "Condition & Group", values=c("blue","red")) +
    scale_linetype_manual(name = "Condition & Group", values=c(1,2)) +
    theme(legend.key.width=unit(2.5,"line"))

fig_ObjPlur_ASSenTD + ggtitle("Looks to target vs. distractor picture") +
      xlab("Time in milliseconds from sentence start") +
      ylab("Proportion of looks") +
      xlim(0,3000)
</code>```

Which gives me this graph. Instead of two legends, I want one legend with 4 points:

- Target ASD (blue solid line)

- Distractor ASD (red solid line)

- Target TD (blue dashed line)

- Distractor TD (red dashed line)

Picture of graph

My dataframes look like this:

Example dataframe ObjPlur_ASS

Help would be appreciated!

答:
You have data in the wide format, it's easier to have legends with them in long format, so let's say your data is like this:

```<code>gazetarget_ObjPlur_ASS = data.frame(
  Time = seq(0,3000,length.out=10),
  Targetgaze = runif(10),
  Othergaze = runif(10)
)

gazetarget_ObjPlur_TD = data.frame(
  Time = seq(0,3000,length.out=10),
  Targetgaze = runif(10),
  Othergaze = runif(10)
)
</code>```

We first add another column that annotates the dataset:

```<code>gazetarget_ObjPlur_ASS$Type = "ASD"
gazetarget_ObjPlur_TD$Type = "TD"
</code>```

Then we set the colors /  linetype for the legend:

```<code>COLS = c("blue","red","blue","red")
LINES = c("solid","solid","dashed","dashed")
names(COLS) = c("Target ASD","Distractor ASD","Target TD","Distractor TD")
names(LINES) = c("Target ASD","Distractor ASD","Target TD","Distractor TD")
</code>```

Now we cast the data frame into long format and also change the values to Target / Distractor:

```<code>DF = rbind(gazetarget_ObjPlur_ASS,gazetarget_ObjPlur_TD) %>%
pivot_longer(-c(Time,Type)) %>%
mutate(name=recode_factor(name,Targetgaze="Target",Othergaze="Distractor")) %>%
mutate(Group=paste(name,Type))
</code>```

Then plot:

```<code>ggplot(DF,aes(x=Time,y=value,col=Group,linetype=Group)) +
geom_line() +
scale_color_manual(values=COLS,breaks=names(COLS)) +
scale_linetype_manual(values=LINES,breaks=names(COLS))
</code>```

Body:
I am trying to merge the legends of a plot, but I can't figure out how. I looked up many examples, but in these examples people build the plots from one dataframe. My plot is build from four dataframes. I tried merging these dateframes with the merge and rbind function, but I can't figure out how to do it correctly.

Is it possible to merge the legends without merging the dataframes?

This is my code

fig_ObjPlur_ASSenTD <- ggplot(subset(gazetarget_ObjPlur_ASS)) +
      geom_line(data=gazetarget_ObjPlur_ASS,aes(x=Time, y=Targetgaze, color="Target", linetype="ASS"), size=1) +
      geom_line(data=gazeother_ObjPlur_ASS,aes(x=Time, y=Othergaze, color="Distractor",linetype="ASS"), size=1) +
      geom_line(data=gazetarget_ObjPlur_TD,aes(x=Time, y=Targetgaze, color="Target", linetype="TD"), size=1) +
      geom_line(data=gazeother_ObjPlur_TD,aes(x=Time, y=Othergaze, color="Distractor", linetype="TD"), size=1) +

    scale_color_manual(name = "Condition & Group", values=c("blue","red")) +
    scale_linetype_manual(name = "Condition & Group", values=c(1,2)) +
    theme(legend.key.width=unit(2.5,"line"))

fig_ObjPlur_ASSenTD + ggtitle("Looks to target vs. distractor picture") +
      xlab("Time in milliseconds from sentence start") +
      ylab("Proportion of looks") +
      xlim(0,3000)

Which gives me this graph. Instead of two legends, I want one legend with 4 points:

- Target ASD (blue solid line)

- Distractor ASD (red solid line)

- Target TD (blue dashed line)

- Distractor TD (red dashed line)

Picture of graph

My dataframes look like this:

Example dataframe ObjPlur_ASS

Help would be appreciated!

Body:
You have data in the wide format, it's easier to have legends with them in long format, so let's say your data is like this:

gazetarget_ObjPlur_ASS = data.frame(
  Time = seq(0,3000,length.out=10),
  Targetgaze = runif(10),
  Othergaze = runif(10)
)

gazetarget_ObjPlur_TD = data.frame(
  Time = seq(0,3000,length.out=10),
  Targetgaze = runif(10),
  Othergaze = runif(10)
)

We first add another column that annotates the dataset:

gazetarget_ObjPlur_ASS$Type = "ASD"
gazetarget_ObjPlur_TD$Type = "TD"

Then we set the colors /  linetype for the legend:

COLS = c("blue","red","blue","red")
LINES = c("solid","solid","dashed","dashed")
names(COLS) = c("Target ASD","Distractor ASD","Target TD","Distractor TD")
names(LINES) = c("Target ASD","Distractor ASD","Target TD","Distractor TD")

Now we cast the data frame into long format and also change the values to Target / Distractor:

DF = rbind(gazetarget_ObjPlur_ASS,gazetarget_ObjPlur_TD) %>%
pivot_longer(-c(Time,Type)) %>%
mutate(name=recode_factor(name,Targetgaze="Target",Othergaze="Distractor")) %>%
mutate(Group=paste(name,Type))

Then plot:

ggplot(DF,aes(x=Time,y=value,col=Group,linetype=Group)) +
geom_line() +
scale_color_manual(values=COLS,breaks=names(COLS)) +
scale_linetype_manual(values=LINES,breaks=names(COLS))


问:
Hive Exists condition not working on multiple condition
I'm running the following query

```<code>select * from Data t1
where not exists (select 1 from data2 t2 where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx )
</code>```

the above query throws the following error.

org.apache.hive.service.cli.HiveSQLException: Error while compiling
  statement: FAILED: SemanticException [Error 10250]: Line 2:33 Invalid
  SubQuery expression 'dx': For Exists/Not Exists operator SubQuery must
  be Correlated.

but the same query executes when I write for a single condition

```<code>select * from Data t1
where not exists (select 1 from  Data2 t2
                  where t1.diagnosiscode3 = t2.dx)
</code>```

whether hive supports only one exists condition.

I can't able to perform multiple in condition also since hive doesn't support.

How to resolve the issue.

答:
Also this condition

```<code>where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx
</code>```

can be transformed to this condition:

```<code>where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t1.diagonosiscode2 and
t1.diagonosiscode4 = t1.diagonosiscode2 and
t1.diagonosiscode5 = t1.diagonosiscode2 and
t1.diagonosiscode6 = t1.diagonosiscode2 and
t1.diagonosiscode7 = t1.diagonosiscode2 and
t1.diagonosiscode8 = t1.diagonosiscode2 and
t1.diagonosiscode9 = t1.diagonosiscode2 and
t1.diagonosiscode10 = t1.diagonosiscode2 and
t1.diagonosiscode11 = t1.diagonosiscode2 and
t1.diagonosiscode12 = t1.diagonosiscode2 and
t1.diagonosiscode13 = t1.diagonosiscode2 and
t1.diagonosiscode14 = t1.diagonosiscode2 and
t1.diagonosiscode15 = t1.diagonosiscode2 and
t1.diagonosiscode16 = t1.diagonosiscode2 and
t1.diagonosiscode17 = t1.diagonosiscode2 and
t1.diagonosiscode18 = t1.diagonosiscode2 and
t1.diagonosiscode19 = t1.diagonosiscode2 and
t1.diagonosiscode20 = t1.diagonosiscode2 and
t1.diagonosiscode21 = t1.diagonosiscode2 and
t1.diagonosiscode22 = t1.diagonosiscode2 and
t1.diagonosiscode23 = t1.diagonosiscode2 and
t1.diagonosiscode24 = t1.diagonosiscode2 and
t1.diagonosiscode25 = t1.diagonosiscode2
</code>```

Body:
I'm running the following query

select * from Data t1
where not exists (select 1 from data2 t2 where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx )

the above query throws the following error.

org.apache.hive.service.cli.HiveSQLException: Error while compiling
  statement: FAILED: SemanticException [Error 10250]: Line 2:33 Invalid
  SubQuery expression 'dx': For Exists/Not Exists operator SubQuery must
  be Correlated.

but the same query executes when I write for a single condition

select * from Data t1
where not exists (select 1 from  Data2 t2
                  where t1.diagnosiscode3 = t2.dx)

whether hive supports only one exists condition.

I can't able to perform multiple in condition also since hive doesn't support.

How to resolve the issue.

Body:
Also this condition

where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx

can be transformed to this condition:

where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t1.diagonosiscode2 and
t1.diagonosiscode4 = t1.diagonosiscode2 and
t1.diagonosiscode5 = t1.diagonosiscode2 and
t1.diagonosiscode6 = t1.diagonosiscode2 and
t1.diagonosiscode7 = t1.diagonosiscode2 and
t1.diagonosiscode8 = t1.diagonosiscode2 and
t1.diagonosiscode9 = t1.diagonosiscode2 and
t1.diagonosiscode10 = t1.diagonosiscode2 and
t1.diagonosiscode11 = t1.diagonosiscode2 and
t1.diagonosiscode12 = t1.diagonosiscode2 and
t1.diagonosiscode13 = t1.diagonosiscode2 and
t1.diagonosiscode14 = t1.diagonosiscode2 and
t1.diagonosiscode15 = t1.diagonosiscode2 and
t1.diagonosiscode16 = t1.diagonosiscode2 and
t1.diagonosiscode17 = t1.diagonosiscode2 and
t1.diagonosiscode18 = t1.diagonosiscode2 and
t1.diagonosiscode19 = t1.diagonosiscode2 and
t1.diagonosiscode20 = t1.diagonosiscode2 and
t1.diagonosiscode21 = t1.diagonosiscode2 and
t1.diagonosiscode22 = t1.diagonosiscode2 and
t1.diagonosiscode23 = t1.diagonosiscode2 and
t1.diagonosiscode24 = t1.diagonosiscode2 and
t1.diagonosiscode25 = t1.diagonosiscode2


问:
Deleting a row in datagrid view
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

答:
bind the linkbutton id as the primary key. On client clicking the link button save that id in a hidden field. This hidden field value will be the id of row to be deleted.

Then on the server click of link button delete the row corresponding to the hidden field value

ContentLicense: CC BY-SA 3.0

Title: Deleting a row in datagrid view


问:
Delete records referenced by other records in different tables
I have a following requirement:

I need to delete records from one table based on the given ID, now this table is referenced by another table and that other table is referenced by yet another table and that last table is also referenced by another table, so I have a chain like this:

table_1 <- table_2 <- table_3 <- table_4

I'm not that experienced with SQL so my solution involves using subqueries to perform this.

I have something like this:

```<code>DELETE FROM table_4
     WHERE pk_of_table_3 IN
               (SELECT id
                FROM table_3
                WHERE pk_of_table_2 IN
                          (SELECT id FROM table 2 WHERE pk_of_table_1 = ?
                          )
               )
</code>```

So this would clear records from table_4 which reference targeted records in table_3.

For table_3 I would do something like:

```<code>DELETE FROM table_3
    WHERE pk_of_table_2 IN
              (SELECT id FROM table_2 WHERE pk_of_table_1 = ?)
</code>```

Now I move to table_2:

```<code>DELETE FROM table_2 WHERE pk_of_table_1 = 5;
</code>```

So in the end it leaves me with possibility to cleanup necessary records from table_1 since it's not being constrained by anything.

I wanted to ask if this seems like viable solution and if there are better ways to do this?

答:
Do it with a common table expression that chains the DELETE statements:

```<code>with delete_t1 as (
  delete from table_1
  where pk = 42
  returning pk
), delete_t2 as (
  delete from table_2
  where pk_of_table_1 in (select pk from delete_t1)
  returning pk
), delete_t3 as (
  delete from table_3
  where pk_of_table_2 in (select pk from delete_t2)
  returning pk
)
delete from table_4
where pk_of_table_3 in (select pk from delete_t3);
</code>```

If you always do it like that, consider defining the foreign key constraints as on delete cascade, then you only need to delete from table_1 and Postgres will take care of the rest.

Body:
I have a following requirement:

I need to delete records from one table based on the given ID, now this table is referenced by another table and that other table is referenced by yet another table and that last table is also referenced by another table, so I have a chain like this:

table_1 <- table_2 <- table_3 <- table_4

I'm not that experienced with SQL so my solution involves using subqueries to perform this.

I have something like this:

DELETE FROM table_4
     WHERE pk_of_table_3 IN
               (SELECT id
                FROM table_3
                WHERE pk_of_table_2 IN
                          (SELECT id FROM table 2 WHERE pk_of_table_1 = ?
                          )
               )

So this would clear records from table_4 which reference targeted records in table_3.

For table_3 I would do something like:

DELETE FROM table_3
    WHERE pk_of_table_2 IN
              (SELECT id FROM table_2 WHERE pk_of_table_1 = ?)

Now I move to table_2:

DELETE FROM table_2 WHERE pk_of_table_1 = 5;

So in the end it leaves me with possibility to cleanup necessary records from table_1 since it's not being constrained by anything.

I wanted to ask if this seems like viable solution and if there are better ways to do this?

Body:
Do it with a common table expression that chains the DELETE statements:

with delete_t1 as (
  delete from table_1
  where pk = 42
  returning pk
), delete_t2 as (
  delete from table_2
  where pk_of_table_1 in (select pk from delete_t1)
  returning pk
), delete_t3 as (
  delete from table_3
  where pk_of_table_2 in (select pk from delete_t2)
  returning pk
)
delete from table_4
where pk_of_table_3 in (select pk from delete_t3);

If you always do it like that, consider defining the foreign key constraints as on delete cascade, then you only need to delete from table_1 and Postgres will take care of the rest.


问:
Checking a cell is Not IsEmpty in If Loop
I can't my nested If Loop working right.

I want the data in the TestTable column coped over IF there is a figure in there, if the cell is blank, I Want it to go to next i.

There are no runtime errors however, for some reason it is just copying every cell over, completely ignoring the NOT IsEmpty part?

```<code>Sub MoveData
Dim InTbl As ListObject, TeTbl As ListObject, i As Long, LastRow As Long, AmendedCCY

Set InTbl = ThisWorkbook.Sheets("Input").Range("Input").ListObject
Set TeTbl = ThisWorkbook.Sheets("Input").Range("TestTab").ListObject
Set AmendedCCY = InTbl.ListColumns(4).DataBodyRange

LastRow = AmendedCCY.Rows.Count

    For i = 1 To LastRow

        If Not IsEmpty("Input[Amended]") Then
         TeTbl.DataBodyRange(i, 2).Value = InTbl.DataBodyRange(i, 4).Value
        End If

    Next
End Sub

</code>```

I've also used the following:

If ("Input[Amended]") <> "" Then

If IsEmpty("Input[Amended]") = False Then

I guess there is an issue with the ("Input[Amended]") but I can't figure out what.

答:
"Input[Amended]" is just a constant string, filled with characters, hence it won't ever be empty.

You need to access the cell, containing the information you're looking for, something like:

```<code>IsEmpty(InTbl.DataBodyRange(i, 4).Value)
</code>```

Obviously I don't know if you should look in column 4 or in another one, so please change that value 4 accordingly.

Body:
I can't my nested If Loop working right.

I want the data in the TestTable column coped over IF there is a figure in there, if the cell is blank, I Want it to go to next i.

There are no runtime errors however, for some reason it is just copying every cell over, completely ignoring the NOT IsEmpty part?

Sub MoveData
Dim InTbl As ListObject, TeTbl As ListObject, i As Long, LastRow As Long, AmendedCCY

Set InTbl = ThisWorkbook.Sheets("Input").Range("Input").ListObject
Set TeTbl = ThisWorkbook.Sheets("Input").Range("TestTab").ListObject
Set AmendedCCY = InTbl.ListColumns(4).DataBodyRange

LastRow = AmendedCCY.Rows.Count

    For i = 1 To LastRow

        If Not IsEmpty("Input[Amended]") Then
         TeTbl.DataBodyRange(i, 2).Value = InTbl.DataBodyRange(i, 4).Value
        End If

    Next
End Sub

I've also used the following:

If ("Input[Amended]") <> "" Then

If IsEmpty("Input[Amended]") = False Then

I guess there is an issue with the ("Input[Amended]") but I can't figure out what.

Body:
"Input[Amended]" is just a constant string, filled with characters, hence it won't ever be empty.

You need to access the cell, containing the information you're looking for, something like:

IsEmpty(InTbl.DataBodyRange(i, 4).Value)

Obviously I don't know if you should look in column 4 or in another one, so please change that value 4 accordingly.


问:
node.js exported promise chain not running sequentially with web api callbacks
I have 2 files. One (get_data.js) gets data from an API by getting an access token, using that to get the URL containing the data, then getting the csv data from that URL and converting it to JSON.
The second file (process_data.js) just console.logs that JSON data.

Contents of get_data.js (in pseudo-code, as the file is quite long and the individual functions all work fine).

```<code>module.exports.getData = () => {
    new Promise((resolve, reject) => {
        resolve(get_access_token());           // returns an access token from a web api
    })

    .then((access_token) => {
        return new Promise((resolve, reject) => {
            resolve(get_url());                // returns a url from a web api
        })
    })

    .then((url) => {
        return new Promise ((resolve, reject) => {
            resolve(get_data_from_url(url));    // returns a csv in a string from url
        })
    })

    .then((csv_data) => {
        return new Promise ((resolve, reject) => {
            resolve(convert_csv_to_json());    // returns data in a json string
        })
    })
}

</code>```

Contents of process_data.js:

```<code>const dataHandler = require('./get_data');

dataHandler.getData()
.then(
    (JSON_data) => {
        console.log("JSON_data: ".concat(JSON_data))
    }
)
</code>```

What I want to happen is

run process_data.js

it gets the data from get_data.js

print that data to the console (for now)

However at the first API callback in get_data.js, the promise chain from process_data.js moves on and prints 'undefined', and I'm not sure why it's not waiting for the various callbacks from get_data.js.
What's strange is that if I run get_data.js with a console.log(json_data) appended to the end of the code it all works fine. The problem is I need to be able to subdivide my code into modules.
Any help would be greatly appreciated! Error printed to the console is below:

```<code>.then((JSON_data) => {console.log("JSON_data: ".concat(JSON_data))})
^

TypeError: Cannot read property 'then' of undefined
    at Object.<anonymous> (/Users/tom/Desktop/stuff/process_data.js:5:1)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11
</code>```

答:
In getData you are currently not returning anything. That's why the error is TypeError: Cannot read property 'then' of undefined since returning nothing returns an undefined.

In order to .then on dataHandler.getData() you need to return your first new Promise.

```<code>module.exports.getData = () => {
    return new Promise((resolve, reject) => {
        resolve(get_access_token());           // returns an access token from a web api
    })

    .then((access_token) => {
        return new Promise((resolve, reject) => {
            resolve(get_url());                // returns a url from a web api
        })
    })

    .then((url) => {
        return new Promise ((resolve, reject) => {
            resolve(get_data_from_url(url));    // returns a csv in a string from url
        })
    })

    .then((csv_data) => {
        return new Promise ((resolve, reject) => {
            resolve(convert_csv_to_json());    // returns data in a json string
        })
    })
}
</code>```

Body:
I have 2 files. One (get_data.js) gets data from an API by getting an access token, using that to get the URL containing the data, then getting the csv data from that URL and converting it to JSON.
The second file (process_data.js) just console.logs that JSON data.

Contents of get_data.js (in pseudo-code, as the file is quite long and the individual functions all work fine).

module.exports.getData = () => {
    new Promise((resolve, reject) => {
        resolve(get_access_token());           // returns an access token from a web api
    })

    .then((access_token) => {
        return new Promise((resolve, reject) => {
            resolve(get_url());                // returns a url from a web api
        })
    })

    .then((url) => {
        return new Promise ((resolve, reject) => {
            resolve(get_data_from_url(url));    // returns a csv in a string from url
        })
    })

    .then((csv_data) => {
        return new Promise ((resolve, reject) => {
            resolve(convert_csv_to_json());    // returns data in a json string
        })
    })
}

Contents of process_data.js:

const dataHandler = require('./get_data');

dataHandler.getData()
.then(
    (JSON_data) => {
        console.log("JSON_data: ".concat(JSON_data))
    }
)

What I want to happen is

run process_data.js

it gets the data from get_data.js

print that data to the console (for now)

However at the first API callback in get_data.js, the promise chain from process_data.js moves on and prints 'undefined', and I'm not sure why it's not waiting for the various callbacks from get_data.js.
What's strange is that if I run get_data.js with a console.log(json_data) appended to the end of the code it all works fine. The problem is I need to be able to subdivide my code into modules.
Any help would be greatly appreciated! Error printed to the console is below:

.then((JSON_data) => {console.log("JSON_data: ".concat(JSON_data))})
^

TypeError: Cannot read property 'then' of undefined
    at Object.<anonymous> (/Users/tom/Desktop/stuff/process_data.js:5:1)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11

Body:
In getData you are currently not returning anything. That's why the error is TypeError: Cannot read property 'then' of undefined since returning nothing returns an undefined.

In order to .then on dataHandler.getData() you need to return your first new Promise.

module.exports.getData = () => {
    return new Promise((resolve, reject) => {
        resolve(get_access_token());           // returns an access token from a web api
    })

    .then((access_token) => {
        return new Promise((resolve, reject) => {
            resolve(get_url());                // returns a url from a web api
        })
    })

    .then((url) => {
        return new Promise ((resolve, reject) => {
            resolve(get_data_from_url(url));    // returns a csv in a string from url
        })
    })

    .then((csv_data) => {
        return new Promise ((resolve, reject) => {
            resolve(convert_csv_to_json());    // returns data in a json string
        })
    })
}


问:
Can't read file after writing it to temp folder in .NET Core
In my scenario, I have an use case where I must received a compressed file, do some validations and then find a specific file within the archive that I'll have to handle through a third-party library. I'm having some trouble getting such library to read the file though. This is what I came up with so far:

```<code>public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        if (Path.GetExtension(entry.FullName).Equals(".shp"))
        {
            var stream = entry.Open();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            var fileName = Path.GetTempFileName();
            try
            {
                using var fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.ReadWrite);

                var bytes = new byte[ms.Length];
                ms.Read(bytes, 0, (int)ms.Length);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Flush();
                fileStream.Close();

                var featureSource = new ShapeFileFeatureSource(fileName); // Class from 3rd-party
                featureSource.Open();
                // Do my stuff with the shapefile
            }
            finally
            {
                File.Delete(fileName);
            }
        }
    }
}
</code>```

Take notice that I'm using the "old way" of copying streams as Stream.CopyTo and Stream.CopyToAsync were creating empty files, explicitly calling fileStream.Close() looks like the only way to get the bytes into the file somehow, but that's beyond my point. Regardless, after closing the stream, upon calling featureSource.Open() my application throws

```<code>"The process cannot access the file 'C:\\Users\\me\\AppData\\Local\\Temp\\tmpE926.tmp' because it is
being used by another process."
</code>```

tmpE926.tmp being different every time, obviously. Also take notice that I'm creating a file because the constructor for ShapeFileFeatureSource demands not a stream, not a byte array, but a path.

A much shorter implementation

```<code>public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        var tempFile = Path.GetTempFileName();
        try
        {
            entry.ExtractToFile(tempFile, true);

            if (Path.GetExtension(entry.FullName).Equals(".shp"))
            {
                var featureSource = new ShapeFileFeatureSource(tempFile);
                featureSource.Open();
                var type = featureSource.GetShapeFileType();
            }
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
}
</code>```

will actually amount to the same error. I honestly don't think the problem lies within this library, but rather I'm the one screwing it up somehow. Does anyone have any ideas or should I contact the vendor's (unresponsive) tech support?

Edit: Just in case, this is such library Install-Package ThinkGeo.UI.WebApi but you have to subscribe to evaluate in order to use it.

答:
This code morphed for a couple of days until I reached out to tech support, they tinkered with it a bit and came up with this:

```<code>public async Task ProcessFile(IFormFile file)
{
    if (!Path.GetExtension(file.FileName).Equals(".zip"))
        throw new System.Exception("File should be compressed in '.zip' format");

    var filePaths = new List<string>();

    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);

        using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, false))
        {

            var replaceList = new Dictionary<string, string>();

            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                var tempPath = Path.GetTempFileName();

                string key = Path.GetFileNameWithoutExtension(entry.FullName);

                string value = Path.GetFileNameWithoutExtension(tempPath);

                if (replaceList.ContainsKey(key))
                {
                    value = replaceList[key];
                }
                else
                {
                    replaceList.Add(key, value);
                }

                string unzippedPath = Path.Combine(Path.GetDirectoryName(tempPath), value + Path.GetExtension(entry.FullName));

                entry.ExtractToFile(unzippedPath, true);
                filePaths.Add(unzippedPath);
            }

            foreach (var unzippedPath in filePaths)
            {
                if (Path.GetExtension(unzippedPath).Equals(".shp"))
                {
                    // Successfully doing third-party library stuff
                }
            }

            foreach (var unzippedPath in filePaths)
            {
                if (File.Exists(unzippedPath))
                {
                    File.Delete(unzippedPath);
                }
            }
        }
    }
}
</code>```

It works. I'm happy.

Body:
In my scenario, I have an use case where I must received a compressed file, do some validations and then find a specific file within the archive that I'll have to handle through a third-party library. I'm having some trouble getting such library to read the file though. This is what I came up with so far:

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        if (Path.GetExtension(entry.FullName).Equals(".shp"))
        {
            var stream = entry.Open();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            var fileName = Path.GetTempFileName();
            try
            {
                using var fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.ReadWrite);

                var bytes = new byte[ms.Length];
                ms.Read(bytes, 0, (int)ms.Length);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Flush();
                fileStream.Close();

                var featureSource = new ShapeFileFeatureSource(fileName); // Class from 3rd-party
                featureSource.Open();
                // Do my stuff with the shapefile
            }
            finally
            {
                File.Delete(fileName);
            }
        }
    }
}

Take notice that I'm using the "old way" of copying streams as Stream.CopyTo and Stream.CopyToAsync were creating empty files, explicitly calling fileStream.Close() looks like the only way to get the bytes into the file somehow, but that's beyond my point. Regardless, after closing the stream, upon calling featureSource.Open() my application throws

"The process cannot access the file 'C:\\Users\\me\\AppData\\Local\\Temp\\tmpE926.tmp' because it is
being used by another process."

tmpE926.tmp being different every time, obviously. Also take notice that I'm creating a file because the constructor for ShapeFileFeatureSource demands not a stream, not a byte array, but a path.

A much shorter implementation

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        var tempFile = Path.GetTempFileName();
        try
        {
            entry.ExtractToFile(tempFile, true);

            if (Path.GetExtension(entry.FullName).Equals(".shp"))
            {
                var featureSource = new ShapeFileFeatureSource(tempFile);
                featureSource.Open();
                var type = featureSource.GetShapeFileType();
            }
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
}

will actually amount to the same error. I honestly don't think the problem lies within this library, but rather I'm the one screwing it up somehow. Does anyone have any ideas or should I contact the vendor's (unresponsive) tech support?

Edit: Just in case, this is such library Install-Package ThinkGeo.UI.WebApi but you have to subscribe to evaluate in order to use it.

Body:
This code morphed for a couple of days until I reached out to tech support, they tinkered with it a bit and came up with this:

public async Task ProcessFile(IFormFile file)
{
    if (!Path.GetExtension(file.FileName).Equals(".zip"))
        throw new System.Exception("File should be compressed in '.zip' format");

    var filePaths = new List<string>();

    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);

        using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, false))
        {

            var replaceList = new Dictionary<string, string>();

            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                var tempPath = Path.GetTempFileName();

                string key = Path.GetFileNameWithoutExtension(entry.FullName);

                string value = Path.GetFileNameWithoutExtension(tempPath);

                if (replaceList.ContainsKey(key))
                {
                    value = replaceList[key];
                }
                else
                {
                    replaceList.Add(key, value);
                }

                string unzippedPath = Path.Combine(Path.GetDirectoryName(tempPath), value + Path.GetExtension(entry.FullName));

                entry.ExtractToFile(unzippedPath, true);
                filePaths.Add(unzippedPath);
            }

            foreach (var unzippedPath in filePaths)
            {
                if (Path.GetExtension(unzippedPath).Equals(".shp"))
                {
                    // Successfully doing third-party library stuff
                }
            }

            foreach (var unzippedPath in filePaths)
            {
                if (File.Exists(unzippedPath))
                {
                    File.Delete(unzippedPath);
                }
            }
        }
    }
}

It works. I'm happy.


问:
SQL Server 2008 r2: data being truncated when running via a scheduled job but not via the command line
Using Sql Server 2008 r2 and I can get a process to work perfectly while executing it myself. When I set it up to run as a job, the binary field is getting truncated to 2kb (2048 characters) every single time.   Below are the details of exactly what is going on.

Here is the basic process my stored procedure.

Dynamically build sql statement that inserts a data set (usually 10 to 15 rows) from a linked server to a user defined table variable. (The data set basically contains information about photos.  mime/type, order, description, and the binary (or the blob) of the specific photo.)

That table variable is then passed to another stored procedure that saves the data set

As stated before, when I execute the stored procedure, the process works perfectly. The blob is a complete and generates a great looking photo.  However when the stored procedure is executed via a scheduled job, the binary string is truncated after 2048 characters.  And this happens every single time without fail.

I have been able to determine that the truncation is coming from OPENQUERY statement I'm using to pull the data out of the linked server, but I cannot figure out WHY it is happening during the scheduled job and not when I just run it.  I would think it was a permission issue, it would just fail to pull back anything.

Thanks in advance for your help, Will

答: Take a look at documention in BOL for TEXTSIZE, and try setting it to a larger value in the stored proc.</p>


问:
Class inheritance and instantiation - confusion between internal calls to __init__() and __new__() methods
This is a follow-up question to a problem I previously posted that was partially resolved with the answer I received.

The scenario is that I have 1 class that is defined at run time, that inherits from a class that is defined based on a type: MasterData or Transaction, which on its turn, inherits from the BusinessDocument.

The BusinessDocument class needs to inherit from a class Thing which is available through an external module.

The following code has been implemented to create all the classes in the chain:

```<code>from owlready2 import *

with onto:
    class BusinessDocument(Thing):
        @staticmethod
        def get_class(doc_type):
            switch = {
                'MasterData': MasterData,
                'Transactional': Transactional
            }
            cls = switch.get(doc_type, lambda: "Invalid Noun Type")
            return cls

        def __init__(self, doc_id, location, doc_type, color, size):
            self.doc_id = doc_id
            self.location = location
            self.doc_type = doc_type
            self.color = color
            self.size = size

        @property
        def get_location(self):
            return self.location

        @property
        def get_doc_id(self):
            return self.doc_id

with onto:
    class MasterData(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'MasterData')

with onto:
    class Transactional(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'Transactional')

with onto:
    class NounClass():
        @staticmethod
        def get_class(doc_name, doc_type):
            return type(doc_name, (BusinessDocument.get_class(doc_type),
                               BusinessDocument, ),dict.fromkeys(['doc_id', 'location', 'color', 'size',]))
</code>```

At run time when I get the doc_name and I get a new class, but when I try to instantiate.

```<code>invoice_cls = NounClass.get_class('Invoice', 'Transactional')
my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')
</code>```

Calls to the type() and mro() methods for the invoice_cls gives me the following information:

DEBUG:app.__main__:Type of from_noun is [(bod_ontology.Invoice, bod_ontology.MasterData, bod_ontology.BusinessDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]
```

<p>But then I get an exception thrown related to the <code>__new__()</code> method:</p>

```DEBUG:app.__main__:Type of from_noun is [(bod_ontology.BillFromPartyMaster, bod_ontology.MasterData, bod_ontology.BusinessObjectDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')
--- Logging error ---
Traceback (most recent call last):
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')
TypeError: __new__() takes from 1 to 3 positional arguments but 5 were given

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 1081, in emit
    msg = self.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 925, in format
    return fmt.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 664, in format
    record.message = record.getMessage()
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 369, in getMessage
    msg = msg % self.args
TypeError: must be real number, not TypeError
Call stack:
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 520, in <module>
    exit(main())
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 515, in main
    query_database()
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 103, in query_database
    csv_record = parse_xml(bod_type, date_time, from_lid, tenant, xml_string)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 174, in parse_xml
    log.debug("Got an error [%e]", e)
Arguments: (TypeError('__new__() takes from 1 to 3 positional arguments but 5 were given'),)

```

<p>Then if I try to make the instantiation call without the arguments, I get a different exception related to the <code>__init__()</code> method, and here is the full :</p>

```DEBUG:app.__main__:Type of from_noun is [(bod_ontology.BillFromPartyMaster, bod_ontology.MasterData, bod_ontology.BusinessObjectDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls()
--- Logging error ---
Traceback (most recent call last):
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_obj = MyCls()
TypeError: __init__() missing 4 required positional arguments: 'doc_id', 'location', 'color', and 'size'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 1081, in emit
    msg = self.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 925, in format
    return fmt.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 664, in format
    record.message = record.getMessage()
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 369, in getMessage
    msg = msg % self.args
TypeError: must be real number, not TypeError
Call stack:
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 520, in <module>
    exit(main())
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 515, in main
    query_database()
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 103, in query_database
    csv_record = parse_xml(bod_type, date_time, from_lid, tenant, xml_string)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 174, in parse_xml
    log.debug("Got an error [%e]", e)
Arguments: (TypeError("__init__() missing 4 required positional arguments: 'doc_id', 'location', 'color', and 'size'"),)

```

This only happens when I inherit from the 'Thing' class. If I remove the inheritance the code runs just fine.
It looks like I am messing up with the instantiation sequence in the class hierarchy.

答: The problem seems to be caused by the Thing class as I suspected and also confirmed by @quamrana. </p>

Body:
This is a follow-up question to a problem I previously posted that was partially resolved with the answer I received.

The scenario is that I have 1 class that is defined at run time, that inherits from a class that is defined based on a type: MasterData or Transaction, which on its turn, inherits from the BusinessDocument.

The BusinessDocument class needs to inherit from a class Thing which is available through an external module.

The following code has been implemented to create all the classes in the chain:

from owlready2 import *

with onto:
    class BusinessDocument(Thing):
        @staticmethod
        def get_class(doc_type):
            switch = {
                'MasterData': MasterData,
                'Transactional': Transactional
            }
            cls = switch.get(doc_type, lambda: "Invalid Noun Type")
            return cls

        def __init__(self, doc_id, location, doc_type, color, size):
            self.doc_id = doc_id
            self.location = location
            self.doc_type = doc_type
            self.color = color
            self.size = size

        @property
        def get_location(self):
            return self.location

        @property
        def get_doc_id(self):
            return self.doc_id

with onto:
    class MasterData(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'MasterData')

with onto:
    class Transactional(BusinessDocument):
        def __init__(self, doc_id, location, color, size):
            BusinessDocument.__init__(self, doc_id, location, color, size, 'Transactional')

with onto:
    class NounClass():
        @staticmethod
        def get_class(doc_name, doc_type):
            return type(doc_name, (BusinessDocument.get_class(doc_type),
                               BusinessDocument, ),dict.fromkeys(['doc_id', 'location', 'color', 'size',]))

At run time when I get the doc_name and I get a new class, but when I try to instantiate.

invoice_cls = NounClass.get_class('Invoice', 'Transactional')
my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')

Calls to the type() and mro() methods for the invoice_cls gives me the following information:

DEBUG:app.__main__:Type of from_noun is [(bod_ontology.Invoice, bod_ontology.MasterData, bod_ontology.BusinessDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]

But then I get an exception thrown related to the __new__() method:

DEBUG:app.__main__:Type of from_noun is [(bod_ontology.BillFromPartyMaster, bod_ontology.MasterData, bod_ontology.BusinessObjectDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')
--- Logging error ---
Traceback (most recent call last):
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls('IN-1234', 'New York', 'blue', 'big')
TypeError: __new__() takes from 1 to 3 positional arguments but 5 were given

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 1081, in emit
    msg = self.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 925, in format
    return fmt.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 664, in format
    record.message = record.getMessage()
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 369, in getMessage
    msg = msg % self.args
TypeError: must be real number, not TypeError
Call stack:
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 520, in <module>
    exit(main())
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 515, in main
    query_database()
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 103, in query_database
    csv_record = parse_xml(bod_type, date_time, from_lid, tenant, xml_string)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 174, in parse_xml
    log.debug("Got an error [%e]", e)
Arguments: (TypeError('__new__() takes from 1 to 3 positional arguments but 5 were given'),)

Then if I try to make the instantiation call without the arguments, I get a different exception related to the __init__() method, and here is the full :

DEBUG:app.__main__:Type of from_noun is [(bod_ontology.BillFromPartyMaster, bod_ontology.MasterData, bod_ontology.BusinessObjectDocument, owl.Thing, <class 'object'>)]
DEBUG:app.__main__:Class type is [<class 'owlready2.entity.ThingClass'>]
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_invoice = invoice_cls()
--- Logging error ---
Traceback (most recent call last):
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 167, in parse_xml
    my_obj = MyCls()
TypeError: __init__() missing 4 required positional arguments: 'doc_id', 'location', 'color', and 'size'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 1081, in emit
    msg = self.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 925, in format
    return fmt.format(record)
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 664, in format
    record.message = record.getMessage()
  File "/Users/cracoras/.pyenv/versions/3.8.1/lib/python3.8/logging/__init__.py", line 369, in getMessage
    msg = msg % self.args
TypeError: must be real number, not TypeError
Call stack:
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 520, in <module>
    exit(main())
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 515, in main
    query_database()
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 103, in query_database
    csv_record = parse_xml(bod_type, date_time, from_lid, tenant, xml_string)
  File "/Users/cracoras/PycharmProjects/bod2owl/app/convert_data.py", line 174, in parse_xml
    log.debug("Got an error [%e]", e)
Arguments: (TypeError("__init__() missing 4 required positional arguments: 'doc_id', 'location', 'color', and 'size'"),)

This only happens when I inherit from the 'Thing' class. If I remove the inheritance the code runs just fine.
It looks like I am messing up with the instantiation sequence in the class hierarchy.


问:
How to get instance by base type from IServiceProvider.GetServices<T> (aspnet core DI)?
I would like to get all services that inherite MyBaseClass from IServiceProvider:

```<code>var myBaseClassInstances = serviceProvider.GetServices<MyBaseClass>();
</code>```

I can register all derived classes as:

```<code>services.AddSingleton<InheritedFromMyBaseClass>();
services.AddSingleton<MyBaseClass>(serviceProvider => serviceProvider.GetService<InheritedFromMyBaseClass>());
</code>```

Are there any ways to do this with one registration?

答: The dependency injection that comes with .NET Core does not allow that out of the box, you need to roll out your custom extension method. </p>

Body:
I would like to get all services that inherite MyBaseClass from IServiceProvider:

var myBaseClassInstances = serviceProvider.GetServices<MyBaseClass>();

I can register all derived classes as:

services.AddSingleton<InheritedFromMyBaseClass>();
services.AddSingleton<MyBaseClass>(serviceProvider => serviceProvider.GetService<InheritedFromMyBaseClass>());

Are there any ways to do this with one registration?


问:
AWS Lambda is not invoked if byte array is published via mqtt
I have created a rule in AWS-iot to invoke a lambda with following query:

```<code>select * from 'my_topic'
</code>```

This rule will invoke a below javascript lambda:

```<code>var AWS = require('aws-sdk');
var zlib = require('zlib');
var s3 = new AWS.S3();

        exports.handler = (event, context, callback) => {
            console.log("hello:");
            var bucketName = "otonomobucket";
            var keyName = getKeyName("myData", Date.now());
            var content = event;
            //var content = JSON.stringify(event);

            console.log("event data:" + content);

            var params = { Bucket: bucketName, Key: keyName, Body: content };

            s3.putObject(params, function (err, data) {
                if (err)
                    console.log(err)
                else
                    console.log("Successfully saved object to " + bucketName + "/" + keyName);
            });
        };

        function getKeyName(folder, filename) {
            return folder + '/' + filename + ".txt";
        }
</code>```

The lambda works perfectly if i publish any string to my_topic. But the lambda is not working if i publish bytearray to my_topic. CloudWatch is also not showing any logs. How could i get the byte array into my lambda function.

答:
The lambda can receive binary data as long as it is base64 encoded and in a JSON payload. This can be done by changing the rule to:

```<code>SELECT encode(*, 'base64') AS data FROM 'my_topic'
</code>```

The documentation on binary payloads in the SELECT clause indicates that SELECT * FROM 'a/b' should work. But in my experience this only works for non-JSON payloads with some actions (e.g. writing to S3) and not with others (sending it to a lambda or Kinesis stream).

This appears to be an issue with how the lambda is invoked.

From https://forums.aws.amazon.com/thread.jspa?messageID=925603&#925603

AWS Lambda only accepts JSON payloads [1] so the Lambda action will only work for json payloads. This is a common problem and we recommend modifying your rule to base64 encode the binary into a json blob like so:

select encode(*, 'base64') as data from 'some/topic'

Your Lambda function will then need to be modified to decode the 'data' key in the event body.

[1] https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestBody

My hypothesis is that the lambda invocation uses the lambda REST API. This requires a JSON payload in the request body as described in the link to the API_Invoke_RequestBody

Body:
I have created a rule in AWS-iot to invoke a lambda with following query:

select * from 'my_topic'

This rule will invoke a below javascript lambda:

var AWS = require('aws-sdk');
var zlib = require('zlib');
var s3 = new AWS.S3();

        exports.handler = (event, context, callback) => {
            console.log("hello:");
            var bucketName = "otonomobucket";
            var keyName = getKeyName("myData", Date.now());
            var content = event;
            //var content = JSON.stringify(event);

            console.log("event data:" + content);

            var params = { Bucket: bucketName, Key: keyName, Body: content };

            s3.putObject(params, function (err, data) {
                if (err)
                    console.log(err)
                else
                    console.log("Successfully saved object to " + bucketName + "/" + keyName);
            });
        };

        function getKeyName(folder, filename) {
            return folder + '/' + filename + ".txt";
        }

The lambda works perfectly if i publish any string to my_topic. But the lambda is not working if i publish bytearray to my_topic. CloudWatch is also not showing any logs. How could i get the byte array into my lambda function.

Body:
The lambda can receive binary data as long as it is base64 encoded and in a JSON payload. This can be done by changing the rule to:

SELECT encode(*, 'base64') AS data FROM 'my_topic'

The documentation on binary payloads in the SELECT clause indicates that SELECT * FROM 'a/b' should work. But in my experience this only works for non-JSON payloads with some actions (e.g. writing to S3) and not with others (sending it to a lambda or Kinesis stream).

This appears to be an issue with how the lambda is invoked.

From https://forums.aws.amazon.com/thread.jspa?messageID=925603&#925603

AWS Lambda only accepts JSON payloads [1] so the Lambda action will only work for json payloads. This is a common problem and we recommend modifying your rule to base64 encode the binary into a json blob like so:

select encode(*, 'base64') as data from 'some/topic'

Your Lambda function will then need to be modified to decode the 'data' key in the event body.

[1] https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestBody

My hypothesis is that the lambda invocation uses the lambda REST API. This requires a JSON payload in the request body as described in the link to the API_Invoke_RequestBody


问:
Angular 8 : How to do calculation on observable object's two properties and need to save on another property
I need to show sum of two properties of an observable data. here is my code Please advice me how to fix it.

Typescript class

```<code>export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}
</code>```

In typescript service:

I have declared the observable object

```<code>export class AmountService {
 public newmessageService = new BehaviorSubject(new Amount());
  public Model = this.newmessageService.asObservable();
}
</code>```

In Component Class:

subscribed that observable Model in calcuation component

```<code>export class Calculation implements OnInit {
Model$:Amount;
  ngOnInit() {
    this.service.Model.subscribe(temp => this.Model$ = temp)
  }
}
</code>```

In component view :

In the view, Amount1 and Amount2 property are declared for inputs and total is displayed.

```<code>  <form name="calculationform">

  <mat-form-field class="example-full-width">
    <mat-label>Amount1</mat-label>
    <input matInput [(ngModel)]="Model$.Amount1" name="Amount1">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <mat-label>Amount2</mat-label>
    <input matInput [(ngModel)]="Model$.Amount2" name="Amount2">
  </mat-form-field>

      <mat-label>Total:</mat-label>
      <mat-label>{{Model$.Total}}</mat-label>
</form>
</code>```

I need to show the sum of Amount1 and Amount2 on Total property when ever we change the amount.

Thank you.

答:
Please try</p>

```<code>ngDoCheck( ){
   this.service.Model.subscribe(temp => {
      this.Model$ = temp;
      this.Model$.Total = Number(this.Model$.Amount1) + Number(this.Model$.Amount2);
   });
}
</code>```

Body:
I need to show sum of two properties of an observable data. here is my code Please advice me how to fix it.

Typescript class

export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}

In typescript service:

I have declared the observable object

export class AmountService {
 public newmessageService = new BehaviorSubject(new Amount());
  public Model = this.newmessageService.asObservable();
}

In Component Class:

subscribed that observable Model in calcuation component

export class Calculation implements OnInit {
Model$:Amount;
  ngOnInit() {
    this.service.Model.subscribe(temp => this.Model$ = temp)
  }
}

In component view :

In the view, Amount1 and Amount2 property are declared for inputs and total is displayed.

  <form name="calculationform">

  <mat-form-field class="example-full-width">
    <mat-label>Amount1</mat-label>
    <input matInput [(ngModel)]="Model$.Amount1" name="Amount1">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <mat-label>Amount2</mat-label>
    <input matInput [(ngModel)]="Model$.Amount2" name="Amount2">
  </mat-form-field>

      <mat-label>Total:</mat-label>
      <mat-label>{{Model$.Total}}</mat-label>
</form>

I need to show the sum of Amount1 and Amount2 on Total property when ever we change the amount.

Thank you.

Body:
Please try

ngDoCheck( ){
   this.service.Model.subscribe(temp => {
      this.Model$ = temp;
      this.Model$.Total = Number(this.Model$.Amount1) + Number(this.Model$.Amount2);
   });
}


问:
How to get the current directory of the cmdlet being executed
This should be a simple task, but I have seen several attempts on how to get the path to the directory where the executed cmdlet is located with mixed success. For instance, when I execute C:\temp\myscripts\mycmdlet.ps1 which has a settings file at C:\temp\myscripts\settings.xml I would like to be able to store C:\temp\myscripts in a variable within mycmdlet.ps1.

This is one solution which works (although a bit cumbersome):

```<code>$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$settingspath = $directorypath + '\settings.xml'
</code>```

Another one suggested this solution which only works on our test environment:

```<code>$settingspath = '.\settings.xml'
</code>```

I like the latter approach a lot and prefer it to having to parse the filepath as a parameter each time, but I can't get it to work on my development environment. What should I do? Does it have something to do with how PowerShell is configured?

答:
this function will set the prompt location to script path, dealing with the differents way to get scriptpath between vscode, psise and pwd :</p>

```<code>function Set-CurrentLocation
{
    $currentPath = $PSScriptRoot                                                                                # AzureDevOps, Powershell
    if (!$currentPath) { $currentPath = Split-Path $pseditor.GetEditorContext().CurrentFile.Path -ErrorAction SilentlyContinue }     # VSCode
    if (!$currentPath) { $currentPath = Split-Path $psISE.CurrentFile.FullPath -ErrorAction SilentlyContinue }                       # PsISE

    if ($currentPath) { Set-Location $currentPath }
}
</code>```

Body:
This should be a simple task, but I have seen several attempts on how to get the path to the directory where the executed cmdlet is located with mixed success. For instance, when I execute C:\temp\myscripts\mycmdlet.ps1 which has a settings file at C:\temp\myscripts\settings.xml I would like to be able to store C:\temp\myscripts in a variable within mycmdlet.ps1.

This is one solution which works (although a bit cumbersome):

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$settingspath = $directorypath + '\settings.xml'

Another one suggested this solution which only works on our test environment:

$settingspath = '.\settings.xml'

I like the latter approach a lot and prefer it to having to parse the filepath as a parameter each time, but I can't get it to work on my development environment. What should I do? Does it have something to do with how PowerShell is configured?

Body:
this function will set the prompt location to script path, dealing with the differents way to get scriptpath between vscode, psise and pwd :

function Set-CurrentLocation
{
    $currentPath = $PSScriptRoot                                                                                # AzureDevOps, Powershell
    if (!$currentPath) { $currentPath = Split-Path $pseditor.GetEditorContext().CurrentFile.Path -ErrorAction SilentlyContinue }     # VSCode
    if (!$currentPath) { $currentPath = Split-Path $psISE.CurrentFile.FullPath -ErrorAction SilentlyContinue }                       # PsISE

    if ($currentPath) { Set-Location $currentPath }
}


问:
MongoDb - cursor option is required after upgrade of mongodb
Since we were forced to upgrade our mongo installation, we're receiving an error during some aggregation function calls:

MongoDB.Driver.MongoCommandException: "Command 'aggregate' failed: The
  'cursor' option is required, except for aggregate with the explain
  argument (response: { "ok" : 0.0, "errmsg" : "The 'cursor' option is
  required, except for aggregate with the explain argument", "code" : 9,
  "codeName" : "FailedToParse" })"

```<code>        BsonArray arr = BsonSerializer.Deserialize<BsonArray>("[{ \"$match\" : { \"Param1\" : \"VAL\" } }, { \"$unwind\" : \"$Entries\" }, { \"$match\" : { \"PARAM\" : \"VALUE\" } }]");
        var pipeline = arr.Select(x => x.AsBsonDocument).ToList();
        // AggregateArgs aArgs = new AggregateArgs { Pipeline = bsonList };
        var cursor = collection.Aggregate(pipeline).ResultDocuments;
</code>```

I already figured out, that we have to manually add cursor configuration to the BsonDocument - but we weren't able to figure out, how the query should be configured.

Is there any work around for this exception (without changing drivers)?

答: You have extra brace in the end of query string</p>

Body:
Since we were forced to upgrade our mongo installation, we're receiving an error during some aggregation function calls:

MongoDB.Driver.MongoCommandException: "Command 'aggregate' failed: The
  'cursor' option is required, except for aggregate with the explain
  argument (response: { "ok" : 0.0, "errmsg" : "The 'cursor' option is
  required, except for aggregate with the explain argument", "code" : 9,
  "codeName" : "FailedToParse" })"

        BsonArray arr = BsonSerializer.Deserialize<BsonArray>("[{ \"$match\" : { \"Param1\" : \"VAL\" } }, { \"$unwind\" : \"$Entries\" }, { \"$match\" : { \"PARAM\" : \"VALUE\" } }]");
        var pipeline = arr.Select(x => x.AsBsonDocument).ToList();
        // AggregateArgs aArgs = new AggregateArgs { Pipeline = bsonList };
        var cursor = collection.Aggregate(pipeline).ResultDocuments;

I already figured out, that we have to manually add cursor configuration to the BsonDocument - but we weren't able to figure out, how the query should be configured.

Is there any work around for this exception (without changing drivers)?


问:
What are the RTP Libraries in Python with good RTCP Support?
I am looking for a RTP/RTCP Library that is open source.
I plan to use Python.</p>

答:
GStreamer. Open source multimedia framework

This is a good framework for doing RTP in. It is widely used on a number of platforms and has bindings in many different languages.

Here is a link to the python bindings of GStreamer

Advantages to using GStreamer:

Cross Platform

Cross Language

Comprehensive and simple API

Good documentation

Supports almost all multimedia
formats.

Disadvantages:

Adds a dependency

Adds learning requirements to the
project


问:
When do Karnaugh Map terms make no groups?
I understand how K-Maps work and what their utility is, but I can't seem to figure out under what conditions there could be no groups made. (When an expression is not simplifiable further? Won't it always be while speaking of canonical terms?)
Do help me out.</p>

答:
These are the conditions to make groups obtained from here:

Groups must be formed by combining 1, 2, 4 or usually 2n cells.

Cells can be grouped either in horizontal or vertical direction but not diagonally.

The cell having the zero value should not included in the groups.

Group must be as big as possible.

Overlapping of the groups are allowed.

Groups can be formed by wrapping around the grid.

No ones should be left alone.

So you cannot make groups for any situation not falling into any one of the above.


问:
How to configure the logger of schema registry image with helm chart deployment
I use schema registry 5.4 - https://hub.docker.com/r/confluentinc/cp-schema-registry/, and use helm chart https://github.com/helm/charts/tree/master/incubator/schema-registry to deploy.

To set my logger, I create a configmap and mount it to the schema registry container that uses the image -confluentinc/cp-schema-registry:5.4.0

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "schema-registry.fullname" . }}-log4j-configmap
  labels:
    app: {{ template "schema-registry.name" . }}
    chart: {{ template "schema-registry.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  log4j.properties: |+
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.encoding=UTF-8
</code>```

But I don't know what should be changed in the command of the container, or there is a variable pointing to log4j.properties to set it?
for example I plan to change the command like the following:

```<code>command:
- java
- -Dlog4j.configuration=file:/etc/schema-registry-log4j/log4j.properties
- -jar
- schema-registry.jar
</code>```

答:
Option 1:

One way I found is to build a new image using FROM and put my custom log4j properties there.

https://docs.confluent.io/current/installation/docker/development.html#log-to-external-volumes

Option 2:
The other way is to set an environment variable

SCHEMA_REGISTRY_LOG4J_LOGGERS="org.apache.kafka=ERROR,io.confluent.rest.exceptions=FATAL"

Body:
I use schema registry 5.4 - https://hub.docker.com/r/confluentinc/cp-schema-registry/, and use helm chart https://github.com/helm/charts/tree/master/incubator/schema-registry to deploy.

To set my logger, I create a configmap and mount it to the schema registry container that uses the image -confluentinc/cp-schema-registry:5.4.0

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "schema-registry.fullname" . }}-log4j-configmap
  labels:
    app: {{ template "schema-registry.name" . }}
    chart: {{ template "schema-registry.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  log4j.properties: |+
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.encoding=UTF-8

But I don't know what should be changed in the command of the container, or there is a variable pointing to log4j.properties to set it?
for example I plan to change the command like the following:

command:
- java
- -Dlog4j.configuration=file:/etc/schema-registry-log4j/log4j.properties
- -jar
- schema-registry.jar


问:
How to loop for adding BatchNormalization after every conv2d layer in pretrain model
I have a pretrain model (vgg16) from keras.  I'm trying to add BatchNormalization layer after every conv2d by looping.  However, it seems that I could not all of them together.  Here is my code.

```<code>from keras.applications import VGG16
from keras.layers import BatchNormalization, Input
from keras.models import Model

input_tensor = Input(shape=(256, 256, 3))
pretrain = VGG16(weights="imagenet", include_top=False, input_tensor=input_tensor)

            model = pretrain.layers[0].input
            for i in range(len(pretrain.layers)):
                x = pretrain.layers[i].output
                if "conv" in pretrain.layers[i].name:
                    x = pretrain.layers[i].output
                    x = BatchNormalization(axis=-1)(x)

                model = Model(input=model.input, output=x)
</code>```

May I have your suggestions?  Thank you in advance

答:
You should build a new model by copying layers from VGG and adding your own where you want.

The problem now is that the conv. layers are connected to the batch norm but which are not connected to anything.

Body:
I have a pretrain model (vgg16) from keras.  I'm trying to add BatchNormalization layer after every conv2d by looping.  However, it seems that I could not all of them together.  Here is my code.

from keras.applications import VGG16
from keras.layers import BatchNormalization, Input
from keras.models import Model

input_tensor = Input(shape=(256, 256, 3))
pretrain = VGG16(weights="imagenet", include_top=False, input_tensor=input_tensor)

            model = pretrain.layers[0].input
            for i in range(len(pretrain.layers)):
                x = pretrain.layers[i].output
                if "conv" in pretrain.layers[i].name:
                    x = pretrain.layers[i].output
                    x = BatchNormalization(axis=-1)(x)

                model = Model(input=model.input, output=x)

May I have your suggestions?  Thank you in advance


问:
Why the CPU usage of a GKE Workload is not equal to the sum of the CPU usage of its pods?
I'm trying to figure out why a GKE "Workload" CPU usage is not equivalent to the sum of cpu usage of its pods.

Following image shows a Workload CPU usage.

Service Workload CPU Usage

Following images show pods CPU usage for the above Workload.

Pod #1 CPU Usage

Pod #2 CPU Usage

For example, at 9:45, the Workload cpu usage was around 3.7 cores, but at the same time Pod#1 CPU usage was around 0.9 cores and Pod#2 CPU usage was around 0.9 cores too. It means, the service Workload CPU Usage should have been around 1.8 cores, but it wasn't.

Does anyone have an idea of this behavior?

Thanks.

答:
I suspect this is a bug in the UI. There is no actual metric for deployment CPU usage. Stackdriver Monitoring only collects data on container, pod, and node level metrics thus the only really reliable metrics in this case are the ones for pod CPU usage.

The graph for the total deployment CPU usage is likely meant to be a sum of all the pods metrics calculated and then presented to you. It is not as reliable as the pod or container metrics since it is not a direct metric.

If you are seeing this discrepancy consistently, I recommend opening a UI bug report through the Google Public Issue Tracker to report this to the GCP Engineers.


问:
does luaExpat provide apis to find tag or attributes?
I'm using LuaExpat to do some xml parsing.
I wonder whether it provides apis to do "getTag", "getAttribute", so I have to write that by myself.</p>

答:
You are supposed to pass callback functions to LuaExpat which enables you to extract values, print stuff out or whatever your use case is. Below is a short example that prints out the id attribute of an element.

```<code>p = lxp.new({ StartElement = function(parser, elementName, attributes)
                           print(attributes.id)
                         end
})
p:parse('<xml id="123"></xml>') --> 123
</code>```

I recommend checking out http://www.keplerproject.org/luaexpat/manual.html for more instructions.

Body:
You are supposed to pass callback functions to LuaExpat which enables you to extract values, print stuff out or whatever your use case is. Below is a short example that prints out the id attribute of an element.

p = lxp.new({ StartElement = function(parser, elementName, attributes)
                           print(attributes.id)
                         end
})
p:parse('<xml id="123"></xml>') --> 123

I recommend checking out http://www.keplerproject.org/luaexpat/manual.html for more instructions.


问:
Tensorboard Graph: Profiler session started
I wanted to show my network graph on tensorboard using tensorflow 2. I followed this tutorial and I did a code that was something like this:

```<code>for epoch in range(epochs):
    # Bracket the function call with
    # tf.summary.trace_on() and tf.summary.trace_export().
    tf.summary.trace_on(graph=True, profiler=True)
    # Call only one tf.function when tracing.
    z = train_step(x, y)
    with writer.as_default():
        tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)
</code>```

When doing that, I got the message Profiler session started. several times. When I open tensorboard, of course, the Graph said an error occurred and couldn't show anything.

答:
I found the response here.

Actually, you can enable graph export in v2. You'll need to call
  tf.summary.trace_on() before the code you want to trace the graph for
  (e.g. L224 if you just want the train step), and then call
  tf.summary.trace_off() after the code completes. Since you only need
  one trace of the graph, I would recommend wrapping these calls with if
  global_step_val == 0: so that you don't produce traces every step.

Actually, to create the graph it is necessary to do the trace just once and makes no sense of doing it at each epoch. The solution is just to check before calling the trace just once like:

```<code>for epoch in range(epochs):
    if epoch == 0:
        tf.summary.trace_on(graph=True, profiler=True)
    z = train_step(x, y)
    if epoch == 0:
        with writer.as_default():
            tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)
</code>```

I personally like more this decorator idea:

```<code>def run_once(f):
    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper

@run_once
def _start_graph_tensorflow(self):
    tf.summary.trace_on(graph=True, profiler=True)  # https://www.tensorflow.org/tensorboard/graphs

@run_once
def _end_graph_tensorflow(self):
    with self.graph_writer.as_default():
        tf.summary.trace_export(name="graph", step=0, profiler_outdir=self.graph_writer_logdir)

for epoch in range(epochs):
    _start_graph_tensorflow()
    z = train_step(x, y)
    _end_graph_tensorflow()
</code>```

Body:
I wanted to show my network graph on tensorboard using tensorflow 2. I followed this tutorial and I did a code that was something like this:

for epoch in range(epochs):
    # Bracket the function call with
    # tf.summary.trace_on() and tf.summary.trace_export().
    tf.summary.trace_on(graph=True, profiler=True)
    # Call only one tf.function when tracing.
    z = train_step(x, y)
    with writer.as_default():
        tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)

When doing that, I got the message Profiler session started. several times. When I open tensorboard, of course, the Graph said an error occurred and couldn't show anything.

Body:
I found the response here.

Actually, you can enable graph export in v2. You'll need to call
  tf.summary.trace_on() before the code you want to trace the graph for
  (e.g. L224 if you just want the train step), and then call
  tf.summary.trace_off() after the code completes. Since you only need
  one trace of the graph, I would recommend wrapping these calls with if
  global_step_val == 0: so that you don't produce traces every step.

Actually, to create the graph it is necessary to do the trace just once and makes no sense of doing it at each epoch. The solution is just to check before calling the trace just once like:

for epoch in range(epochs):
    if epoch == 0:
        tf.summary.trace_on(graph=True, profiler=True)
    z = train_step(x, y)
    if epoch == 0:
        with writer.as_default():
            tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)

I personally like more this decorator idea:

def run_once(f):
    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper

@run_once
def _start_graph_tensorflow(self):
    tf.summary.trace_on(graph=True, profiler=True)  # https://www.tensorflow.org/tensorboard/graphs

@run_once
def _end_graph_tensorflow(self):
    with self.graph_writer.as_default():
        tf.summary.trace_export(name="graph", step=0, profiler_outdir=self.graph_writer_logdir)

for epoch in range(epochs):
    _start_graph_tensorflow()
    z = train_step(x, y)
    _end_graph_tensorflow()


问:
Calling firebase functions returns null
I am calling the Functions function to get user information, but it returns null.
Please tell me the solution.

workspace/functions/src/index.ts

```<code>exports.getUser = functions.https.onCall((data, context) => {
  admin.database().ref(`user/${data.userId}`)
    .on('value', (snapshot) => {
      if (snapshot) return snapshot.val();
    });
});
</code>```

workspace/src/app/sample.component.ts

```<code>firebase.functions().httpsCallable('getUser')({
  userId: profile.userId
}).then(data => {
  console.log(data);
}).catch(error => {
  alert(error);
});
</code>```

答:
You're not returning anything in your https callable, add a return:</p>

```<code>exports.getUser = functions.https.onCall((data, context) => {
  return admin.database().ref(`user/${data.userId}`)
    .on('value', (snapshot) => {
      if (snapshot) return snapshot.val();
    });
});
</code>```

Title: Calling firebase functions returns null

Body:
I am calling the Functions function to get user information, but it returns null.
Please tell me the solution.

workspace/functions/src/index.ts

exports.getUser = functions.https.onCall((data, context) => {
  admin.database().ref(`user/${data.userId}`)
    .on('value', (snapshot) => {
      if (snapshot) return snapshot.val();
    });
});

workspace/src/app/sample.component.ts

firebase.functions().httpsCallable('getUser')({
  userId: profile.userId
}).then(data => {
  console.log(data);
}).catch(error => {
  alert(error);
});

Body:
You're not returning anything in your https callable, add a return:

exports.getUser = functions.https.onCall((data, context) => {
  return admin.database().ref(`user/${data.userId}`)
    .on('value', (snapshot) => {
      if (snapshot) return snapshot.val();
    });
});


问:
How to find the average of double values in an array list using a do loop?
I am creating a method called getAveragePrice and I need it to calculate the average of values in an undefined array list (which would only be defined during the testing/implementation of said method).

```<code>    public double getAveragePrice() {
    double sum = 0;
    int x = 0; //counting variable
    do {
</code>```

That is what I have right now for a start. I know that every time a value is added to the sum the count of x needs to increase by 1 so the method knows what to divide the final sum by. The only issue I have is how to set up a do loop to give me the sum of the values in an array list.

答:
It's 21st century. No need to use any loop. Use Scala & just write </p>

```<code>def exercise5(a: Array[Double]): Double = {
    a.sum / a.length
}
</code>```

Body:
I am creating a method called getAveragePrice and I need it to calculate the average of values in an undefined array list (which would only be defined during the testing/implementation of said method).

    public double getAveragePrice() {
    double sum = 0;
    int x = 0; //counting variable
    do {

That is what I have right now for a start. I know that every time a value is added to the sum the count of x needs to increase by 1 so the method knows what to divide the final sum by. The only issue I have is how to set up a do loop to give me the sum of the values in an array list.

Body:
It's 21st century. No need to use any loop. Use Scala & just write

def exercise5(a: Array[Double]): Double = {
    a.sum / a.length
}


问:
Rails 3.1 pre Migration problem
Now i am upgrade the rails 3.0.7 to rails 3.1 pre version. When i am creating a sample project it works fine. After creating a scaffold i am try to migrate, but it gives me the rake aborted! message.

Here my code

```<code>rails g scaffold product name:string price:decimal category:string
      invoke  active_record
      create    db/migrate/20110517090853_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/unit/product_test.rb
      create      test/fixtures/products.yml
       route  resources :products
      invoke  scaffold_controller
      create    app/controllers/products_controller.rb
      invoke    erb
      create      app/views/products
      create      app/views/products/index.html.erb
      create      app/views/products/edit.html.erb
      create      app/views/products/show.html.erb
      create      app/views/products/new.html.erb
      create      app/views/products/_form.html.erb
      invoke    test_unit
      create      test/functional/products_controller_test.rb
      invoke    helper
      create      app/helpers/products_helper.rb
      invoke      test_unit
      create        test/unit/helpers/products_helper_test.rb
      create  app/assets/stylesheets/scaffold.css.scss
      invoke  assets
      create    app/assets/javascripts/products.js.coffee
      create    app/assets/stylesheets/products.css.scss
rake db:migrate
==  CreateProducts: migrating =================================================
-- create_table(:products)
   -> 0.0053s
==  CreateProducts: migrated (0.0054s) ========================================

rake aborted!
An error has occurred, all later migrations canceled:

undefined method `rows' for nil:NilClass

(See full trace by running task with --trace)
</code>```

I am using ruby 1.9.2 and xampp.

Can any one know what is the problem?

答:
I had the same problem using mysql2 v0.2.6 as database adapter.

I've tried to solve  it updating mysql2 to latest version 0.3.2, but I could not compile this gem on Windows.
But I still believe that recent version of mysql2 might work.
Currently I use "pg" gem as postgres adapter for DB and it works fine with Rails 3.1.pre

Title: Rails 3.1 pre Migration problem

Body:
Now i am upgrade the rails 3.0.7 to rails 3.1 pre version. When i am creating a sample project it works fine. After creating a scaffold i am try to migrate, but it gives me the rake aborted! message.

Here my code

rails g scaffold product name:string price:decimal category:string
      invoke  active_record
      create    db/migrate/20110517090853_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/unit/product_test.rb
      create      test/fixtures/products.yml
       route  resources :products
      invoke  scaffold_controller
      create    app/controllers/products_controller.rb
      invoke    erb
      create      app/views/products
      create      app/views/products/index.html.erb
      create      app/views/products/edit.html.erb
      create      app/views/products/show.html.erb
      create      app/views/products/new.html.erb
      create      app/views/products/_form.html.erb
      invoke    test_unit
      create      test/functional/products_controller_test.rb
      invoke    helper
      create      app/helpers/products_helper.rb
      invoke      test_unit
      create        test/unit/helpers/products_helper_test.rb
      create  app/assets/stylesheets/scaffold.css.scss
      invoke  assets
      create    app/assets/javascripts/products.js.coffee
      create    app/assets/stylesheets/products.css.scss
rake db:migrate
==  CreateProducts: migrating =================================================
-- create_table(:products)
   -> 0.0053s
==  CreateProducts: migrated (0.0054s) ========================================

rake aborted!
An error has occurred, all later migrations canceled:

undefined method `rows' for nil:NilClass

(See full trace by running task with --trace)

I am using ruby 1.9.2 and xampp.

Can any one know what is the problem?