问:
draw a straight line between 2 coordinates in d3
I have drawn x axis an y axis in d3.

```<code>var margin = {top: 20, right: 100, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var xScale = d3.scale.linear()
    .domain([0, 15])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, 38])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);
</code>```

I then want to draw a line between 2 points in this grid.

```<code>  svg.append('line')
      .style('stroke', 'black')
      .attr('x1', 5)
      .attr('y1', 5)
      .attr('x2', 20)
      .attr('y2', 20);
</code>```

Here is a jsbin of the results.

So the line is not drawn between the grid coordinates (5, 5) and (20, 20).

How can I place the line on the coordinates of the grid that I have created?

答:
I solved it this way:</p>
```<code>svg.append('line')
  .style('stroke', 'black')
  .attr('x1', function (d) { return x(5))
  .attr('y1', function (d) { return y(5))
  .attr('x2', function (d) { return x(20))
  .attr('y2', function (d) { return y(20));
</code>```

Body:
I have drawn x axis an y axis in d3.

var margin = {top: 20, right: 100, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var xScale = d3.scale.linear()
    .domain([0, 15])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, 38])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

I then want to draw a line between 2 points in this grid.

  svg.append('line')
      .style('stroke', 'black')
      .attr('x1', 5)
      .attr('y1', 5)
      .attr('x2', 20)
      .attr('y2', 20);

Here is a jsbin of the results.

So the line is not drawn between the grid coordinates (5, 5) and (20, 20).

How can I place the line on the coordinates of the grid that I have created?

Body:
I solved it this way:

svg.append('line')
  .style('stroke', 'black')
  .attr('x1', function (d) { return x(5))
  .attr('y1', function (d) { return y(5))
  .attr('x2', function (d) { return x(20))
  .attr('y2', function (d) { return y(20));


来源: stackexchange

问:
Changing a column type from a Pandas dataframe to datetime changes the values on the other columns
I am loading data from .csv files to Pandas dataframes. The data is from meteorological stations and has a "date and time" column. The problem arises when converting that column from string to datetime type, for some reason the data from other columns also changes to zeros or other values that I do not understand.

```<code># first load the data
dique_aforador = pd.read_csv(obs_path+'Altura_diqueAforador_Estacion-4216.csv', sep=';', low_memory=False, skip_blank_lines=True, header=1).dropna(how='all')

# Look at the data
dique_aforador

    Fecha y Hora    Altura [m]
0   19/12/2019 13:00    0.00
1   19/12/2019 14:00    0.00
2   19/12/2019 15:00    0.00
3   19/12/2019 16:00    0.00
4   19/12/2019 17:00    0.00
... ... ...
14778   08/02/2022 15:00    1.34
14779   08/02/2022 16:00    1.34
14780   08/02/2022 17:00    1.33
14781   08/02/2022 18:00    1.33
14782   08/02/2022 19:00    1.33

# Plot the data as is
dique_aforador.plot(x='Fecha y Hora', rot=45)

</code>```

```<code># But when I change the 'Fecha y Hora' column to datetime
dique_aforador['Fecha y Hora'] = pd.to_datetime(dique_aforador['Fecha y Hora'])

# This happens:
dique_aforador.plot(x='Fecha y Hora', rot=45)

</code>```

Looks like several entries of the Altura [m] column are replaced by zero or other random values and I do not understand what is happening. I have also tried other equivalent ways of doing the conversion to datetime and I get the same issue with all of them (using the .astype('datetime64[ns]') method, adding parse_dates=['Fecha y Hora'] when loading the data, etc.). This also happens when using meteorological station data from other sources, so I think it is not dataset-dependent and has to do with something related to the datetime conversion. Any tips on how to solve this?

答:
Have you tried adding the infer_date_format option to pandas.to_datetime?

Something like this:

dique_aforador['Fecha y Hora'] = pd.to_datetime(dique_aforador['Fecha y Hora'], infer_datetime_format=True)

Pandas can take the first value in your date field and infer the remaining from it

ContentLicense: CC BY-SA 4.0

Body:
I am loading data from .csv files to Pandas dataframes. The data is from meteorological stations and has a "date and time" column. The problem arises when converting that column from string to datetime type, for some reason the data from other columns also changes to zeros or other values that I do not understand.

# first load the data
dique_aforador = pd.read_csv(obs_path+'Altura_diqueAforador_Estacion-4216.csv', sep=';', low_memory=False, skip_blank_lines=True, header=1).dropna(how='all')

# Look at the data
dique_aforador

    Fecha y Hora    Altura [m]
0   19/12/2019 13:00    0.00
1   19/12/2019 14:00    0.00
2   19/12/2019 15:00    0.00
3   19/12/2019 16:00    0.00
4   19/12/2019 17:00    0.00
... ... ...
14778   08/02/2022 15:00    1.34
14779   08/02/2022 16:00    1.34
14780   08/02/2022 17:00    1.33
14781   08/02/2022 18:00    1.33
14782   08/02/2022 19:00    1.33

# Plot the data as is
dique_aforador.plot(x='Fecha y Hora', rot=45)

# But when I change the 'Fecha y Hora' column to datetime
dique_aforador['Fecha y Hora'] = pd.to_datetime(dique_aforador['Fecha y Hora'])

# This happens:
dique_aforador.plot(x='Fecha y Hora', rot=45)

Looks like several entries of the Altura [m] column are replaced by zero or other random values and I do not understand what is happening. I have also tried other equivalent ways of doing the conversion to datetime and I get the same issue with all of them (using the .astype('datetime64[ns]') method, adding parse_dates=['Fecha y Hora'] when loading the data, etc.). This also happens when using meteorological station data from other sources, so I think it is not dataset-dependent and has to do with something related to the datetime conversion. Any tips on how to solve this?


问:
Is there any option to hide/ remove .hive files?
When I used hive as local db in flutter, .hive files are generated in user's app-directory. Is there any way to hide or remove these files from the app-directory?</p>

答:
You can remove file which contains the box and closes the box by using this method.
deleteFromDisk</p>


问:
Integer expression expected
I want to read my files line by line every 5 seconds. This time I just tried one-line bash command to do this.
And bash command is:

```<code>let X=1;while [ $X -lt 20 ];do cat XXX.file |head -$X|tail -1;X=$X+1;sleep 5;done
</code>```

However I got the error like:

```<code>-bash: [: 1+1: integer expression expected
</code>```

What's the problem?
btw, why can't we do $X < 20? (Instead we have to do -lt, less than?)

thx

答:
Your assignment X=$X+1 doesn't perform arithmetic. If $X is 1, it sets it to the string "1+1".  Change X=$X+1 to let X=X+1 or let X++.

As for the use of -lt rather than <, that's just part of the syntax of [ (i.e., the test command).  It uses = and != for string equality and inequality -eq, -ne, -lt, -le, -gt, and -ge for numbers.  As @Malvolio points out, the use of < would be inconvenient, since it's the input redirection operator.

(The test / [ command that's built into the bash shell does accept < and >, but not <= or >=, for strings. But the < or > character has to be quoted to avoid interpretation as an I/O redirection operator.)

Or consider using the equivalent (( expr )) construct rather than the let command. For example, let X++ can be written as ((X++)). At least bash, ksh, and zsh support this, though sh likely doesn't. I haven't checked the respective documentation, but I presume the shells' developers would want to make them compatible.

ContentLicense: CC BY-SA 3.0

Title: Integer expression expected

Body:
I want to read my files line by line every 5 seconds. This time I just tried one-line bash command to do this.
And bash command is:

let X=1;while [ $X -lt 20 ];do cat XXX.file |head -$X|tail -1;X=$X+1;sleep 5;done

However I got the error like:

-bash: [: 1+1: integer expression expected

What's the problem?
btw, why can't we do $X < 20? (Instead we have to do -lt, less than?)

thx


问:
Databricks Apache Spark AttributeError: 'dict' object has no attribute 'write'
The following function results in outputting JSON results.

```<code>def myfunc():
  with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
      # max_wait_time specifies how long the receiver should wait with no incoming messages before stopping receipt.
      # Default is None; to receive forever.

        with client.get_queue_receiver(QUEUE_NAME, session_id=session_id, max_wait_time=5) as receiver:
          for msg in receiver:
              # print("Received: " + str(msg))
              themsg = json.loads(str(msg))
              # complete the message so that the message is removed from the queue
              receiver.complete_message(msg)
              return themsg

result = myfunc()
</code>```

The following is snippet of the JSON output.

```<code>Out[65]: {'name': 'dmMapping_DIM_WORK_ORDER',
 'description': 'DIM_WORK_ORDER Azure Foundation to Azure Data Mart Mapping',
 'version': '2.4',
 'updateDttm': '01/02/2022 14:46PM',
 'SCDType': 4,
 'mappings': [{'ELLIPSE': {'method': 'ellipseItem',
    'tables': [{'database': 'foundation',
      'schema': 'AZ_FH_ELLIPSE',
      'table': 'ADS_FND_MSF620',
      'primaryKey': [{'column': 'WORK_ORDER'}]}],
    'columns': [{'column': 'D_WORK_ORDER_KEY',
      'type': 'int',
      'allowNulls': 'No',
      'mapType': 'autoGenerate'},
     {'column': 'SYSTEM_OF_RECORD',
      'type': 'varchar',
      'length': 24,
      'allowNulls': 'No',
      'mapType': 'staticValue',
      'value': 'ELLIPSE'},
     {'column': 'ACTUAL_FINISH_DATE',
</code>```

When I attempt to save the output with following

```<code>result.write.save().json('/mnt/lake/RAW/FormulaClassification/F1Area/')
</code>```

I get the error:

```<code>AttributeError: 'dict' object has no attribute 'write'
</code>```

Can someone let me know how overcome this error?

答:
The simplest way is just write data as JSON, without using Spark:

with open("/dbfs/mnt/lake/RAW/FormulaClassification/F1Area/<file-name>", "w") as file:
  file.write(json.dumps(result))
```
<p>You can still use Spark API, but for one message it would be the overkill:</p>
<pre class="lang-py prettyprint-override"><code>rdd = sc.parallelize([json.dumps(result)])
spark.read.json(rdd) \
  .write.mode("append").json('/mnt/lake/RAW/FormulaClassification/F1Area/')
</code>```

Body:
The following function results in outputting JSON results.

def myfunc():
  with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
      # max_wait_time specifies how long the receiver should wait with no incoming messages before stopping receipt.
      # Default is None; to receive forever.

        with client.get_queue_receiver(QUEUE_NAME, session_id=session_id, max_wait_time=5) as receiver:
          for msg in receiver:
              # print("Received: " + str(msg))
              themsg = json.loads(str(msg))
              # complete the message so that the message is removed from the queue
              receiver.complete_message(msg)
              return themsg

result = myfunc()

The following is snippet of the JSON output.

Out[65]: {'name': 'dmMapping_DIM_WORK_ORDER',
 'description': 'DIM_WORK_ORDER Azure Foundation to Azure Data Mart Mapping',
 'version': '2.4',
 'updateDttm': '01/02/2022 14:46PM',
 'SCDType': 4,
 'mappings': [{'ELLIPSE': {'method': 'ellipseItem',
    'tables': [{'database': 'foundation',
      'schema': 'AZ_FH_ELLIPSE',
      'table': 'ADS_FND_MSF620',
      'primaryKey': [{'column': 'WORK_ORDER'}]}],
    'columns': [{'column': 'D_WORK_ORDER_KEY',
      'type': 'int',
      'allowNulls': 'No',
      'mapType': 'autoGenerate'},
     {'column': 'SYSTEM_OF_RECORD',
      'type': 'varchar',
      'length': 24,
      'allowNulls': 'No',
      'mapType': 'staticValue',
      'value': 'ELLIPSE'},
     {'column': 'ACTUAL_FINISH_DATE',

When I attempt to save the output with following

result.write.save().json('/mnt/lake/RAW/FormulaClassification/F1Area/')

I get the error:

AttributeError: 'dict' object has no attribute 'write'

Can someone let me know how overcome this error?

Body:
The simplest way is just write data as JSON, without using Spark:

with open("/dbfs/mnt/lake/RAW/FormulaClassification/F1Area/<file-name>", "w") as file:
  file.write(json.dumps(result))

You can still use Spark API, but for one message it would be the overkill:

rdd = sc.parallelize([json.dumps(result)])
spark.read.json(rdd) \
  .write.mode("append").json('/mnt/lake/RAW/FormulaClassification/F1Area/')


问:
PYTHON/PRINT wrong output
I've made a code where python reads from a file and then proceeds to print a specific line:

```<code>with open('crypto.txt') as f:
    lines = f.readlines(1)
crypto = str(lines)
print(crypto)
</code>```

But the output is for example:
['bitcoin\n'] how do i remove ['\n'] to only get bitcoin as an output ?

I know that with f.read() there is no brackets and \n but I can't choose a specific line to read - or can I?

here is the txt file:

```<code>bitcoin
ethereum
cardano
sandbox
</code>```

答:
Foud the answer!

```<code>f = open('crypto.txt')
lines = f.readlines()
line = lines[0]
print(line)
</code>```

output ex:  bitcoin

Title: PYTHON/PRINT wrong output

Body:
I've made a code where python reads from a file and then proceeds to print a specific line:

with open('crypto.txt') as f:
    lines = f.readlines(1)
crypto = str(lines)
print(crypto)

But the output is for example:
['bitcoin\n'] how do i remove ['\n'] to only get bitcoin as an output ?

I know that with f.read() there is no brackets and \n but I can't choose a specific line to read - or can I?

here is the txt file:

bitcoin
ethereum
cardano
sandbox

Body:
Foud the answer!

f = open('crypto.txt')
lines = f.readlines()
line = lines[0]
print(line)

output ex:  bitcoin


问:
Reading a .dat file in Python with potentially empty columns
I am trying to read a .DAT file in Python. This .DAT file is part of a group of files, which can be loaded into Google Maps (so it has a .ID, .MAP, .IND, and a .TAB file associated with it).

Opening it in Notepad, my file looks like: Dat File, Additionally, I have uploaded the dat file from this link: https://filedropper.com/d/s/T0kpe8vHYcsP0swu2CZB30K7UZpB99

I am trying to parse this file into a readable Pandas dataframe. After analyzing the file, it seems that there are 4 columns (RecAreaNam, RecAreaCat, Province, and Comments-typically blank). For example, if you look at the second line:

Whistler           World Class               BC             Tofino Ucluelet...

There is a lot of spaces in between these columns, but after "BC" (the province column), Tofino Ucluelet would be part of a new row, not in comments.

I don't have much experience with reading DAT files in python, so what I tried is to research similar questions asked on StackOverFlow.

What I attempted:

Attempted to read it into Pandas:

```<code>s=pd.read_csv('CanHwyBuffer.DAT', header=None, lineterminator='\n')
</code>```

Error: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 2, saw 11021

datContent = [i.strip().split() for i in open('CanHwyBuffer.DAT', encoding='latin1').readlines()]

Can anyone suggest something that could remove the extra space, and make a dataframe out of this file?

答:
This file seems to be in dBase III DBF format:

$ file /tmp/RecAreaPolygons.DAT
/tmp/RecAreaPolygons.DAT: FoxBase+/dBase III DBF, 165 records * 232, update-date 118-4-25, at offset 161 1st record "Whistler"
```
<p>You should use a proper parser instead of trying to read it yourself. Using this answer you could use the Python <code>dbf</code> module. The data seems to have a strange encoding and contains a lot of null bytes which have to be cleaned up:</p>
<pre class="lang-py prettyprint-override"><code>import dbf
table = dbf.Table('/tmp/RecAreaPolygons.DAT')
table.open()

data = []
for record in table:
    try:
        data.append([record[fieldname].rstrip('\x00') for fieldname in table.field_names])
    except Exception as e:
        print('unable to decode record', e)
</code>```

This will yield 164 records (skipping one due to a UnicodeDecodeError). You can then convert this into a DataFrame:

import pandas as pd

df = pd.DataFrame(data, columns=('RecAreaNam', 'RecAreaCat', 'Province', 'Comments'))
df.head()
```
<p>gives</p>
```        RecAreaNam   RecAreaCat Province Comments
0         Whistler  World Class       BC
1  Tofino Ucluelet  World Class       BC
2            Banff  World Class       AB
3          Canmore  World Class       AB
4      Lake Louise  World Class       AB
```

Body:
I am trying to read a .DAT file in Python. This .DAT file is part of a group of files, which can be loaded into Google Maps (so it has a .ID, .MAP, .IND, and a .TAB file associated with it).

Opening it in Notepad, my file looks like: Dat File, Additionally, I have uploaded the dat file from this link: https://filedropper.com/d/s/T0kpe8vHYcsP0swu2CZB30K7UZpB99

I am trying to parse this file into a readable Pandas dataframe. After analyzing the file, it seems that there are 4 columns (RecAreaNam, RecAreaCat, Province, and Comments-typically blank). For example, if you look at the second line:

Whistler           World Class               BC             Tofino Ucluelet...

There is a lot of spaces in between these columns, but after "BC" (the province column), Tofino Ucluelet would be part of a new row, not in comments.

I don't have much experience with reading DAT files in python, so what I tried is to research similar questions asked on StackOverFlow.

What I attempted:

Attempted to read it into Pandas:

s=pd.read_csv('CanHwyBuffer.DAT', header=None, lineterminator='\n')

Error: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 2, saw 11021

datContent = [i.strip().split() for i in open('CanHwyBuffer.DAT', encoding='latin1').readlines()]

Can anyone suggest something that could remove the extra space, and make a dataframe out of this file?

Body:
This file seems to be in dBase III DBF format:

$ file /tmp/RecAreaPolygons.DAT
/tmp/RecAreaPolygons.DAT: FoxBase+/dBase III DBF, 165 records * 232, update-date 118-4-25, at offset 161 1st record "Whistler"

You should use a proper parser instead of trying to read it yourself. Using this answer you could use the Python dbf module. The data seems to have a strange encoding and contains a lot of null bytes which have to be cleaned up:

import dbf
table = dbf.Table('/tmp/RecAreaPolygons.DAT')
table.open()

data = []
for record in table:
    try:
        data.append([record[fieldname].rstrip('\x00') for fieldname in table.field_names])
    except Exception as e:
        print('unable to decode record', e)

This will yield 164 records (skipping one due to a UnicodeDecodeError). You can then convert this into a DataFrame:

import pandas as pd

df = pd.DataFrame(data, columns=('RecAreaNam', 'RecAreaCat', 'Province', 'Comments'))
df.head()

gives

        RecAreaNam   RecAreaCat Province Comments
0         Whistler  World Class       BC
1  Tofino Ucluelet  World Class       BC
2            Banff  World Class       AB
3          Canmore  World Class       AB
4      Lake Louise  World Class       AB


问:
Kafka and mult-iline (two by two lines) csv file: can Kafka handle it to gather each couple of lines in a single message?
I want to analyze my bathroom scale measurements, exportable in csv.
But they cannot be exploited immediately.

```<code>Durée,Poids,Variation,IMC,Masse grasse,Masse musculaire squelettique,Masse osseuse,Masse hydrique,
" 14 Fév. 2022",
06:37,72.1 kg,0.3 kg,22.8,26.3 %,29.7 kg,3.5 kg,53.8 %,
" 13 Fév. 2022",
06:48,72.4 kg,0.2 kg,22.9,25.4 %,29.8 kg,3.6 kg,54.4 %,
</code>```

its records ends with a comma,

the date is on the first line, while other data for that day is on the second line,

they are units or percentile signs inside the cells.

Cleanings are needed, and I would like to use Kafka for that.

I never used Kafka before: it will read a csv file, yes, but can it handle the case where that csv is a multi-line one?

A way that it can offer me core messages with this content, for beginning:

```<code>" 14 Fév. 2022","06:37","72.1 kg","0.3 kg","22.8","26.3 %","29.7 kg","3.5 kg","53.8 %"
" 13 Fév. 2022","06:48","72.4 kg","0.2 kg","22.9","25.4 %","29.8 kg","3.6 kg","54.4 %"
</code>```

with fields of String type named :
"Durée", "Poids", "Variation", "IMC", "Masse grasse", "Masse musculaire squelettique", "Masse osseuse", "Masse hydrique".

This crude shape would allow me to start a more precise treatment.

What do you suggest me to do through Kafka?

If this maneuver looks too tricky, I can read that csv file by a small Java program, treat roughly its worse problems, and send the corrected content to Kafka then.

But I would enjoy more handling the whole csv content entirely by Kafka.

答:
Kafka doesn't care about data formats. You'll need to parse the file on your own (in any language, not necessarily Java), outside of Kafka, then build a serializable record that can be produced.

You'd have similar issues with a simple database, and I'm not sure I see the need for Kafka here

Body:
I want to analyze my bathroom scale measurements, exportable in csv.
But they cannot be exploited immediately.

Durée,Poids,Variation,IMC,Masse grasse,Masse musculaire squelettique,Masse osseuse,Masse hydrique,
" 14 Fév. 2022",
06:37,72.1 kg,0.3 kg,22.8,26.3 %,29.7 kg,3.5 kg,53.8 %,
" 13 Fév. 2022",
06:48,72.4 kg,0.2 kg,22.9,25.4 %,29.8 kg,3.6 kg,54.4 %,

its records ends with a comma,

the date is on the first line, while other data for that day is on the second line,

they are units or percentile signs inside the cells.

Cleanings are needed, and I would like to use Kafka for that.

I never used Kafka before: it will read a csv file, yes, but can it handle the case where that csv is a multi-line one?

A way that it can offer me core messages with this content, for beginning:

" 14 Fév. 2022","06:37","72.1 kg","0.3 kg","22.8","26.3 %","29.7 kg","3.5 kg","53.8 %"
" 13 Fév. 2022","06:48","72.4 kg","0.2 kg","22.9","25.4 %","29.8 kg","3.6 kg","54.4 %"

with fields of String type named :
"Durée", "Poids", "Variation", "IMC", "Masse grasse", "Masse musculaire squelettique", "Masse osseuse", "Masse hydrique".

This crude shape would allow me to start a more precise treatment.

What do you suggest me to do through Kafka?

If this maneuver looks too tricky, I can read that csv file by a small Java program, treat roughly its worse problems, and send the corrected content to Kafka then.

But I would enjoy more handling the whole csv content entirely by Kafka.


Title: About the adress arithmetic in C

Body:
It's from a elementary question from the very beginning of MIT6.s081, Why does the fifth
printf's result is:

5: a[0] = 200, a[1] = 128144, a[2] = 256, a[3] = 302

I really can't imagine how 128144 comes!

Here is the code:

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

void f(void)
{
    int a[4];
    int *b = malloc(16);
    int *c;
    int i;

    printf("1: a = %p, b = %p, c = %p\n", a, b, c);

    c = a;
    for (i = 0; i < 4; i++)
        a[i] = 100 + i;
    c[0] = 200;
    printf("2: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c[1] = 300;
    *(c + 2) = 301;
    c[3] = 302;
    printf("3: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c = c + 1;
    *c = 400;
    printf("4: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c = (int *)((char *)c + 1);
    *c = 500;
    printf("5: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    b = (int *)a + 1;
    c = (int *)((char *)a + 1);
    printf("6: a = %p, b = %p, c = %p\n", a, b, c);
}

int main(int ac, char **av)
{
    f();
    return 0;
}

Body:
After 4: a[0] = 200, a[1] = 400, a[2] = 301, a[3] = 302

The binary value of the array pointed by a and c is as following:

            a
            c
C8 00 00 00 | 90 01 00 00 | 2D 01 00 00 | 2E 01 00 00

After    c = (int *) ((char *) c + 1);

            a
            |    c
            |    |
C8 00 00 00 | 90 01 00 00 | 2D 01 00 00 | 2E 01 00 00

After     *c = 500; // 500 = 0x000001F4

            a
            |    c
            |    |
C8 00 00 00 | 90 F4 01 00 | 00 01 00 00 | 2E 01 00 00

So a[1] = 0x0001F490; a[2] = 0x00000100;
And 0x0001F490 = 128144, 0x00000100 = 256.


问:
Why does POST request to controller not work?
There is a POST request on login page which, for some reason, doesn't work. Code for the request is

```<code>$(document).ready(function () {
    $.post(path, {param: "val"});
});
</code>```

The method for getting this POST and working around it is the following:

```<code>[HttpPost]
public ActionResult Func(string val)
{
    ... //some stuff happening
    return new EmptyResult();
}
</code>```

Basically a standard method. Thing is, the method isn't called (most of the times) when I'm sending this POST from login page. However, when I log in and try to send it, the method works as intended. So is there any connection between sending POST request and being authorised?

Edit: as I got another question (kinda related to this one), should I post it here or create a new question?

答:
when I log in and try to send it, the method works as intended.

Sounds like you have an Authorize filter on your method or controller.

Authorization filters can be applied to actionresults or controllers to only allow logged-in users to access those endpoints.

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0#authorization-filters

Body:
There is a POST request on login page which, for some reason, doesn't work. Code for the request is

$(document).ready(function () {
    $.post(path, {param: "val"});
});

The method for getting this POST and working around it is the following:

[HttpPost]
public ActionResult Func(string val)
{
    ... //some stuff happening
    return new EmptyResult();
}

Basically a standard method. Thing is, the method isn't called (most of the times) when I'm sending this POST from login page. However, when I log in and try to send it, the method works as intended. So is there any connection between sending POST request and being authorised?

Edit: as I got another question (kinda related to this one), should I post it here or create a new question?


问:
How I create Octagon shape in google map?
I would like to draw a Octagonal shape.

I don't know how to achieve this. Here is my code -

func drawOctagonalShape(){

```<code>    let camera = GMSCameraPosition.camera(withLatitude: 37.4, longitude:-122.0, zoom: 10)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    mapView.settings.myLocationButton = true;
    self.view = mapView

    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0)
    marker.title = "India"
    //marker.snippet = "Malaysia"
    marker.map = mapView
    let rect = GMSMutablePath()
    rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
    rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
    rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
    rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))

    // Create the polygon, and assign it to the map.
    let polygon = GMSPolygon(path: rect)
    polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.05);
    polygon.strokeColor = UIColor.init(hue: 210, saturation: 88, brightness: 84, alpha: 1)
    //polygon.strokeColor = .black
    polygon.strokeWidth = 2
    polygon.map = mapView
}
</code>```

答:
Octagon is basically 8 points distributed equally on a circle. You can create a method like the following:

```<code>func generateCircle(around center: CLLocationCoordinate2D, radius: Double, pointCount: Int = 8, rotation: Double = 0) -> [CLLocationCoordinate2D] {
    (0..<count).map { index in
        let angle = rotation + (Double(index)/Double(pointCount))*Double.pi*2.0
        return .init(latitude: center.latitude + cos(angle)*radius, longitude: center.longitude + sin(angle)*radius)
    }
}
</code>```

I hope the code speaks for itself. You would use it in your code like

```<code>let rect = GMSMutablePath()
generateCircle(around center: myCenter, radius: someSmallRadius, pointCount: 8, rotation: 0).forEach { coordinate in
    rect.add(coordinate)
}
</code>```

I would expect this to work in most cases. There are 2 potential problems however:

I am unsure how this would behave around edges of both longitude and latitude.

Radius expressed in degrees may be a bit incorrect at some points

Would it not be easier to simply generate an image and place that on your map?

Body:
I would like to draw a Octagonal shape.

I don't know how to achieve this. Here is my code -

func drawOctagonalShape(){

    let camera = GMSCameraPosition.camera(withLatitude: 37.4, longitude:-122.0, zoom: 10)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    mapView.settings.myLocationButton = true;
    self.view = mapView

    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0)
    marker.title = "India"
    //marker.snippet = "Malaysia"
    marker.map = mapView
    let rect = GMSMutablePath()
    rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
    rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
    rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
    rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))

    // Create the polygon, and assign it to the map.
    let polygon = GMSPolygon(path: rect)
    polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.05);
    polygon.strokeColor = UIColor.init(hue: 210, saturation: 88, brightness: 84, alpha: 1)
    //polygon.strokeColor = .black
    polygon.strokeWidth = 2
    polygon.map = mapView
}

Body:
Octagon is basically 8 points distributed equally on a circle. You can create a method like the following:

func generateCircle(around center: CLLocationCoordinate2D, radius: Double, pointCount: Int = 8, rotation: Double = 0) -> [CLLocationCoordinate2D] {
    (0..<count).map { index in
        let angle = rotation + (Double(index)/Double(pointCount))*Double.pi*2.0
        return .init(latitude: center.latitude + cos(angle)*radius, longitude: center.longitude + sin(angle)*radius)
    }
}

I hope the code speaks for itself. You would use it in your code like

let rect = GMSMutablePath()
generateCircle(around center: myCenter, radius: someSmallRadius, pointCount: 8, rotation: 0).forEach { coordinate in
    rect.add(coordinate)
}

I would expect this to work in most cases. There are 2 potential problems however:

I am unsure how this would behave around edges of both longitude and latitude.

Radius expressed in degrees may be a bit incorrect at some points

Would it not be easier to simply generate an image and place that on your map?


问:
Python: How to parse variables from several pandas dataframes?
I want to extract the x and y variables from several pandas dataframes (before proceeding to next steps). I initialize the tab-delimited .txt file, before I extract the information.
Error raised is ValueError: too many values to unpack (expected 2).

```<code>import pandas as pd

class DataProcessing:

    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")
        X, y = self.df.iloc[1:, 1:]
        return X, y

dp_linear_cna = DataProcessing("data_linear_cna.txt")
dp_mrna_seq_v2_rsem = DataProcessing("data_mrna_seq_v2_rsem.txt")

dp_linear_cna.extract_info()
dp_mrna_seq_v2_rsem.extract_info()
</code>```

Traceback:

ValueError: too many values to unpack (expected 2)

答:
You coding style is quite bad. First of all, don't return anything in init. It's a constructor. Make another function instead.

```<code>class DataProcessing:
    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")

    def split_data(self):
        X = self.df.iloc[:, :-1]
        y = self.df.iloc[:, -1]
        return X, y
</code>```

Calling your DataProcessing like this:

```<code>def main():
    dp = DataProcessing('data_linear_cna.txt')
    X, y = dp.split_data()
    print(X)
    print()
    print(y)
</code>```

Main point here is selection over position via df.iloc[rows, columns]

```<code>X, y = self.df.iloc[1:, 1:]
</code>```

this is not a valid statement. pandas.DataFrame.iloc return another pandas.DataFrame. Not a tuple. You can't do tuple unpacking.

Indexing both axes

You can mix the indexer types for the index and columns. Use : to select the entire axis.

Body:
I want to extract the x and y variables from several pandas dataframes (before proceeding to next steps). I initialize the tab-delimited .txt file, before I extract the information.
Error raised is ValueError: too many values to unpack (expected 2).

import pandas as pd

class DataProcessing:

    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")
        X, y = self.df.iloc[1:, 1:]
        return X, y

dp_linear_cna = DataProcessing("data_linear_cna.txt")
dp_mrna_seq_v2_rsem = DataProcessing("data_mrna_seq_v2_rsem.txt")

dp_linear_cna.extract_info()
dp_mrna_seq_v2_rsem.extract_info()

Traceback:

ValueError: too many values to unpack (expected 2)

Body:
You coding style is quite bad. First of all, don't return anything in init. It's a constructor. Make another function instead.

class DataProcessing:
    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")

    def split_data(self):
        X = self.df.iloc[:, :-1]
        y = self.df.iloc[:, -1]
        return X, y

Calling your DataProcessing like this:

def main():
    dp = DataProcessing('data_linear_cna.txt')
    X, y = dp.split_data()
    print(X)
    print()
    print(y)

Main point here is selection over position via df.iloc[rows, columns]

X, y = self.df.iloc[1:, 1:]

this is not a valid statement. pandas.DataFrame.iloc return another pandas.DataFrame. Not a tuple. You can't do tuple unpacking.

Indexing both axes

You can mix the indexer types for the index and columns. Use : to select the entire axis.


问:
Choosing the last element of a list
```<code>scala> last(List(1, 1, 2, 3, 5, 8))
res0: Int = 8
</code>```

for having a result above, I wrote this code:

```<code>val yum = args(0).toInt
val thrill:

def last(a: List[Int]): List[Int] = {
     println(last(List(args(0).toInt).last)
     }
</code>```

What is the problem with this code?

答:
In these types of questions the useful take and takeRight are often overlooked. Similar to last, one avoids the slow initial reversing of a list, but unlike last, can take the last (or first) n items as opposed to just a single one:

```<code>scala> val myList = List(1,2,3)
myList: List[Int] = List(1, 2, 3)

scala> myList.takeRight(2)
res0: List[Int] = List(2, 3)

scala> myList.takeRight(1)
res1: List[Int] = List(3)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Choosing the last element of a list

Body:
scala> last(List(1, 1, 2, 3, 5, 8))
res0: Int = 8

for having a result above, I wrote this code:

val yum = args(0).toInt
val thrill:

def last(a: List[Int]): List[Int] = {
     println(last(List(args(0).toInt).last)
     }

What is the problem with this code?

Body:
In these types of questions the useful take and takeRight are often overlooked. Similar to last, one avoids the slow initial reversing of a list, but unlike last, can take the last (or first) n items as opposed to just a single one:

scala> val myList = List(1,2,3)
myList: List[Int] = List(1, 2, 3)

scala> myList.takeRight(2)
res0: List[Int] = List(2, 3)

scala> myList.takeRight(1)
res1: List[Int] = List(3)


问:
How To Display C# Objects in A Grid in xamarin Forms
Im Looking for a way to display my C# Objects in a Grid. But even after serveral hours of searching I couldn't find a valid Way. How can I Achieve the following result?

答:
first in your c# code create an observable collection of your object type;

```<code>        private ObservableCollection<YourModel> objList;
        public ObservableCollection<YourModel> ObjList
        {
            get { return objList; }
            set
            {
               objList = value;
            }
        }
</code>```

add your data to the list:

```<code>ObjList = new ObservableCollection<YourModel>(){ new YourModel{ ...} , new YourModel{...} };

</code>```

In xaml create a grid inside n collectionview :

```<code><CollectionView ItemsSource="{Binding ObjList}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="10,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>

                <Label Grid.Column="0"
                       Text="{Binding Name}"
                       />
                <Label
                       Grid.Column="1"
                       Text="{Binding Att1}"
                      />

                      <Label
                       Grid.Column="2"
                       Text="{Binding Att2}"
                        />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
    ...
</CollectionView>
</code>```

Alternatively Check DataGrid in syncfusion :
check

Body:
first in your c# code create an observable collection of your object type;

        private ObservableCollection<YourModel> objList;
        public ObservableCollection<YourModel> ObjList
        {
            get { return objList; }
            set
            {
               objList = value;
            }
        }

add your data to the list:

ObjList = new ObservableCollection<YourModel>(){ new YourModel{ ...} , new YourModel{...} };

In xaml create a grid inside n collectionview :

<CollectionView ItemsSource="{Binding ObjList}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="10,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>

                <Label Grid.Column="0"
                       Text="{Binding Name}"
                       />
                <Label
                       Grid.Column="1"
                       Text="{Binding Att1}"
                      />

                      <Label
                       Grid.Column="2"
                       Text="{Binding Att2}"
                        />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
    ...
</CollectionView>

Alternatively Check DataGrid in syncfusion :
check


问:
Flutter: disable screenshot capture for app
I am making a Flutter app and I need to make sure the user is not able to capture screenshot of the app (any screen). Is there any way to achieve this in Flutter or do I need to write native code for both Android and IOS?</p>

答:
It's only in iOS,just modify in AppDelegate.
And no more plugins

```<code>import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    self.window.makeSecure() //Add this line
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

}
//And this extension
extension UIWindow {
func makeSecure() {
    let field = UITextField()
    field.isSecureTextEntry = true
    self.addSubview(field)
    field.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    field.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    self.layer.superlayer?.addSublayer(field.layer)
    field.layer.sublayers?.first?.addSublayer(self.layer)
  }
}
</code>```

See image here

Body:
It's only in iOS,just modify in AppDelegate.
And no more plugins

import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    self.window.makeSecure() //Add this line
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

}
//And this extension
extension UIWindow {
func makeSecure() {
    let field = UITextField()
    field.isSecureTextEntry = true
    self.addSubview(field)
    field.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    field.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    self.layer.superlayer?.addSublayer(field.layer)
    field.layer.sublayers?.first?.addSublayer(self.layer)
  }
}

See image here


问:
how to ingest non-one-minute data in zipline
when I try to ingest data into zipline bundles, since I could not get one-minute data, and only have 5-minutes klines data. Looks like standard zipline does not support it?
cited from http://www.zipline.io/bundles.html

ingest(environ,
       asset_db_writer,
       minute_bar_writer,
       daily_bar_writer,
       adjustment_writer,
       calendar,
       start_session,
       end_session,
       cache,
       show_progress,
       output_dir)

minute_bar_writer
minute_bar_writer is an instance of BcolzMinuteBarWriter. This writer is used to convert data to zipline’s internal bcolz format to later be read by a BcolzMinuteBarReader. If minute data is provided, users should call write() with an iterable of (sid, dataframe) tuples. The show_progress argument should also be forwarded to this method. If the data source does not provide minute level data, then there is no need to call the write method. It is also acceptable to pass an empty iterator to write() to signal that there is no minutely data.

Anyway, I use this interface to ingest the 5 minutes klines into zipline. but when I call run_algorithm, whatever the data_frequency I input, it prompt errors.

```<code>data = run_algorithm(start=start,
                     end=end,
                     initialize=initialize,
                     capital_base=100000,
                     handle_data=handle_data,
                     bundle="poloniex_csv",
                     data_frequency='60min',
                     trading_calendar=PoloniexExchangeCalendar())
</code>```

AssertionError: All readers must share target trading_calendar. Reader= for type= uses calendar= which does not match the desired shared calendar=

How to fix this issue? for instance let BcolzMinuteBarReader support 5minutes data. I am ok with deal the 5 minutes data in zipline handle_data functions.
Thank you!

答:
The answer to this is that one shouldn't use the calendar class directly, PoloniexExchangeCalendar() here, but they should invoke get_calendar(calendar_name) to get an instance of the calendar from the calendar  factory instead. In theory, this would guarantee that there is only one instance of the calendar used by the framework and therefore the line

```<code>assert trading_calendar == r.trading_calendar
</code>```

in the dispatch_bar_reader.py would always resolve to true. In my case and for some reason, even when using get_calendar(calendar_name) wasn't exactly sufficient and I was getting a comparison of two different instances of the same calendar class which inevitably resolved to False. Hence I was getting the same error. I went around the issue by having my calendar class implementing its own equality comparison by adding the following lines inside the custom calendar class

```<code>__hash__ = ExchangeCalendar.__hash__

def __eq__(self, other):
    return all(self.all_sessions == other.all_sessions) if isinstance(other, CoinbaseExchangeCalendar) else False
</code>```

This did the trick for me by bypassing the technicalities of comparing the two instances but admittedly without actually ever figuring out why get_calendar(cal_name) didn't return the singleton instance of the custom calendar class.

Body:
when I try to ingest data into zipline bundles, since I could not get one-minute data, and only have 5-minutes klines data. Looks like standard zipline does not support it?
cited from http://www.zipline.io/bundles.html

ingest(environ,
       asset_db_writer,
       minute_bar_writer,
       daily_bar_writer,
       adjustment_writer,
       calendar,
       start_session,
       end_session,
       cache,
       show_progress,
       output_dir)

minute_bar_writer
minute_bar_writer is an instance of BcolzMinuteBarWriter. This writer is used to convert data to zipline’s internal bcolz format to later be read by a BcolzMinuteBarReader. If minute data is provided, users should call write() with an iterable of (sid, dataframe) tuples. The show_progress argument should also be forwarded to this method. If the data source does not provide minute level data, then there is no need to call the write method. It is also acceptable to pass an empty iterator to write() to signal that there is no minutely data.

Anyway, I use this interface to ingest the 5 minutes klines into zipline. but when I call run_algorithm, whatever the data_frequency I input, it prompt errors.

data = run_algorithm(start=start,
                     end=end,
                     initialize=initialize,
                     capital_base=100000,
                     handle_data=handle_data,
                     bundle="poloniex_csv",
                     data_frequency='60min',
                     trading_calendar=PoloniexExchangeCalendar())

AssertionError: All readers must share target trading_calendar. Reader= for type= uses calendar= which does not match the desired shared calendar=

How to fix this issue? for instance let BcolzMinuteBarReader support 5minutes data. I am ok with deal the 5 minutes data in zipline handle_data functions.
Thank you!

Body:
The answer to this is that one shouldn't use the calendar class directly, PoloniexExchangeCalendar() here, but they should invoke get_calendar(calendar_name) to get an instance of the calendar from the calendar  factory instead. In theory, this would guarantee that there is only one instance of the calendar used by the framework and therefore the line

assert trading_calendar == r.trading_calendar

in the dispatch_bar_reader.py would always resolve to true. In my case and for some reason, even when using get_calendar(calendar_name) wasn't exactly sufficient and I was getting a comparison of two different instances of the same calendar class which inevitably resolved to False. Hence I was getting the same error. I went around the issue by having my calendar class implementing its own equality comparison by adding the following lines inside the custom calendar class

__hash__ = ExchangeCalendar.__hash__

def __eq__(self, other):
    return all(self.all_sessions == other.all_sessions) if isinstance(other, CoinbaseExchangeCalendar) else False

This did the trick for me by bypassing the technicalities of comparing the two instances but admittedly without actually ever figuring out why get_calendar(cal_name) didn't return the singleton instance of the custom calendar class.


问:
Got: TypeError: 'bool' object is not callable when building CNN using PyTorch
I got the following error when using PyTorch to build a convolutional neural network

TypeError: 'bool' object is not callable.

Attached is the related code:

```<code>class alpha(nn.Module):
    '''
    This is the alpha class
    '''

    def __init__(self, alpha_val=0, minus=False, train=True):
        super(alpha, self).__init__()
        if train:
            self.alpha = nn.Parameter(torch.Tensor([alpha_val]).to(device))
            # This sentence defines that alpha is a parameter that to be optimized
            self.alpha.requires_grad = True
        else:
            self.alpha = torch.Tensor([alpha_val]).to(device)
            self.alpha.requires_grad = False
        self.minus = minus

    def forward(self, x):
        out = torch.mul(self.alpha, x)
        if self.minus:
            out = torch.mul(out, -1)
        return out

class InterMedium_Layer(nn.Module):
    def __init__(self, train=False, alpha_threshold=0.9) -> object:
        super(InterMedium_Layer, self).__init__()
        self.alpha1 = alpha()
        self.train = train
        self.alpha_threshold = alpha_threshold

    def forward(self, x):
        if (not self.train) and self.alpha1.alpha.item() < self.alpha_threshold:
            return x
        else:
            out = self.alpha1(x)
            out += F.relu(out)
            out += self.alpha1(x, minus=True)
            return out

class BN_Conv2d_f(nn.Module):
    def __init__(self, in_channels: object, out_channels: object, kernel_size: object, stride: object, padding: object,
                 dilation=1, groups=1, bias=False, activation=True) -> object:
        super(BN_Conv2d_f, self).__init__()
        layers = [nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
                            padding=padding, dilation=dilation, groups=groups, bias=bias),
                  nn.BatchNorm2d(out_channels)]
        self.InterMedium_Layer = InterMedium_Layer()
        if activation:
            # Error: bool obj not callable
            layers.append(self.InterMedium_Layer)
        self.seq = nn.Sequential(*layers)
</code>```

I guess I called a bool var somewhere but I didn't find one.

Attached is the traceback and debug detail:

Debug page

Traceback Page

I find that the model becomes a bool type var, not a cnn network.
Is there anything wrong with my code?

答: "def init(self, alpha_val=0, minus=False, train=True)", define the 'train' paramater to an other word.

Body:
I got the following error when using PyTorch to build a convolutional neural network

TypeError: 'bool' object is not callable.

Attached is the related code:

class alpha(nn.Module):
    '''
    This is the alpha class
    '''

    def __init__(self, alpha_val=0, minus=False, train=True):
        super(alpha, self).__init__()
        if train:
            self.alpha = nn.Parameter(torch.Tensor([alpha_val]).to(device))
            # This sentence defines that alpha is a parameter that to be optimized
            self.alpha.requires_grad = True
        else:
            self.alpha = torch.Tensor([alpha_val]).to(device)
            self.alpha.requires_grad = False
        self.minus = minus

    def forward(self, x):
        out = torch.mul(self.alpha, x)
        if self.minus:
            out = torch.mul(out, -1)
        return out

class InterMedium_Layer(nn.Module):
    def __init__(self, train=False, alpha_threshold=0.9) -> object:
        super(InterMedium_Layer, self).__init__()
        self.alpha1 = alpha()
        self.train = train
        self.alpha_threshold = alpha_threshold

    def forward(self, x):
        if (not self.train) and self.alpha1.alpha.item() < self.alpha_threshold:
            return x
        else:
            out = self.alpha1(x)
            out += F.relu(out)
            out += self.alpha1(x, minus=True)
            return out

class BN_Conv2d_f(nn.Module):
    def __init__(self, in_channels: object, out_channels: object, kernel_size: object, stride: object, padding: object,
                 dilation=1, groups=1, bias=False, activation=True) -> object:
        super(BN_Conv2d_f, self).__init__()
        layers = [nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
                            padding=padding, dilation=dilation, groups=groups, bias=bias),
                  nn.BatchNorm2d(out_channels)]
        self.InterMedium_Layer = InterMedium_Layer()
        if activation:
            # Error: bool obj not callable
            layers.append(self.InterMedium_Layer)
        self.seq = nn.Sequential(*layers)

I guess I called a bool var somewhere but I didn't find one.

Attached is the traceback and debug detail:

Debug page

Traceback Page

I find that the model becomes a bool type var, not a cnn network.
Is there anything wrong with my code?


问:
How can I get previous value of a TextView add to the current TextView value and so on?
I am trying to add the TextView with previous value and so on. The TextView gets updated every 5secs (real-time) and it should add on to the previous TextView value and update. For example, value at T1 = 1 -> value at T2 = 1 => at T2 TextView should update to the total of T1 and T2 = 2. Also I'm dealing with float numbers. And I'm pulling the data from FireBase.

Thank you in advance.

```<code>    private TextView tempMNData;

    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference myRef1 = database.getReference("GCU/temperature") ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extraction_page);

        tempMNData = (TextView) findViewById(R.id.temperatureMNData);

       myRef1.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot snapshot) {

               String value = snapshot.getValue(String.class);

               tempMNData.setText(value);

           }

           @Override
           public void onCancelled(@NonNull DatabaseError error) {

           }
       });

    }
</code>```

答:
If I understand correctly, you need the previous data to be added to the new ones. If so, then this might work for you:

```<code>String value = snapshot.getValue(String.class);
value2 = value2 + value;
Value2 = value2.ToString();

tempMNData.setText(value2);
</code>```

String value2 = 0

how its should working:

you take some data from FireBase, for exemple first data its "1", second "7", third "12".

in code: value = first data from FireBase, value2 = 0.

value2 = 0 + 1;

show value2 in TextView

repeate it

value2 = 1 + 7; //8
TextView(value2);

and last time

value2 = 8 + 12; // 20
TextView(value2); // show 20

Body:
I am trying to add the TextView with previous value and so on. The TextView gets updated every 5secs (real-time) and it should add on to the previous TextView value and update. For example, value at T1 = 1 -> value at T2 = 1 => at T2 TextView should update to the total of T1 and T2 = 2. Also I'm dealing with float numbers. And I'm pulling the data from FireBase.

Thank you in advance.

    private TextView tempMNData;

    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference myRef1 = database.getReference("GCU/temperature") ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extraction_page);

        tempMNData = (TextView) findViewById(R.id.temperatureMNData);

       myRef1.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot snapshot) {

               String value = snapshot.getValue(String.class);

               tempMNData.setText(value);

           }

           @Override
           public void onCancelled(@NonNull DatabaseError error) {

           }
       });

    }

Body:
If I understand correctly, you need the previous data to be added to the new ones. If so, then this might work for you:

String value = snapshot.getValue(String.class);
value2 = value2 + value;
Value2 = value2.ToString();

tempMNData.setText(value2);

String value2 = 0

how its should working:

you take some data from FireBase, for exemple first data its "1", second "7", third "12".

in code: value = first data from FireBase, value2 = 0.

value2 = 0 + 1;

show value2 in TextView

repeate it

value2 = 1 + 7; //8
TextView(value2);

and last time

value2 = 8 + 12; // 20
TextView(value2); // show 20


问:
Play framework asynch job compared to a Windows Service?
I have a windows service that checks an email account and then saves off an attached PDF that has a barcode in it. I read the barcode and route the PDF to an appropriate directory. The service runs every 5 minutes and has been working well.

So my questions:

Should I create Play Job for this? Do I constantly needs hits on the site to kick off the site? Would the job run at 2am when there's no hits?

I am trying to learn what the limitations of the Jobs are and what the alternatives would be.

答:
Jobs in Play are like CronJobs, you set the time/frequency and they will run even if there is no traffic incoming and it's 2am.

But if you already have the service running and working fine, unless you are moving to a new system were it would not be able to run (like Linux), there is no reason to reimplement it.


问:
How to preset the Value of a TNumberBox at DesignTime to a specific Integer value?
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I try to use a TNumberBox control:

```<code>object nbRowheight: TNumberBox
  Left = 20
  Top = 225
  Width = 77
  Height = 23
  Hint = 'Set the Row height.'
  Anchors = []
  MinValue = 18.000000000000000000
  TabOrder = 8
  SpinButtonOptions.ButtonWidth = 20
  SpinButtonOptions.Placement = nbspInline
end
</code>```

At design time, I try to preset it with a value of 21 in the ObjectInspector. But as soon as I enter 21 in the ObjectInspector's Value field and then press the Enter key, the Value switches back to 0!

So how can I preset the Value of a TNumberBox at DesignTime to a specific Integer value?

Update: Obviously, the issue is caused by the MaxValue left at its default value of 0: If I set MaxValue to e.g. 32 in ObjectInspector, then I can enter the Value 21 in ObjectInspector without problems. But doesn't a default MaxValue of 0 mean that it is indeterminate (i.e., that it can be any value)?

答:
Well, if MinValue = 0 and MaxValue = 0, there is no restriction.

This makes sense and is a fairly common convention in APIs.

However, to be absolutely sure, you should always consult the documentation. In this case, the documentation for MaxValue says this:

Embarcadero Technologies does not currently have any additional information.

That's a bug. Documentation is vitally important.

My initial guess was that MinValue = 0 and MaxValue = 0 means "no restriction" and any other pair means that there is a restriction, given by the bounds specified by these properties. So if you set one of them, you must set both.

In your case, you set MinValue but fail to set MaxValue. Since you want no upper bound, you can achieve this by setting MaxValue to the property's greatest possible value. (Which, since this property is of type Extended, depends on whether your app is 32-bit or 64-bit. But in practice, I bet something like 1E20 will work well for you.)

Now, was my guess correct?

Kind of.

Looking at the TNumberBox source code, I see that there is no restriction iff MinValue = MaxValue (not MinValue = 0 and MaxValue = 0 as I had guessed).

IMMNSHO, this is a strange and bad design choice. I mean, if I set MinValue and MaxValue to 20 (at runtime, because of the state of the program), I expect the value to be fixed to 20. But no! Now it can be any value.

IMMNSHO, this is a bug.

Body:
In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I try to use a TNumberBox control:

object nbRowheight: TNumberBox
  Left = 20
  Top = 225
  Width = 77
  Height = 23
  Hint = 'Set the Row height.'
  Anchors = []
  MinValue = 18.000000000000000000
  TabOrder = 8
  SpinButtonOptions.ButtonWidth = 20
  SpinButtonOptions.Placement = nbspInline
end

At design time, I try to preset it with a value of 21 in the ObjectInspector. But as soon as I enter 21 in the ObjectInspector's Value field and then press the Enter key, the Value switches back to 0!

So how can I preset the Value of a TNumberBox at DesignTime to a specific Integer value?

Update: Obviously, the issue is caused by the MaxValue left at its default value of 0: If I set MaxValue to e.g. 32 in ObjectInspector, then I can enter the Value 21 in ObjectInspector without problems. But doesn't a default MaxValue of 0 mean that it is indeterminate (i.e., that it can be any value)?


问:
list elements are not rendered in react
I have a list of elements (Knowledgebase) which I wasnt to render onlyt in the case where one of the roles in the list "roles" is equel to zero. However, it is not renderting anything

In the web-console I can also see the log

```<code>react_devtools_backend.js:4061 Warning: validateDOMNesting(...): <tr> cannot appear as a child of <td>.
    at tr
    at td
    at tr
    at tbody
    at table
    at UserList (http://localhost:3000/static/js/bundle.js:3997:91)
    at Route (http://localhost:3000/static/js/bundle.js:46456:29)
    at Switch (http://localhost:3000/static/js/bundle.js:46658:29)
    at Router (http://localhost:3000/static/js/bundle.js:46091:30)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:45712:35)
    at App
</code>```

Code:

```<code><td>
  {user.roles.map((role) => {
    if (role === "0") {
      user.knowledgeBase.map((techField) => (
        <tr key={techField}>
          <td>{techField}</td>
        </tr>
      ));
    }
  })}
</td>
</code>```

答:
You are rendering a Table Row
, inside a Table data cell . this is semantically not correct. More info here and here. Instead, you can render a new
 inside your outer .

```<code><td>
     <table>
         {user.roles.map((role) => {
            if (role === "0") {
              user.knowledgeBase.map((techField) => (
                <tr key={techField}>
                  <td>{techField}</td>
                </tr>
              ));
            }
          })}
     </table>
</td>
</code>```

Title: list elements are not rendered in react

Body:
I have a list of elements (Knowledgebase) which I wasnt to render onlyt in the case where one of the roles in the list "roles" is equel to zero. However, it is not renderting anything

In the web-console I can also see the log

react_devtools_backend.js:4061 Warning: validateDOMNesting(...):
 cannot appear as a child of .
    at tr
    at td
    at tr
    at tbody
    at table
    at UserList (http://localhost:3000/static/js/bundle.js:3997:91)
    at Route (http://localhost:3000/static/js/bundle.js:46456:29)
    at Switch (http://localhost:3000/static/js/bundle.js:46658:29)
    at Router (http://localhost:3000/static/js/bundle.js:46091:30)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:45712:35)
    at App

Code:

  {user.roles.map((role) => {
    if (role === "0") {
      user.knowledgeBase.map((techField) => (

          {techField}

      ));
    }
  })}

Body:
You are rendering a Table Row <tr>, inside a Table data cell <td>. this is semantically not correct. More info here and here. Instead, you can render a new <table> inside your outer <td>.

<td>
     <table>
         {user.roles.map((role) => {
            if (role === "0") {
              user.knowledgeBase.map((techField) => (
                <tr key={techField}>
                  <td>{techField}</td>
                </tr>
              ));
            }
          })}
     </table>
</td>


问:
Disabling PyQt5 window shadow
There is a very annoying kind of shadow/frame over my PyQt5 window. The window is made as a custom class:

class CustomWindow(QMainWindow):
    def __init__(self):
        super(CustomWindow,self).__init__()
        self.bg = '#FFFFFF'
        self.opacity =1

    def paintEvent(self, event=None):
        painter = QPainter(self)

        painter.setOpacity(self.opacity)
        painter.setBrush(QColor(self.bg))
        painter.setPen(QPen(QColor(0,0,0)))
        painter.drawRect(self.rect())

    def config(self, bg, op):
        self.bg = bg
        self.opacity = op
```

The shadow thing I'm talking about:

You can see that there are thin black lines on the left and upper edges of the window. Does anyone know how to disable them?

答:
Musicmante's solution worked:

You're drawing it. 0, 0, 0 is black in rgb. Change to painter.setPen(Qt.NoPen)

Title: Disabling PyQt5 window shadow

Body:
There is a very annoying kind of shadow/frame over my PyQt5 window. The window is made as a custom class:

class CustomWindow(QMainWindow):
    def __init__(self):
        super(CustomWindow,self).__init__()
        self.bg = '#FFFFFF'
        self.opacity =1

    def paintEvent(self, event=None):
        painter = QPainter(self)

        painter.setOpacity(self.opacity)
        painter.setBrush(QColor(self.bg))
        painter.setPen(QPen(QColor(0,0,0)))
        painter.drawRect(self.rect())

    def config(self, bg, op):
        self.bg = bg
        self.opacity = op

The shadow thing I'm talking about:

You can see that there are thin black lines on the left and upper edges of the window. Does anyone know how to disable them?


问:
Creating a Xamarin.Android project using .NET 6
How would I create a Xamarin.Android project that targets .NET 6 (Xamarin.Android being the traditional Android bindings, not .NET MAUI)?

Creating a new project from the Visual Studio 2022 UI generates the same Mono template Visual Studio 2019 does.

This guide seems to suggest manually editing the .csproj file, but doing that breaks the build with errors like:

Package Xamarin.AndroidX.AppCompat 1.3.1.3 is not compatible with monoandroid50 (MonoAndroid,Version=v5.0)

答:
Upgrade your Visual Studio to Visual Studio 2022 preview.

Version: Microsoft Visual Studio Community 2022 (64-bit) - Preview
Version 17.1.0 Preview 4.0

After that you could create Android project with .Net 6.0.


问:
Flutter DropdownMenuItem delete
I'm developing a combobox using Flutter. combobox needs to be this month and next months. should write month name in combobox and return the number of the selected month. How can I do this in the shortest way?
I developed 12 months as DropdownMenuItem. I gave the current month as the default value. So far everything is fine. but how can I make the items of the past months invisible?</p>

答:
I used this code for a similar problem.
This solution includes intl package but you can change the code in list generation for your purpose.</p>
```<code>import 'package:intl/intl.dart';

void main(){
  var today = DateTime.now();

  var length = 12 - today.month + 1;  // I added +1 because I want to include current month too

  List validMonths = List.generate(length,(index){
    return DateFormat('MMMM').format(DateTime(0, (today.month + index)));
  });

  print(validMonths);
}
</code>```

Title: Flutter DropdownMenuItem delete

Body:
I used this code for a similar problem.
This solution includes intl package but you can change the code in list generation for your purpose.

import 'package:intl/intl.dart';

void main(){
  var today = DateTime.now();

  var length = 12 - today.month + 1;  // I added +1 because I want to include current month too

  List validMonths = List.generate(length,(index){
    return DateFormat('MMMM').format(DateTime(0, (today.month + index)));
  });

  print(validMonths);
}


问:
Mongodb. Aggregate sum / Group rows by field and get sum per row / Get total field amount per user
I have payments table. Every row has a field user (id) and amount.

I need to get total spent amount per every user.

Example of payment row:

```<code>{
    "_id" : ObjectId("60ddedd27e6b7be96409257b"),
    "user" : ObjectId("60dded257e6b7be964092573"),
    "provider" : "connectum",
    "id" : "62256402926432367",
    "status" : "new",
    "amount" : "94.00",
    "currency" : "US",
    "extra" : {
        "real_gift" : ObjectId("60d1f2e580efe489fe150d75"),
        "user_id" : 245672982
    },
    "created_at" : ISODate("2021-07-01T16:31:14.000Z")
}
</code>```

I tried (as described here) and looked this docs:

```<code>db.getCollection('payments').aggregate([{"$group" : {_id : "$user", "my_field" : {$sum: "$amount"}}}])
</code>```

But every time my_field is 0, but surely this is impossible by app payment restrictions

P.S.
Additionally I need to check if user are still registered in a system (no deleted an account).

So I have a table users with last_visit column, but don't know how to combine this 2 queries.

答:
Your amount field is an string, you have to parse to double to can sum the values. You can use $toDouble like this:

```<code>db.collection.aggregate([
  {
    "$group": {
      _id: "$user",
      "my_field": {
        $sum: {
          "$toDouble": "$amount"
        }
      }
    }
  }
])
</code>```

Check this example

Body:
I have payments table. Every row has a field user (id) and amount.

I need to get total spent amount per every user.

Example of payment row:

{
    "_id" : ObjectId("60ddedd27e6b7be96409257b"),
    "user" : ObjectId("60dded257e6b7be964092573"),
    "provider" : "connectum",
    "id" : "62256402926432367",
    "status" : "new",
    "amount" : "94.00",
    "currency" : "US",
    "extra" : {
        "real_gift" : ObjectId("60d1f2e580efe489fe150d75"),
        "user_id" : 245672982
    },
    "created_at" : ISODate("2021-07-01T16:31:14.000Z")
}

I tried (as described here) and looked this docs:

db.getCollection('payments').aggregate([{"$group" : {_id : "$user", "my_field" : {$sum: "$amount"}}}])

But every time my_field is 0, but surely this is impossible by app payment restrictions

P.S.
Additionally I need to check if user are still registered in a system (no deleted an account).

So I have a table users with last_visit column, but don't know how to combine this 2 queries.

Body:
Your amount field is an string, you have to parse to double to can sum the values. You can use $toDouble like this:

db.collection.aggregate([
  {
    "$group": {
      _id: "$user",
      "my_field": {
        $sum: {
          "$toDouble": "$amount"
        }
      }
    }
  }
])

Check this example


问:
XSLT generate-id if node not exist
How can I use generate-id() if the key node does not exist? Below I have an example of input XML and my transformation, but if the key node (StockItem/Master/Sups/Sup/Addr_ID) does not exist, the data will not be fed to the output file.
I need them there.

Input.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<Data>
  <Stock>
    <StockItem>
      <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
      <Name>Alu brzda tlumič</Name>
      <Master ID="dfdbc8b0-b58a-45f8-a7ad-418802eb2045">
        <Sups>
          <Sup>
            <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
            <Addr_Name>D-HOLZ , s.r.o.</Addr_Name>
          </Sup>
        </Sups>
      </Master>
      <Status>
            <Amount>14.0000</Amount>
      </Status>
    </StockItem>

    <StockItem>
      <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
      <Name>Alu profil Wenus </Name>
      <Master ID="30f2e859-c7b1-4e04-accd-9921cdd1a6ed">
        <Sups>
          <Sup>
            <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
            <Addr_Name>D-HOLZ , s.r.o.</Addr_Name>
          </Sup>
        </Sups>
      </Master>
      <Status>
            <Amount>59.0000</Amount>
      </Status>
    </StockItem>

    <StockItem>
      <Master_ID>9ba2042f-c88a-4b13-99d2-e0e248d940b0</Master_ID>
      <Name>ANTARO 30 kg </Name>
      <Master ID="9ba2042f-c88a-4b13-99d2-e0e248d940b0">
        <Sups/>
      </Master>
      <Status>
            <Amount>0.0000</Amount>
      </Status>
    </StockItem>
    <StockItem>
      <Master_ID>69cbf3bb-a116-46dd-9ea3-9e0601fe75c6</Master_ID>
      <Name>lišta úchytková</Name>
      <Master ID="69cbf3bb-a116-46dd-9ea3-9e0601fe75c6">
        <Sups/>
      </Master>
      <Status>
            <Amount>1.0000</Amount>
      </Status>
    </StockItem>
  </Stock>
</Data>
</code>```

my xslt

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>

  <xsl:key name="adr" match="Addr_ID" use="text()" />

<xsl:template match="Data">
 <xsl:apply-templates select="Stock"/>
</xsl:template>

 <xsl:template match="Stock">
    <xsl:element name="SortData">
    <xsl:for-each select="StockItem/Master/Sups/Sup/Addr_ID[generate-id() = generate-id(key('adr',.))]">

    <xsl:element name="Sup">
      <Addr_ID>
         <xsl:value-of select="." />
      </Addr_ID>

       <xsl:for-each select="key('adr',.)">

            <xsl:element name ="Item">
              <xsl:element name ="Master_ID">
                <xsl:value-of select="../../../@ID"/>
              </xsl:element>

              <xsl:element name ="Amount" >
                <xsl:value-of select="../../../../Status/Amount"/>
              </xsl:element>

            </xsl:element>

          </xsl:for-each>
        </xsl:element>

      </xsl:for-each>
      </xsl:element>

  </xsl:template>

</xsl:stylesheet>
</code>```

My output si:

```<code><SortData>
 <Sup>
  <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
  <Item>
   <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
   <Amount>14.0000</Amount>
  </Item>
  <Item>
   <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
   <Amount>59.0000</Amount>
  </Item>
 </Sup>
</SortData>
</code>```

But desired output is:

```<code><SortData>
   <Sup>
      <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
      <Item>
         <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
         <Amount>14.0000</Amount>
      </Item>
      <Item>
         <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
         <Amount>59.0000</Amount>
      </Item>
   </Sup>

<!-- This part is missing in my output-->
   <Sup>
      <Addr_ID />
      <!-- or <Addr_ID>none</Addr_ID-->
      <Item>
         <Master_ID>9ba2042f-c88a-4b13-99d2-e0e248d940b0</Master_ID>
         <Amount>0.0000</Amount>
      </Item>
      <Item>
         <Master_ID>69cbf3bb-a116-46dd-9ea3-9e0601fe75c6</Master_ID>
         <Amount>1.0000</Amount>
      </Item>
   </Sup>
</SortData>
</code>```

答:
AFAICT you want to group the master items by Addr_ID in Sup - which may or may not exist.

This could be done as follows:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="adr" match="Master" use="string(Sups/Sup/Addr_ID)" />

<xsl:template match="/Data">
    <SortData>
        <xsl:for-each select="Stock/StockItem/Master[generate-id() = generate-id(key('adr', string(Sups/Sup/Addr_ID)))]">
            <Sup>
                <Addr_ID>
                    <xsl:value-of select="Sups/Sup/Addr_ID"/>
                </Addr_ID>
                <xsl:for-each select="key('adr', string(Sups/Sup/Addr_ID))">
                    <Item>
                        <Master_ID>
                            <xsl:value-of select="@ID"/>
                        </Master_ID>
                        <Amount>
                            <xsl:value-of select="../Status/Amount"/>
                        </Amount>
                    </Item>
                </xsl:for-each>
            </Sup>
        </xsl:for-each>
    </SortData>
</xsl:template>

</xsl:stylesheet>
</code>```

Note that this assumes each Master has at most one Sup - while your structure allows for multiple occurrences of Sup in each Master.

Title: XSLT generate-id if node not exist

Body:
How can I use generate-id() if the key node does not exist? Below I have an example of input XML and my transformation, but if the key node (StockItem/Master/Sups/Sup/Addr_ID) does not exist, the data will not be fed to the output file.
I need them there.

Input.xml

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <Stock>
    <StockItem>
      <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
      <Name>Alu brzda tlumič</Name>
      <Master ID="dfdbc8b0-b58a-45f8-a7ad-418802eb2045">
        <Sups>

            <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
            <Addr_Name>D-HOLZ , s.r.o.</Addr_Name>

        </Sups>
      </Master>
      <Status>
            <Amount>14.0000</Amount>
      </Status>
    </StockItem>

    <StockItem>
      <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
      <Name>Alu profil Wenus </Name>
      <Master ID="30f2e859-c7b1-4e04-accd-9921cdd1a6ed">
        <Sups>

            <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
            <Addr_Name>D-HOLZ , s.r.o.</Addr_Name>

        </Sups>
      </Master>
      <Status>
            <Amount>59.0000</Amount>
      </Status>
    </StockItem>

    <StockItem>
      <Master_ID>9ba2042f-c88a-4b13-99d2-e0e248d940b0</Master_ID>
      <Name>ANTARO 30 kg </Name>
      <Master ID="9ba2042f-c88a-4b13-99d2-e0e248d940b0">
        <Sups/>
      </Master>
      <Status>
            <Amount>0.0000</Amount>
      </Status>
    </StockItem>
    <StockItem>
      <Master_ID>69cbf3bb-a116-46dd-9ea3-9e0601fe75c6</Master_ID>
      <Name>lišta úchytková</Name>
      <Master ID="69cbf3bb-a116-46dd-9ea3-9e0601fe75c6">
        <Sups/>
      </Master>
      <Status>
            <Amount>1.0000</Amount>
      </Status>
    </StockItem>
  </Stock>
</Data>

my xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="yes"/>

  <xsl:key name="adr" match="Addr_ID" use="text()" />

<xsl:template match="Data">
 <xsl:apply-templates select="Stock"/>
</xsl:template>

 <xsl:template match="Stock">
    <xsl:element name="SortData">
    <xsl:for-each select="StockItem/Master/Sups/Sup/Addr_ID[generate-id() = generate-id(key('adr',.))]">

    <xsl:element name="Sup">
      <Addr_ID>
         <xsl:value-of select="." />
      </Addr_ID>

       <xsl:for-each select="key('adr',.)">

            <xsl:element name ="Item">
              <xsl:element name ="Master_ID">
                <xsl:value-of select="../../../@ID"/>
              </xsl:element>

              <xsl:element name ="Amount" >
                <xsl:value-of select="../../../../Status/Amount"/>
              </xsl:element>

            </xsl:element>

          </xsl:for-each>
        </xsl:element>

      </xsl:for-each>
      </xsl:element>

  </xsl:template>

</xsl:stylesheet>

My output si:

<SortData>

  <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
  <Item>
   <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
   <Amount>14.0000</Amount>
  </Item>
  <Item>
   <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
   <Amount>59.0000</Amount>
  </Item>

</SortData>

But desired output is:

<SortData>

      <Addr_ID>6898e66a-5315-4933-9895-a226bbec8aad</Addr_ID>
      <Item>
         <Master_ID>dfdbc8b0-b58a-45f8-a7ad-418802eb2045</Master_ID>
         <Amount>14.0000</Amount>
      </Item>
      <Item>
         <Master_ID>30f2e859-c7b1-4e04-accd-9921cdd1a6ed</Master_ID>
         <Amount>59.0000</Amount>
      </Item>

      <Addr_ID />

      <Item>
         <Master_ID>9ba2042f-c88a-4b13-99d2-e0e248d940b0</Master_ID>
         <Amount>0.0000</Amount>
      </Item>
      <Item>
         <Master_ID>69cbf3bb-a116-46dd-9ea3-9e0601fe75c6</Master_ID>
         <Amount>1.0000</Amount>
      </Item>

</SortData>

Body:
AFAICT you want to group the master items by Addr_ID in Sup - which may or may not exist.

This could be done as follows:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="adr" match="Master" use="string(Sups/Sup/Addr_ID)" />

<xsl:template match="/Data">
    <SortData>
        <xsl:for-each select="Stock/StockItem/Master[generate-id() = generate-id(key('adr', string(Sups/Sup/Addr_ID)))]">
            <Sup>
                <Addr_ID>
                    <xsl:value-of select="Sups/Sup/Addr_ID"/>
                </Addr_ID>
                <xsl:for-each select="key('adr', string(Sups/Sup/Addr_ID))">
                    <Item>
                        <Master_ID>
                            <xsl:value-of select="@ID"/>
                        </Master_ID>
                        <Amount>
                            <xsl:value-of select="../Status/Amount"/>
                        </Amount>
                    </Item>
                </xsl:for-each>
            </Sup>
        </xsl:for-each>
    </SortData>
</xsl:template>

</xsl:stylesheet>

Note that this assumes each Master has at most one Sup - while your structure allows for multiple occurrences of Sup in each Master.


问:
How to get value out of mono
I'm trying to extract a String out out Mono.

Mono method:

```<code>public Mono<String> getVal() {
    return webClient.get()
        .uri("/service")
        .retrieve()
        .bodyToMono(String.class);
}
</code>```

Calling getVal():

```<code>String val = getVal().block();
</code>```

I tried using block() but it returns the following error:

```<code>java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking,
which is not supported in thread reactor-http-nio-3
</code>```

I suppose I would have to use a non-blocking method like subscribe() which I'm not to sure how to.

答:
If you are using reactive programming, try to avoid blocking calls and use already existing features.

public Mono<String> getVal() {
    return webClient.get()
        .uri("/service")
        .retrieve()
        .bodyToMono(String.class)
        .map(str ->  {
          // You have your string unwrapped here
          return str;
        });
}
```

Title: How to get value out of mono

Body:
I'm trying to extract a String out out Mono.

Mono method:

public Mono<String> getVal() {
    return webClient.get()
        .uri("/service")
        .retrieve()
        .bodyToMono(String.class);
}

Calling getVal():

String val = getVal().block();

I tried using block() but it returns the following error:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking,
which is not supported in thread reactor-http-nio-3

I suppose I would have to use a non-blocking method like subscribe() which I'm not to sure how to.


问:
Are there any compression and encryption libraries in C#?
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

答: I'm not sure if the steps can be combined, but .NET has good support for basic crypto. Here's an article on it.</p>

OwnerDisplayName: Niyaz

OwnerDisplayName: Hank Gay


问:
What's the difference between string template and log framework's placeholder in Kotlin?
And now, I am trying to rewrite my java application in Kotlin. And then, I met the log statement, like

log.info("do the print thing for {}", arg);
```

So I have two ways to do the log things in Kotlin like log.info("do the print thing for {}", arg) and log.info("do the print thing for $arg"). The 1st is delegate format to framework like Slf4j or Log4j; the 2nd is using Kotlin string template.

So what's the difference and which one's performance is better?

答:
In general, these two ways produce the same log, unless the logging library is also configured to localise the message and parameters when formatting the message, which Kotlin's string interpolation does not do at all.

The crucial difference lies in the performance, when you turn off logging (at that particular level). As SLF4J's FAQ says:

There exists a very convenient alternative based on message formats.
Assuming entry is an object, you can write:

```<code>Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);
</code>```

After evaluating whether to log or not, and only if the decision is
affirmative, will the logger implementation format the message and
replace the '{}' pair with the string value of entry. In other words,
this form does not incur the cost of parameter construction in case
the log statement is disabled.

The following two lines will yield the exact same output. However, the
second form will outperform the first form by a factor of at least 30,
in case of a disabled logging statement.

```<code>logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
</code>```

Basically, if the logging is disabled, the message won't be constructed if you use parameterised logging. If you use string interpolation however, the message will always be constructed.

Note that Kotlin's string interpolation compiles to something similar to what a series of string concatenation (+) in Java compiles to (though this might change in the future).

```<code>"foo $bar baz"
</code>```

is translated into:

```<code>StringBuilder().append("foo ").append(bar).append(" baz").toString()
</code>```

See also: Unable to understand why to use parameterized logging

Body:
And now, I am trying to rewrite my java application in Kotlin. And then, I met the log statement, like

log.info("do the print thing for {}", arg);

So I have two ways to do the log things in Kotlin like log.info("do the print thing for {}", arg) and log.info("do the print thing for $arg"). The 1st is delegate format to framework like Slf4j or Log4j; the 2nd is using Kotlin string template.

So what's the difference and which one's performance is better?

Body:
In general, these two ways produce the same log, unless the logging library is also configured to localise the message and parameters when formatting the message, which Kotlin's string interpolation does not do at all.

The crucial difference lies in the performance, when you turn off logging (at that particular level). As SLF4J's FAQ says:

There exists a very convenient alternative based on message formats.
Assuming entry is an object, you can write:

Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);

After evaluating whether to log or not, and only if the decision is
affirmative, will the logger implementation format the message and
replace the '{}' pair with the string value of entry. In other words,
this form does not incur the cost of parameter construction in case
the log statement is disabled.

The following two lines will yield the exact same output. However, the
second form will outperform the first form by a factor of at least 30,
in case of a disabled logging statement.

logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);

Basically, if the logging is disabled, the message won't be constructed if you use parameterised logging. If you use string interpolation however, the message will always be constructed.

Note that Kotlin's string interpolation compiles to something similar to what a series of string concatenation (+) in Java compiles to (though this might change in the future).

"foo $bar baz"

is translated into:

StringBuilder().append("foo ").append(bar).append(" baz").toString()

See also: Unable to understand why to use parameterized logging


问:
How to use ChakraUI extended fonts
Hello I have question can I have 2 different fonts for Heading like you know you define
<Heading fontFamily={???}></Heading> and set font family inside it. I do not want to have one font family for heading.

```<code>import { extendTheme } from "@chakra-ui/react";

const theme = extendTheme({
  fonts: {
    heading: "Dancing Script",
  },
});

export default theme;
</code>```

答:
Yes, you can write <Heading fontFamily="myFont1"></Heading> and <Heading fontFamily="myFont2">Some Text</Heading> if you declare these two fonts in your extended theme:

import { extendTheme } from "@chakra-ui/react";
import "@fontsource/dancing-script";

const theme = extendTheme({
  fonts: {
    myFont1: "Dancing Script",
    myFont2: "Times New Roman",
  },
});

export default theme;
```

Also, notice that I didn't have to import any external library for Times New Roman (because it's likely to already be installed on you users' computer) but I had to import @fontsource/dancing-script because it's not a standard font. (Remember to install it with npm install --save @fontsource/dancing-script before you use it).

You can probably find any fonts you need on FontSource, and for more information (and alternative solutions) there is the Chakra UI documentation on fonts.

Title: How to use ChakraUI extended fonts

Body:
Hello I have question can I have 2 different fonts for Heading like you know you define
<Heading fontFamily={???}></Heading> and set font family inside it. I do not want to have one font family for heading.

import { extendTheme } from "@chakra-ui/react";

const theme = extendTheme({
  fonts: {
    heading: "Dancing Script",
  },
});

export default theme;

Body:
Yes, you can write <Heading fontFamily="myFont1"></Heading> and <Heading fontFamily="myFont2">Some Text</Heading> if you declare these two fonts in your extended theme:

import { extendTheme } from "@chakra-ui/react";
import "@fontsource/dancing-script";

const theme = extendTheme({
  fonts: {
    myFont1: "Dancing Script",
    myFont2: "Times New Roman",
  },
});

export default theme;

Also, notice that I didn't have to import any external library for Times New Roman (because it's likely to already be installed on you users' computer) but I had to import @fontsource/dancing-script because it's not a standard font. (Remember to install it with npm install --save @fontsource/dancing-script before you use it).

You can probably find any fonts you need on FontSource, and for more information (and alternative solutions) there is the Chakra UI documentation on fonts.


问:
flutter CustomPainter - how to cut out a hole in line path
I have a CustomPaint which paints an oval.

I want to cut out a hole at a specific position which I couldn't figure out yet how that works.

I tried:

canvas.drawPath(
      Path.combine(PathOperation.difference, ovalPath, holePath),
      ovalPaint,
    );
```
<p>but that doesn't cut the hole, but gives me the following result:</p>
<p><img src="https://i.stack.imgur.com/vtDnB.png" alt="enter image description here" /></p>
<p>But this is what I want to achieve:
<img src="https://i.stack.imgur.com/fwvjq.png" alt="enter image description here" /></p>
<p>This oval is just an example, the "real" custom paint is gonna get more complex and I need more than just one cutout. So just painting several lines is not an alternative. I want to first define the path and then apply a cutout (or even inverted clipping) to get the hole.</p>
<p>Is that possible?</p>
<p>Here is a full working example of what I have:</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
import 'dart:math';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: OvalCustomPaint(),
        ),
      ),
    );
  }
}

class OvalCustomPaint extends StatelessWidget {
  const OvalCustomPaint({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: LayoutBuilder(
        builder: (context, constraints) {
          return Center(
            child: CustomPaint(
              painter: _Painter(),
              child: SizedBox(
                width: constraints.maxWidth,
                height: constraints.maxHeight,
              ),
            ),
          );
        },
      ),
    );
  }
}

class _Painter extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    canvas.translate(size.width / 2, size.height / 2);
    const curveRadius = 50.0;
    const legLength = 150.0;
    canvas.rotate(pi/2);

    final ovalPaint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 2.5
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    const fixPoint = Offset.zero;

    //* OVAL LINE
    final ovalPath = Path()..moveTo(fixPoint.dx, fixPoint.dy);
    ovalPath.relativeArcToPoint(
      const Offset(curveRadius * 2, 0),
      radius: const Radius.circular(curveRadius),
    );
    ovalPath.relativeLineTo(0, legLength);
    ovalPath.relativeArcToPoint(
      const Offset(-curveRadius * 2, 0),
      radius: const Radius.circular(curveRadius),
    );
    ovalPath.relativeLineTo(0, -legLength);

    //* CLP HOLE
    final holePath = Path();
    holePath.addArc(Rect.fromCircle(center: fixPoint, radius: 13), 0, 2 * pi);

    canvas.drawPath(
      Path.combine(PathOperation.difference, ovalPath, holePath),
      ovalPaint,
    );
  }

  @override
  bool shouldRepaint(_Painter oldDelegate) => false;

}
</code>```

答:
You can control the length of the line.

ovalPath.relativeArcToPoint(
  const Offset(-curveRadius * 2, 0),
  radius: const Radius.circular(curveRadius),
);
ovalPath.relativeLineTo(0, -legLength + (13 * 2)); //here based on radius

canvas.drawPath(
  ovalPath,
  ovalPaint,
);
```

Body:
I have a CustomPaint which paints an oval.

I want to cut out a hole at a specific position which I couldn't figure out yet how that works.

I tried:

canvas.drawPath(
      Path.combine(PathOperation.difference, ovalPath, holePath),
      ovalPaint,
    );

but that doesn't cut the hole, but gives me the following result:

But this is what I want to achieve:

This oval is just an example, the "real" custom paint is gonna get more complex and I need more than just one cutout. So just painting several lines is not an alternative. I want to first define the path and then apply a cutout (or even inverted clipping) to get the hole.

Is that possible?

Here is a full working example of what I have:

import 'package:flutter/material.dart';
import 'dart:math';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: const Scaffold(
        body: Center(
          child: OvalCustomPaint(),
        ),
      ),
    );
  }
}

class OvalCustomPaint extends StatelessWidget {
  const OvalCustomPaint({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: LayoutBuilder(
        builder: (context, constraints) {
          return Center(
            child: CustomPaint(
              painter: _Painter(),
              child: SizedBox(
                width: constraints.maxWidth,
                height: constraints.maxHeight,
              ),
            ),
          );
        },
      ),
    );
  }
}

class _Painter extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    canvas.translate(size.width / 2, size.height / 2);
    const curveRadius = 50.0;
    const legLength = 150.0;
    canvas.rotate(pi/2);

    final ovalPaint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 2.5
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    const fixPoint = Offset.zero;

    //* OVAL LINE
    final ovalPath = Path()..moveTo(fixPoint.dx, fixPoint.dy);
    ovalPath.relativeArcToPoint(
      const Offset(curveRadius * 2, 0),
      radius: const Radius.circular(curveRadius),
    );
    ovalPath.relativeLineTo(0, legLength);
    ovalPath.relativeArcToPoint(
      const Offset(-curveRadius * 2, 0),
      radius: const Radius.circular(curveRadius),
    );
    ovalPath.relativeLineTo(0, -legLength);

    //* CLP HOLE
    final holePath = Path();
    holePath.addArc(Rect.fromCircle(center: fixPoint, radius: 13), 0, 2 * pi);

    canvas.drawPath(
      Path.combine(PathOperation.difference, ovalPath, holePath),
      ovalPaint,
    );
  }

  @override
  bool shouldRepaint(_Painter oldDelegate) => false;

}