问:
Counting the number of lines in a .txt file in c
I have a processes.txt file that contains details about incoming processes like so,

```<code>0 4 96 30
3 2 32 40
5 1 100 20
20 3 4 30
</code>```

I wanted to find the number of lines in this file. How can that be done?

I tried this code, but it always returns the number of lines as 0

```<code>char c;
int count = 0;
// fp is the pile pointer
for (c = getc(fp); c != EOF; c = getc(fp))
        if (c == '\n') // Increment count if this character is newline
            count = count + 1;
</code>```

答:
Please, read How to create a minimal, complete and verifiable example.

In order to test your program snippet, I first had to complete your fragment of code in order to make it compilable.  Probably your error has gone with that modifications, as my run of it shows (over your input text) this output:

pru.c

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

int main()
{
        char c;
        int count = 0;
        FILE *fp = stdin; // most probably your error is
                          // related to this initialization.

        // fp is the pile pointer
        for (c = getc(fp); c != EOF; c = getc(fp))
                        if (c == '\n') // Increment count if this character is newline
                                count = count + 1;
        printf("%d\n", count);

        return 0;
}
</code>```

and running it:

```<code>$ pru <<EOF
0 4 96 30
3 2 32 40
5 1 100 20
20 3 4 30
EOF
4
$ _
</code>```

Which is the correct answer.

Despite of this, your program fragment, shows a non visible error, as you have been told in the comments to your question:  type of c variable should be int and not char, but why?

Because char is the type you want to receive, all available values are possible, so to indicate that some special condition has been detected in your file (the end of the data in the stream, or EOF is not one of those values, but a special condition) one extra value is needed, so making the type char insufficient to include all possible return values from fgetc(3).  This is the reason to make fgetc(3) function to return an int.

Check the documentation of fgetc(3) as your program works almost fine, while you have to be given a reason of why:

When the program reads a character, it is mapped into the int values 0 to 255, so all different bytes convert as positive integer values, while normally (almost every implementation does) EOF is mapped into the integer value -1.  What is happening here is that all your values are converted into a char, making EOF to be mapped into one of those 0 to 256 values (which one is dependent on the implementation, but normally it is the value 255 ---or -1 if char happens to be signed) so:

in case your char type is represented as a two's complement type (signed) your values 0 to 255 are mapped into 0 to 127 and -128 to -1, and the EOF value is mapped to some of them (mostly -1).

in case your char type is represented as an unsigned type, your values 0 to 255 are mapped into 0 to 255 and the EOF value is mapped to one of them (most probably 255)

it doesn't matter which value the EOF is converted to, as you make your comparison in a coherent type system, so the converted char value is compared with the converted EOF value making that EOF is converted into the converted value of EOF.  But this makes another char value to happen to show the same behaviour, making that one such charater on input will be interpreted as EOF, and will  make your program to stop prematurely.

In both cases above, if a byte with the same mapped-to value of EOF is input, your program will finish, believing that it has reached the end of the file, and your count will be erroneous.  This is not the case here, but you can get a surprise with one file that has such a character.

So your final program (corrected) would be:

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

int main()
{
        int c;
        int count = 0;
        FILE *fp = stdin;

        // fp is the pile pointer
        for (c = getc(fp); c != EOF; c = getc(fp))
                        if (c == '\n') // Increment count if this character is newline
                                count = count + 1;
        printf("%d\n", count);

        return 0;
}
</code>```

Before terminating, I'll recommend to use a while loop, as it is a frequently used idiom in C to produce more compact form of your loop:

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

int main()
{
        int c;
        long count = 0;
        FILE *fp = stdin; /* probably you dont have intialized this
                           * field in your code, but who knows, if
                           * you have not posted a complete
                           * sample */

        // fp is the pile pointer
        while ((c = getc(fp)) != EOF)
              if (c == '\n') // Increment count if this character is newline
                 count++; // this is another  frequently used idiom :)

        printf("%d\n", count);

        return 0;
}
</code>```

Body:
I have a processes.txt file that contains details about incoming processes like so,

0 4 96 30
3 2 32 40
5 1 100 20
20 3 4 30

I wanted to find the number of lines in this file. How can that be done?

I tried this code, but it always returns the number of lines as 0

char c;
int count = 0;
// fp is the pile pointer
for (c = getc(fp); c != EOF; c = getc(fp))
        if (c == '\n') // Increment count if this character is newline
            count = count + 1;

Body:
Please, read How to create a minimal, complete and verifiable example.

In order to test your program snippet, I first had to complete your fragment of code in order to make it compilable.  Probably your error has gone with that modifications, as my run of it shows (over your input text) this output:

pru.c

#include <stdio.h>

int main()
{
        char c;
        int count = 0;
        FILE *fp = stdin; // most probably your error is
                          // related to this initialization.

        // fp is the pile pointer
        for (c = getc(fp); c != EOF; c = getc(fp))
                        if (c == '\n') // Increment count if this character is newline
                                count = count + 1;
        printf("%d\n", count);

        return 0;
}

and running it:

$ pru <<EOF
0 4 96 30
3 2 32 40
5 1 100 20
20 3 4 30
EOF
4
$ _

Which is the correct answer.

Despite of this, your program fragment, shows a non visible error, as you have been told in the comments to your question:  type of c variable should be int and not char, but why?

Because char is the type you want to receive, all available values are possible, so to indicate that some special condition has been detected in your file (the end of the data in the stream, or EOF is not one of those values, but a special condition) one extra value is needed, so making the type char insufficient to include all possible return values from fgetc(3).  This is the reason to make fgetc(3) function to return an int.

Check the documentation of fgetc(3) as your program works almost fine, while you have to be given a reason of why:

When the program reads a character, it is mapped into the int values 0 to 255, so all different bytes convert as positive integer values, while normally (almost every implementation does) EOF is mapped into the integer value -1.  What is happening here is that all your values are converted into a char, making EOF to be mapped into one of those 0 to 256 values (which one is dependent on the implementation, but normally it is the value 255 ---or -1 if char happens to be signed) so:

in case your char type is represented as a two's complement type (signed) your values 0 to 255 are mapped into 0 to 127 and -128 to -1, and the EOF value is mapped to some of them (mostly -1).

in case your char type is represented as an unsigned type, your values 0 to 255 are mapped into 0 to 255 and the EOF value is mapped to one of them (most probably 255)

it doesn't matter which value the EOF is converted to, as you make your comparison in a coherent type system, so the converted char value is compared with the converted EOF value making that EOF is converted into the converted value of EOF.  But this makes another char value to happen to show the same behaviour, making that one such charater on input will be interpreted as EOF, and will  make your program to stop prematurely.

In both cases above, if a byte with the same mapped-to value of EOF is input, your program will finish, believing that it has reached the end of the file, and your count will be erroneous.  This is not the case here, but you can get a surprise with one file that has such a character.

So your final program (corrected) would be:

#include <stdio.h>

int main()
{
        int c;
        int count = 0;
        FILE *fp = stdin;

        // fp is the pile pointer
        for (c = getc(fp); c != EOF; c = getc(fp))
                        if (c == '\n') // Increment count if this character is newline
                                count = count + 1;
        printf("%d\n", count);

        return 0;
}

Before terminating, I'll recommend to use a while loop, as it is a frequently used idiom in C to produce more compact form of your loop:

#include <stdio.h>

int main()
{
        int c;
        long count = 0;
        FILE *fp = stdin; /* probably you dont have intialized this
                           * field in your code, but who knows, if
                           * you have not posted a complete
                           * sample */

        // fp is the pile pointer
        while ((c = getc(fp)) != EOF)
              if (c == '\n') // Increment count if this character is newline
                 count++; // this is another  frequently used idiom :)

        printf("%d\n", count);

        return 0;
}


来源: stackexchange

问:
Does application event term exist in DDD?
Domain events are well known in DDD, which can be published in Aggregate Roots or in Domain Services. My question here is, Can domain events be published in application services/use cases?

For example, simplifying. I have an application service called UseCaseA, which performs various operations calling some aggregate roots. If I want to raise an event when this use case ends, could I publish the UseCaseAFinished event within this application service? Is it a domain event or should it be called an application event? Does application event terminology exist in DDD?

Thanks in advance.

答:
I think you should look this from another perspective. Let me explain.

Instead of raising an event as an outcome of your UseCaseA to handle your side effects, such as sending an email the event you want to raise should still be a Domain Event like you described.

Then at the time of handling this specific Domain Event you could raise an "Application event" (I'd call them Integration Events) which would then handle the side effect of sending an email, doing monitoring, logging..

This integration event can span multiple BCs, services and even applications.

Step-by-step flow example:

Start executing UseCaseA

Perform operations on entities, change state etc.

Raise a domain event from the domain

Dispatch the domain event just before the end of executing UseCaseA

Catch the domain event in one or more Domain Event Handlers

In one of those handlers, raise an Integration Event to handle "application wide" side-effects

Handle integration event in Integration Event Handler and send emails, do logging, notify monitoring etc.

The integration event can be dispatched multiple ways, but usually via some sort of event bus.

ContentLicense: CC BY-SA 4.0


问:
How can I get the months between two dates in Oracle SQL
I need to get the numbers of the months between two dates.
For example, between those dates: "03/03/2020 - 06/06/2020"
I need something like "(03,04,05,06)".</p>

答:
I am a SQL Server programmer, and if your question was about SQL Server then the solution would be like this:

```<code>;WITH cte AS
(
SELECT TOP (DATEDIFF(MONTH, '2020-03-03', '2020-06-06') + 1)
Format(DateAdd(MONTH, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, '2020-03-03'), 'MM',
'en-US') AS MonthNumber
FROM    sys.all_objects a
)
SELECT '(' + String_Agg(MonthNumber, ', ') + ')' AS Result
FROM cte;
</code>```

I have tested the above and it returns '(03, 04, 05, 06)' as desired.
I did my best to rewrite the above SQL Server solution into Oracle SQL, but I am unable to test it at the moment. You can try it out:

```<code>WITH cte AS
(
SELECT TOP (MONTHS_BETWEEN (TO_DATE('06/06/2020','DD/MM/YYYY'),
                            TO_DATE('03/03/2020','DD/MM/YYYY') ) + 1)
TO_CHAR(ADD_MONTHS(ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, TO_DATE('03/03/2020','DD/MM/YYYY')), 'MM')
AS MonthNumber
FROM sys.all_objects a
)
SELECT '(' + LIST_AGG(MonthNumber, ', ') + ')' AS Result
FROM cte;
</code>```

Body:
I am a SQL Server programmer, and if your question was about SQL Server then the solution would be like this:

;WITH cte AS
(
SELECT TOP (DATEDIFF(MONTH, '2020-03-03', '2020-06-06') + 1)
Format(DateAdd(MONTH, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, '2020-03-03'), 'MM',
'en-US') AS MonthNumber
FROM    sys.all_objects a
)
SELECT '(' + String_Agg(MonthNumber, ', ') + ')' AS Result
FROM cte;

I have tested the above and it returns '(03, 04, 05, 06)' as desired.
I did my best to rewrite the above SQL Server solution into Oracle SQL, but I am unable to test it at the moment. You can try it out:

WITH cte AS
(
SELECT TOP (MONTHS_BETWEEN (TO_DATE('06/06/2020','DD/MM/YYYY'),
                            TO_DATE('03/03/2020','DD/MM/YYYY') ) + 1)
TO_CHAR(ADD_MONTHS(ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, TO_DATE('03/03/2020','DD/MM/YYYY')), 'MM')
AS MonthNumber
FROM sys.all_objects a
)
SELECT '(' + LIST_AGG(MonthNumber, ', ') + ')' AS Result
FROM cte;


问:
Unable to generate jmeter html report from java code
When trying to generate html report using java code, I can only see a statistics.json generated but no html reports are there.

My Java Code -

```<code>ResultCollector logger = new ResultCollector(summer);
logger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);

//run
StandardJMeterEngine jMeterEngine = new StandardJMeterEngine();
jMeterEngine.configure(testPlanTree);
jMeterEngine.run();

//Report Generator
ReportGenerator rg = new ReportGenerator(csvFile, null);
rg.generate();
</code>```

In my reportgenerator.properties, I have following entries (only end part)

```<code>jmeter.reportgenerator.exporter.html.classname=org.apache.jmeter.report.dashboard.HtmlTemplateExporter
jmeter.reportgenerator.exporter.html.property.template_dir=report-template
jmeter.reportgenerator.exporter.json.classname=org.apache.jmeter.report.dashboard.JsonExporter
jmeter.reportgenerator.exporter.json.property.output_dir=report-output
</code>```

I have checked that the csv file is generated and has valid data, because i tried generating html report from jmeter command line using the same csv and it worked.

After the execution, my java code only produces a statistics.json file but no html reports are generated. There are no errors in the logs (only few warnings related to some properties not set and default being used).

Edit
I'm setting the JMeter property jmeter.reportgenerator.outputdir in java code -

```<code>properties.put(org.apache.jmeter.JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY, "report-path");
</code>```

The output logs -

```<code>   Creating statistics for overall
    Creating statistics for other transactions
    Checking output folder
    Writing statistics JSON to path\to\dir\statistics.json
    Exporting data using exporter:'html' of
 className:'org.apache.jmeter.report.dashboard.HtmlTemplateExporter'
    Will generate dashboard in folder: path\to\dir
</code>```

It says 'will generate dashboard in folder' in the logs but no html is generated.
Any idea what I might be missing?

答:
After checking out all the configurations, I went on to debug the code in JMeter's ReportGenerator class, to check at what point the code fails. Here' the hierarchy of the code used in gnerating html reports -

```<code>ReportGenerator generator = new ReportGenerator(csvFileName, null);
generator.generate();
</code>```

```<code> public void generate() throws GenerationException {
 -----
 exportData(sampleContext, key, value);
 -----
 }
</code>```

```<code>private void exportData(SampleContext sampleContext, String exporterName,
        ExporterConfiguration exporterConfiguration)
        throws GenerationException {
----
 exporter.export(sampleContext, testFile, configuration);
----
}
</code>```

Eventualy, export() method of HTMLTemplateExporter is invoked -

public void export(SampleContext context, File file,
            ReportGeneratorConfiguration configuration) throws ExportException {
    ----
    Configuration templateCfg = new Configuration(
                Configuration.getVersion());
    ----

The code fails here while creating new configuration for Freemarker. JMeter internally uses Freemarker templating engine to generate the dashboard reports.

On further analysis, I could figure out that I had conflicting dependencies for Freemarker library. Freemarker dependencies are added with JMeter lib itslef, while my application was already using a different vesion of freemarker library. I had to exclude one of the versions (using exclude tags in pom.xml) and made sure that only one version is present. (You can check this using maven dependency tree.)

PS - Although in maven dependency tree, initialy it appeared that the older version was omitted and only one version is being used. It was the reason I didn't doubt on the library versions conflict. But on debugging, I was convinced that the code was failing due to conflicting libs, and I had to explicitly make sure that only one lib version is there.

Body:
When trying to generate html report using java code, I can only see a statistics.json generated but no html reports are there.

My Java Code -

ResultCollector logger = new ResultCollector(summer);
logger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);

//run
StandardJMeterEngine jMeterEngine = new StandardJMeterEngine();
jMeterEngine.configure(testPlanTree);
jMeterEngine.run();

//Report Generator
ReportGenerator rg = new ReportGenerator(csvFile, null);
rg.generate();

In my reportgenerator.properties, I have following entries (only end part)

jmeter.reportgenerator.exporter.html.classname=org.apache.jmeter.report.dashboard.HtmlTemplateExporter
jmeter.reportgenerator.exporter.html.property.template_dir=report-template
jmeter.reportgenerator.exporter.json.classname=org.apache.jmeter.report.dashboard.JsonExporter
jmeter.reportgenerator.exporter.json.property.output_dir=report-output

I have checked that the csv file is generated and has valid data, because i tried generating html report from jmeter command line using the same csv and it worked.

After the execution, my java code only produces a statistics.json file but no html reports are generated. There are no errors in the logs (only few warnings related to some properties not set and default being used).

Edit
I'm setting the JMeter property jmeter.reportgenerator.outputdir in java code -

properties.put(org.apache.jmeter.JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY, "report-path");

The output logs -

   Creating statistics for overall
    Creating statistics for other transactions
    Checking output folder
    Writing statistics JSON to path\to\dir\statistics.json
    Exporting data using exporter:'html' of
 className:'org.apache.jmeter.report.dashboard.HtmlTemplateExporter'
    Will generate dashboard in folder: path\to\dir

It says 'will generate dashboard in folder' in the logs but no html is generated.
Any idea what I might be missing?

Body:
After checking out all the configurations, I went on to debug the code in JMeter's ReportGenerator class, to check at what point the code fails. Here' the hierarchy of the code used in gnerating html reports -

ReportGenerator generator = new ReportGenerator(csvFileName, null);
generator.generate();

 public void generate() throws GenerationException {
 -----
 exportData(sampleContext, key, value);
 -----
 }

private void exportData(SampleContext sampleContext, String exporterName,
        ExporterConfiguration exporterConfiguration)
        throws GenerationException {
----
 exporter.export(sampleContext, testFile, configuration);
----
}

Eventualy, export() method of HTMLTemplateExporter is invoked -

public void export(SampleContext context, File file,
            ReportGeneratorConfiguration configuration) throws ExportException {
    ----
    Configuration templateCfg = new Configuration(
                Configuration.getVersion());
    ----

The code fails here while creating new configuration for Freemarker. JMeter internally uses Freemarker templating engine to generate the dashboard reports.

On further analysis, I could figure out that I had conflicting dependencies for Freemarker library. Freemarker dependencies are added with JMeter lib itslef, while my application was already using a different vesion of freemarker library. I had to exclude one of the versions (using exclude tags in pom.xml) and made sure that only one version is present. (You can check this using maven dependency tree.)

PS - Although in maven dependency tree, initialy it appeared that the older version was omitted and only one version is being used. It was the reason I didn't doubt on the library versions conflict. But on debugging, I was convinced that the code was failing due to conflicting libs, and I had to explicitly make sure that only one lib version is there.


问:
Python: joining 2 lists of the same size
Let's say I have 2 following lists:

list1 = [1,1,1,1]
list2 = [3,3,3,3]

I want the result of join to be:

list3 [4,4,4,4]

What's would be the best way to do it?

答:
Extremely similar to Ignacio's answer, but for a tiny bit more brevity:

```<code>list3 = [sum(i) for i in zip(list1, list2)]
</code>```

or

```<code>list3 = map(sum, zip(list1, list2))
</code>```

I prefer the map version myself.

Edit: As JBernardo rightly points out, if using Python 2.x you should replace zip with its iterator counterpart in itertools.izip for efficiency, but zip uses iterators by default in Python 3.

ContentLicense: CC BY-SA 3.0

Body:
Extremely similar to Ignacio's answer, but for a tiny bit more brevity:

list3 = [sum(i) for i in zip(list1, list2)]

or

list3 = map(sum, zip(list1, list2))

I prefer the map version myself.

Edit: As JBernardo rightly points out, if using Python 2.x you should replace zip with its iterator counterpart in itertools.izip for efficiency, but zip uses iterators by default in Python 3.


问:
When I try to make a button show a different view controller using a segue it adds a black bar at the top
I am using the latest version on Xcode and am trying to connect a button to a new view controller using a segue. In my project I have other buttons that work and the view controller looks normal but when I attach it to this one by control clicking and dragging to another view controller it does this...

(There is a black space at the top rather than the usual full page)

I have also tried

```<code>presentedController.modalPresentationStyle = .fullScreen
</code>```

However this did not work for some reason.
I think a reason that it may not work is because the view controller is disconnected. I need to do this to connect 2 programmatically, how can I fix this?

答:
In your storyboard in segue options choose:
Kind: Present Modally
Presentation: Fullscreen</p>

Body:
I am using the latest version on Xcode and am trying to connect a button to a new view controller using a segue. In my project I have other buttons that work and the view controller looks normal but when I attach it to this one by control clicking and dragging to another view controller it does this...

(There is a black space at the top rather than the usual full page)

I have also tried

presentedController.modalPresentationStyle = .fullScreen

However this did not work for some reason.
I think a reason that it may not work is because the view controller is disconnected. I need to do this to connect 2 programmatically, how can I fix this?


问:
Why builtin function abs() don't work with Python lists, but works correctly with NumPy arrays and pandas series (as it would be vectorized)?
Why builtin function abs() don't work with Python lists, but work correctly with NumPy arrays and pandas series?

Applying built-in abs() function to Python list raises an exception

TypeError: bad operand type for abs(): 'list'

Nothing surprising, it's in concordance with documentation:

abs(x)

  Return the absolute value of a number. The argument may be an integer or a floating point number.
  If the argument is a complex number, its magnitude is returned.

But the same function behaves correctly (as a vectorized function) for NumPy arrays and pandas series:

```<code>In[2]: lst = [2, 0, -1]
In[3]: # abs(lst)             # bad operand type for abs(): 'list'
</code>```

```<code>In[4]: import numpy as np
In[5]: arr = np.array(lst)
In[6]: abs(arr)               # no problem
Out[6]: array([2, 0, 1])
</code>```

```<code>In[7]: import pandas as pd
In[8]: s = pd.Series(lst)
In[9]: abs(s)                 # no problem
Out[9]:
0    2
1    0
2    1
dtype: int64
</code>```

```<code>In[10]: abs.__class__
Out[10]: builtin_function_or_method
</code>```

How is it possible?

答:
The quoted documentation is obsolete.

The new documentation (for Python 3.8.3) states:

abs(x)

      Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned. If x defines __abs__(), abs(x) returns x.__abs__().

The last sentence is new, and it explains the question:

NumPy ndarray class and pandas Series class both define the magic __abs__() method.

Body:
Why builtin function abs() don't work with Python lists, but work correctly with NumPy arrays and pandas series?

Applying built-in abs() function to Python list raises an exception

TypeError: bad operand type for abs(): 'list'

Nothing surprising, it's in concordance with documentation:

abs(x)

  Return the absolute value of a number. The argument may be an integer or a floating point number.
  If the argument is a complex number, its magnitude is returned.

But the same function behaves correctly (as a vectorized function) for NumPy arrays and pandas series:

In[2]: lst = [2, 0, -1]
In[3]: # abs(lst)             # bad operand type for abs(): 'list'

In[4]: import numpy as np
In[5]: arr = np.array(lst)
In[6]: abs(arr)               # no problem
Out[6]: array([2, 0, 1])

In[7]: import pandas as pd
In[8]: s = pd.Series(lst)
In[9]: abs(s)                 # no problem
Out[9]:
0    2
1    0
2    1
dtype: int64

In[10]: abs.__class__
Out[10]: builtin_function_or_method

How is it possible?


问:
Get fiscal year based on current timestamp-python

I am trying get the start date of the financial year based on today's date.

So after a little research, I found this package called fiscalyear where you can modify the start date of the fiscal year. In my case i wanted 01-07-year to be the start date of my fiscal year so i set fiscalyear.START_MONTH = 7

I have tried the below(reproducible example if you pip install fiscalyear):

```<code>import datetime
import fiscalyear
fiscalyear.START_MONTH = 7
a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
a.strftime('%Y-%m-%d')
</code>```

Which outputs correctly:

```<code>'2018-07-01'
</code>```

However, this would not work when the month turns to August, since the datetime.datetime.now().year doesnot change. So i tried doing something like:

```<code>if (datetime.datetime.now()-pd.to_datetime('2018-07-01')).days < 365:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
    print(a.strftime('%Y-%m-%d'))
else:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year+1).start.date()
    print(a.strftime('%Y-%m-%d'))
</code>```

I have a bad feeling about what I am doing since this might now work for leap years too.

Is there some better way to do this in python which will detect the start date of the fiscal year based on current timestamp?

py version: 3.6.7

答:
You can try following code, It worked for me:</p>

```<code>>>> import fiscalyear
>>> fiscalyear.START_MONTH = 4
>>> fiscalyear.FiscalYear.current()
FiscalYear(2021)
>>>
</code>```

Body:
I am trying get the start date of the financial year based on today's date.

So after a little research, I found this package called fiscalyear where you can modify the start date of the fiscal year. In my case i wanted 01-07-year to be the start date of my fiscal year so i set fiscalyear.START_MONTH = 7

I have tried the below(reproducible example if you pip install fiscalyear):

import datetime
import fiscalyear
fiscalyear.START_MONTH = 7
a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
a.strftime('%Y-%m-%d')

Which outputs correctly:

'2018-07-01'

However, this would not work when the month turns to August, since the datetime.datetime.now().year doesnot change. So i tried doing something like:

if (datetime.datetime.now()-pd.to_datetime('2018-07-01')).days < 365:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year).start.date()
    print(a.strftime('%Y-%m-%d'))
else:
    a = fiscalyear.FiscalYear(datetime.datetime.now().year+1).start.date()
    print(a.strftime('%Y-%m-%d'))

I have a bad feeling about what I am doing since this might now work for leap years too.

Is there some better way to do this in python which will detect the start date of the fiscal year based on current timestamp?

py version: 3.6.7

Body:
You can try following code, It worked for me:

>>> import fiscalyear
>>> fiscalyear.START_MONTH = 4
>>> fiscalyear.FiscalYear.current()
FiscalYear(2021)
>>>


问:
Laravel path from Controller to a file
I am trying to implement payment by card in a laravel project. For this i neeed to make a link in Controller to a certificat file.
I put the file in public/files and i made a variable like this

$x509FilePath   = '/files/public.cer';
```

<p>When i'm trying to encrypt an object using this file i get the error </p>

```Error while loading X509 public key certificate! Reason:error:02001002:system library:fopen:No such file or directory
error:2006D080:BIO routines:BIO_new_file:no such file
error:02001002:system library:fopen:No such file or directory
error:2006D080:BIO routines:BIO_new_file:no such file
```

Can anyone help me? Thanks alot!

答:
I think you have to reference the file path using the helper public_path()

Try using:

```<code>$x509FilePath   = public_path('/files/public.cer');
</code>```

Title: Laravel path from Controller to a file

Body:
I am trying to implement payment by card in a laravel project. For this i neeed to make a link in Controller to a certificat file.
I put the file in public/files and i made a variable like this

$x509FilePath   = '/files/public.cer';

When i'm trying to encrypt an object using this file i get the error

Error while loading X509 public key certificate! Reason:error:02001002:system library:fopen:No such file or directory
error:2006D080:BIO routines:BIO_new_file:no such file
error:02001002:system library:fopen:No such file or directory
error:2006D080:BIO routines:BIO_new_file:no such file

Can anyone help me? Thanks alot!

Body:
I think you have to reference the file path using the helper public_path()

Try using:

$x509FilePath   = public_path('/files/public.cer');


问:
Override ToString() is not working in abstract class (.net-core 3.1)
When interpolating objects into strings (mainly for logging purposes), it needs to be explicitly serialized  otherwise what you get is:

```<code><ProjectName>.<Class>
</code>```

or in my case

```<code>ConsoleApp1.Program+Person
</code>```

So I made a very simple console application as a PoC to tackle this problem.

In this PoC I have an abstract base class that only overrides ToString method with JsonSerializer, so I do not need to serialize every time I want to log/ConsoleWrite my object.

```<code>    public abstract class BaseModel
    {
        public override string ToString()
        {
            return JsonSerializer.Serialize(this);
        }
    }
</code>```

This abstract class is supposed to be inherited by all my models. This is the whole console app

```<code>        static async Task Main(string[] args)
        {
            var a = new Person() { Name = "John", Lastname = "Doe" };
            Console.WriteLine($"Hi, {a}.");
            Console.ReadKey();
        }

        public class Person : BaseModel
        {
            public string Name { get; set; }
            public string Lastname { get; set; }
        }
</code>```

Running the code above ConsoleWrites

```<code>Hi, {}.
</code>```

Why is it empty?

When I put a Quickwatch on this in the abstract method I can see that the properties are populated properly.

Why does this happen?

答:
Change your serialization code to (assuming you are using System.Text.Json):

```<code>public abstract class BaseModel
{
    public override string ToString()
    {
        return JsonSerializer.Serialize(this, this.GetType());
    }
}
</code>```

You are using generic JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions) overload in your base class  so during compilation generic parameter TValue is subsitued with your BaseModel class, which has no properties, basically ending in JsonSerializer.Serialize<BaseModel>(this) call being performed.

Body:
When interpolating objects into strings (mainly for logging purposes), it needs to be explicitly serialized  otherwise what you get is:

<ProjectName>.<Class>

or in my case

ConsoleApp1.Program+Person

So I made a very simple console application as a PoC to tackle this problem.

In this PoC I have an abstract base class that only overrides ToString method with JsonSerializer, so I do not need to serialize every time I want to log/ConsoleWrite my object.

    public abstract class BaseModel
    {
        public override string ToString()
        {
            return JsonSerializer.Serialize(this);
        }
    }

This abstract class is supposed to be inherited by all my models. This is the whole console app

        static async Task Main(string[] args)
        {
            var a = new Person() { Name = "John", Lastname = "Doe" };
            Console.WriteLine($"Hi, {a}.");
            Console.ReadKey();
        }

        public class Person : BaseModel
        {
            public string Name { get; set; }
            public string Lastname { get; set; }
        }

Running the code above ConsoleWrites

Hi, {}.

Why is it empty?

When I put a Quickwatch on this in the abstract method I can see that the properties are populated properly.

Why does this happen?

Body:
Change your serialization code to (assuming you are using System.Text.Json):

public abstract class BaseModel
{
    public override string ToString()
    {
        return JsonSerializer.Serialize(this, this.GetType());
    }
}

You are using generic JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions) overload in your base class  so during compilation generic parameter TValue is subsitued with your BaseModel class, which has no properties, basically ending in JsonSerializer.Serialize<BaseModel>(this) call being performed.


问:
How to add to ObservableCollection with MVVM C#
I'm making a xamrin.forms application with tabbed pages containing some listviews. So I decided to try the MVVM approach, but I've never done that before. I have tried to learn from various online tutorials, and I get the concept, but there are some thing I'm missing apparently.

I want the user to be able to add to the list with the click of a button, but I just don't know how to do it.

The Model contains a class called ConnectedProjectors:

```<code>public class ConnectedProjectors
{
    public string ipaddress { get; set; }
    public string version { get; set; }
    public string swversion { get; set; }

    public Color activeStatus { get; set; }

    public override string ToString()
    {
        return ipaddress;
    }

}
</code>```

In ViewModel I have a 2 classes ProjectorViewModel which inherits from ViewModelBase:

```<code> public class ProjectorViewModel : ViewModelBase
{
    private ProjectorServices service;

    public ProjectorViewModel()
    {
        service = new ProjectorServices();
        ProjectorList = new ObservableCollection<ConnectedProjectors>();
        ProjectorList = service.GetProjectors("test", "test", "test", Color.White); //Works as expected
    }

    public void AddProjector(string ip, string ver, string sw, Color color)
    {
        ProjectorList = service.GetProjectors(ip, ver, sw, color); //I expected this to add to the list
    }

    private ObservableCollection<ConnectedProjectors> connectedProjectors;
    public ObservableCollection<ConnectedProjectors> ProjectorList
    {
        get { return connectedProjectors; }
        set { SetProperty(ref connectedProjectors, value); } // Maybe the NotifyEvent doesn't work as expected?
    }

}

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value,
        [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

plus the ProjectorServices class:

```<code> class ProjectorServices
{
    public ProjectorServices()
    {

    }

    public ObservableCollection<ConnectedProjectors> GetProjectors(string ipad, string ver, string sw, Color color)
    {
        var list = new ObservableCollection<ConnectedProjectors>
        {
            new ConnectedProjectors
            {
                ipaddress = ipad,
                version = ver,
                swversion = sw,
                activeStatus = color
            }
        };

        return list;
    }
}
</code>```

and finally the MainPage class:

```<code>   public partial class MainPage : ContentPage
{
    public ConnectedProjectors projectors;
    private ProjectorViewModel projvm = new ProjectorViewModel();
    public MainPage()
    {
        InitializeComponent();

        this.BindingContext = new ProjectorViewModel();
    }
     public void AddProj(object sender,EventArgs e)
    {
        string ip = txt.Text;  // text input in editor in MainView view.
        string pn = "Not Found";
        string sw = "Not Found";
        Color col = Color.Chocolate;

        try
        {
            pn = GetPartNr(ip); // Sends an ascii command to see if the ipaddress returns an expected result
            sw = GetSWVersion(ip);
            col = GetActiveStatus(ip);
        }

        finally
        {
            projvm.AddProjector(ip, pn, sw, col);
        }
    }
}
</code>```

The result of the code as it is now, is that the command in ProjectorViewModel() method adds to the Observable collection as the application initializes as expected. But in the method AddProjector() that I wrote just below, the same command does not add a new item to the collection (At least not visible in listview).

in XAML I have listview ItemSource bound to ProjectorList, and the listview shows the test item, but when I click the button that fires the AddProj()Method, nothing happens.

I expect that the issue is one of two things:

The way I try to add to collection is not correct

The PropertyChanged doesn't work as expected

I was hoping someone could help me with this. Any help would be very much appreciated.

答:
You are correct in what the issue is. Your MainPage has its BindingContext set to a new instance of ProjectorViewModel.

this.BindingContext = new ProjectorViewModel();
```

<p>However, <code>AddProj</code> method adds the new ViewModel to <code>projvm</code>, which is just a private field, sitting there. It has no connection whatsoever to the page and its binding. A better approach is to expose your BindingContext's ViewModel in a property and use it.</p>

<pre class="lang-cs prettyprint-override"><code>public ProjectorViewModel ViewModel
{
    get => this.BindingContext as ProjectorViewModel;
    set => this.BindingContext = value;
}
</code>```

And then you can set your BindingContext like this:

public HomePage()
{
    InitializeComponent();

    this.ViewModel = new ProjectorViewModel();
}
```

<p>This way we have set up again our context, but this time we have access to it. Now, you can add your new ViewModel like this:</p>

<pre class="lang-cs prettyprint-override"><code>this.ViewModel.AddProjector(ip, pn, sw, col);
</code>```

Now you will be using the same instance, that your page has been bound to.

Body:
I'm making a xamrin.forms application with tabbed pages containing some listviews. So I decided to try the MVVM approach, but I've never done that before. I have tried to learn from various online tutorials, and I get the concept, but there are some thing I'm missing apparently.

I want the user to be able to add to the list with the click of a button, but I just don't know how to do it.

The Model contains a class called ConnectedProjectors:

public class ConnectedProjectors
{
    public string ipaddress { get; set; }
    public string version { get; set; }
    public string swversion { get; set; }

    public Color activeStatus { get; set; }

    public override string ToString()
    {
        return ipaddress;
    }

}

In ViewModel I have a 2 classes ProjectorViewModel which inherits from ViewModelBase:

 public class ProjectorViewModel : ViewModelBase
{
    private ProjectorServices service;

    public ProjectorViewModel()
    {
        service = new ProjectorServices();
        ProjectorList = new ObservableCollection<ConnectedProjectors>();
        ProjectorList = service.GetProjectors("test", "test", "test", Color.White); //Works as expected
    }

    public void AddProjector(string ip, string ver, string sw, Color color)
    {
        ProjectorList = service.GetProjectors(ip, ver, sw, color); //I expected this to add to the list
    }

    private ObservableCollection<ConnectedProjectors> connectedProjectors;
    public ObservableCollection<ConnectedProjectors> ProjectorList
    {
        get { return connectedProjectors; }
        set { SetProperty(ref connectedProjectors, value); } // Maybe the NotifyEvent doesn't work as expected?
    }

}

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value,
        [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

plus the ProjectorServices class:

 class ProjectorServices
{
    public ProjectorServices()
    {

    }

    public ObservableCollection<ConnectedProjectors> GetProjectors(string ipad, string ver, string sw, Color color)
    {
        var list = new ObservableCollection<ConnectedProjectors>
        {
            new ConnectedProjectors
            {
                ipaddress = ipad,
                version = ver,
                swversion = sw,
                activeStatus = color
            }
        };

        return list;
    }
}

and finally the MainPage class:

   public partial class MainPage : ContentPage
{
    public ConnectedProjectors projectors;
    private ProjectorViewModel projvm = new ProjectorViewModel();
    public MainPage()
    {
        InitializeComponent();

        this.BindingContext = new ProjectorViewModel();
    }
     public void AddProj(object sender,EventArgs e)
    {
        string ip = txt.Text;  // text input in editor in MainView view.
        string pn = "Not Found";
        string sw = "Not Found";
        Color col = Color.Chocolate;

        try
        {
            pn = GetPartNr(ip); // Sends an ascii command to see if the ipaddress returns an expected result
            sw = GetSWVersion(ip);
            col = GetActiveStatus(ip);
        }

        finally
        {
            projvm.AddProjector(ip, pn, sw, col);
        }
    }
}

The result of the code as it is now, is that the command in ProjectorViewModel() method adds to the Observable collection as the application initializes as expected. But in the method AddProjector() that I wrote just below, the same command does not add a new item to the collection (At least not visible in listview).

in XAML I have listview ItemSource bound to ProjectorList, and the listview shows the test item, but when I click the button that fires the AddProj()Method, nothing happens.

I expect that the issue is one of two things:

The way I try to add to collection is not correct

The PropertyChanged doesn't work as expected

I was hoping someone could help me with this. Any help would be very much appreciated.

Body:
You are correct in what the issue is. Your MainPage has its BindingContext set to a new instance of ProjectorViewModel.

this.BindingContext = new ProjectorViewModel();

However, AddProj method adds the new ViewModel to projvm, which is just a private field, sitting there. It has no connection whatsoever to the page and its binding. A better approach is to expose your BindingContext's ViewModel in a property and use it.

public ProjectorViewModel ViewModel
{
    get => this.BindingContext as ProjectorViewModel;
    set => this.BindingContext = value;
}

And then you can set your BindingContext like this:

public HomePage()
{
    InitializeComponent();

    this.ViewModel = new ProjectorViewModel();
}

This way we have set up again our context, but this time we have access to it. Now, you can add your new ViewModel like this:

this.ViewModel.AddProjector(ip, pn, sw, col);

Now you will be using the same instance, that your page has been bound to.


问:
Reverse a get_dummies encoding in pandas
Column names are: ID,1,2,3,4,5,6,7,8,9.

The col values are either 0 or 1

My dataframe looks like this:

```<code> ID     1    2    3    4    5    6   7   8   9

1002    0    1    0    1    0    0   0   0   0
1003    0    0    0    0    0    0   0   0   0
1004    1    1    0    0    0    0   0   0   0
1005    0    0    0    0    1    0   0   0   0
1006    0    0    0    0    0    1   0   0   0
1007    1    0    1    0    0    0   0   0   0
1000    0    0    0    0    0    0   0   0   0
1009    0    0    1    0    0    0   1   0   0
</code>```

I want the column names in front of the ID where the value in a row is 1.

The Dataframe i want should look like this:

```<code> ID      Col2
1002       2    // has 1 at Col(2) and Col(4)
1002       4
1004       1    // has 1 at col(1) and col(2)
1004       2
1005       5    // has 1 at col(5)
1006       6    // has 1 at col(6)
1007       1    // has 1 at col(1) and col(3)
1007       3
1009       3    // has 1 at col(3) and col(7)
1009       7
</code>```

Please help me in this, Thanks in advance

答:
Several great answers for the OP post. However, often get_dummies is used for multiple categorical features. Pandas uses a prefix separator prefix_sep to distinguish different values for a column.

The following function collapses a "dummified" dataframe while keeping the order of columns:

def undummify(df, prefix_sep="_"):
    cols2collapse = {
        item.split(prefix_sep)[0]: (prefix_sep in item) for item in df.columns
    }
    series_list = []
    for col, needs_to_collapse in cols2collapse.items():
        if needs_to_collapse:
            undummified = (
                df.filter(like=col)
                .idxmax(axis=1)
                .apply(lambda x: x.split(prefix_sep, maxsplit=1)[1])
                .rename(col)
            )
            series_list.append(undummified)
        else:
            series_list.append(df[col])
    undummified_df = pd.concat(series_list, axis=1)
    return undummified_df

```

<h3>Example</h3>

```>>> df
     a    b    c
0  A_1  B_1  C_1
1  A_2  B_2  C_2
>>> df2 = pd.get_dummies(df)
>>> df2
   a_A_1  a_A_2  b_B_1  b_B_2  c_C_1  c_C_2
0      1      0      1      0      1      0
1      0      1      0      1      0      1
>>> df3 = undummify(df2)
>>> df3
     a    b    c
0  A_1  B_1  C_1
1  A_2  B_2  C_2
```

Body:
Column names are: ID,1,2,3,4,5,6,7,8,9.

The col values are either 0 or 1

My dataframe looks like this:

 ID     1    2    3    4    5    6   7   8   9

1002    0    1    0    1    0    0   0   0   0
1003    0    0    0    0    0    0   0   0   0
1004    1    1    0    0    0    0   0   0   0
1005    0    0    0    0    1    0   0   0   0
1006    0    0    0    0    0    1   0   0   0
1007    1    0    1    0    0    0   0   0   0
1000    0    0    0    0    0    0   0   0   0
1009    0    0    1    0    0    0   1   0   0

I want the column names in front of the ID where the value in a row is 1.

The Dataframe i want should look like this:

 ID      Col2
1002       2    // has 1 at Col(2) and Col(4)
1002       4
1004       1    // has 1 at col(1) and col(2)
1004       2
1005       5    // has 1 at col(5)
1006       6    // has 1 at col(6)
1007       1    // has 1 at col(1) and col(3)
1007       3
1009       3    // has 1 at col(3) and col(7)
1009       7

Please help me in this, Thanks in advance

Body:
Several great answers for the OP post. However, often get_dummies is used for multiple categorical features. Pandas uses a prefix separator prefix_sep to distinguish different values for a column.

The following function collapses a "dummified" dataframe while keeping the order of columns:

def undummify(df, prefix_sep="_"):
    cols2collapse = {
        item.split(prefix_sep)[0]: (prefix_sep in item) for item in df.columns
    }
    series_list = []
    for col, needs_to_collapse in cols2collapse.items():
        if needs_to_collapse:
            undummified = (
                df.filter(like=col)
                .idxmax(axis=1)
                .apply(lambda x: x.split(prefix_sep, maxsplit=1)[1])
                .rename(col)
            )
            series_list.append(undummified)
        else:
            series_list.append(df[col])
    undummified_df = pd.concat(series_list, axis=1)
    return undummified_df

Example

>>> df
     a    b    c
0  A_1  B_1  C_1
1  A_2  B_2  C_2
>>> df2 = pd.get_dummies(df)
>>> df2
   a_A_1  a_A_2  b_B_1  b_B_2  c_C_1  c_C_2
0      1      0      1      0      1      0
1      0      1      0      1      0      1
>>> df3 = undummify(df2)
>>> df3
     a    b    c
0  A_1  B_1  C_1
1  A_2  B_2  C_2


问:
Do I need a server to send PDFs created in my app to the same app (different account) on another device?
Beginner here.

I'm creating an app in Android Studio (Java) where the user can create and store PDFs on the app and send these to another account on the same app, on a different device.

The user will have a list of contacts stored in a database.

Do I need a server to do this? Are there any tutorials online showing one how to code this? (I've been searching for hours but can't find anything specific to my problem. Maybe I'm wording it wrong...)

I was looking into Firebase but I'm completely lost on where to start.

Thanks!

答:
For simple use cases you don't need a server, you can use firebase instead. Currently, they have a storage feature that lets you store files on their servers and retrieve them later.

Here is the official documentation firebase cloud storage

One thing you could do is upload the file from android device and download from another one.


问:
Flutter - show android homescreen widget in the app
Is it possible somehow to display Android homescreen widget as a Flutter widget?

I've read about PlatformView widget that can embed any Android view inside Flutter app. How is it possible to do the same with homescreen widgets?

答:
I found a github project which is only for android in flutter but
  initially has  much to solve the problem
   This flutter_home_screen_widget_example
  github repo

Also found a similar github issue26134 requesting for the same

Got two more related stackoverflow questions

questions/44120149/android-lock-screen-widget-in-flutter

questions/47870740/flutter-is-it-somehow-possible-to-create-app-widgets-android-and-today-extens#47887388


问:
Ant XSLT task with fileset running out of memory/not freeing up memory
I have a big (1.9 GB) XML file which has data I want to insert into a MySQL database every month. I have made an Ant script for this.

The Ant XSLT task can't handle one file this big, so I have a task that uses xml_split (from xml-twig-tools) to split the 1.9 GB xml file into smaller xml files of roughly 4 MB.

This all goes well.

I use the following Ant xml to run the XSLT task over all these XML files:

```<code>    <target name="xsltransform" depends="split" description="Transform XML to SQL...">
            <xslt basedir="${import.dir}/"
                  destdir="${import.dir}/sql/"
                  style="${xsl.filename}" force="true">
                    <mapper type="glob" from="*.xml" to="*.sql" />
                    <factory name="net.sf.saxon.TransformerFactoryImpl"/>
            </xslt>
    </target>
</code>```

The problem is, as soon as it starts on the first XML file, I see the 'RES' memory in linux top growing with every next XML file. As it is processing multiple (unrelated) xml files, I would suspect it would free up memory in between the translation of each xml file. Well, it doesn't... after two-hundred 4MB xml files, java throws an out-of-memory exception:

```<code>BUILD FAILED
/var/lib/hudson/jobs/EPDB_Rebuild_Monthly/workspace/trunk/buildfiles/buildMonthly.xml:67: java.lang.OutOfMemoryError: Java heap space
at net.sf.saxon.tinytree.TinyTree.ensureNodeCapacity(Unknown Source)
at net.sf.saxon.tinytree.TinyTree.addNode(Unknown Source)
at net.sf.saxon.tinytree.TinyBuilder.startElement(Unknown Source)
at net.sf.saxon.event.Stripper.startElement(Unknown Source)
at net.sf.saxon.event.ReceivingContentHandler.startElement(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Unknown Source)
at net.sf.saxon.event.Sender.send(Unknown Source)
at net.sf.saxon.event.Sender.send(Unknown Source)
at net.sf.saxon.Controller.transform(Unknown Source)
at org.apache.tools.ant.taskdefs.optional.TraXLiaison.transform(TraXLiaison.java:194)
at org.apache.tools.ant.taskdefs.XSLTProcess.process(XSLTProcess.java:812)
at org.apache.tools.ant.taskdefs.XSLTProcess.execute(XSLTProcess.java:408)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:390)
at org.apache.tools.ant.Target.performTasks(Target.java:411)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1360)
at org.apache.tools.ant.Project.executeTarget(Project.java:1329)
</code>```

Is there something I can do to prevent the XSLT task eating up all my memory?
Or should I reconsider my approach?

答:
We are all going to agree that it should be letting go of the memory, but since it doesn't, you can try breaking up the xslt task in to seperate calls. e.g., using Ant Contrib's for task

```<code><for param="file">
    <fileset dir="${import.dir}"/>
    <sequential>
        <xslt in="@{file}"
              destdir="${import.dir}/sql/"
              style="${xsl.filename}" force="true">
                <mapper type="glob" from="*.xml" to="*.sql" />
                <factory name="net.sf.saxon.TransformerFactoryImpl"/>
        </xslt>
    </sequential>
</for>
</code>```

If that doesn't do the trick, then since you are using Saxon, you can calling Saxon's java classes directly in a forked JVM. e.g.,

```<code><java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:${import.dir}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql" />
</java>
</code>```

or you can try both

```<code><for param="file">
    <fileset dir="${import.dir}"/>
    <sequential>
        <basename property="@{file}.base" file="@{file}" suffix="xml"/>
        <java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:@{file}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql/${@{file}.base}.sql" />
        </java>
    </sequential>
</for>
</code>```

and for bonus points you could try to speed things up a bit by doing it in parallel.

```<code><for param="file">
    <fileset dir="${import.dir}"/>
    <parallel>
        <basename property="@{file}.base" file="@{file}" suffix="xml"/>
        <java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:@{file}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql/${@{file}.base}.sql" />
        </java>
    </parallel>
</for>
</code>```

Body:
I have a big (1.9 GB) XML file which has data I want to insert into a MySQL database every month. I have made an Ant script for this.

The Ant XSLT task can't handle one file this big, so I have a task that uses xml_split (from xml-twig-tools) to split the 1.9 GB xml file into smaller xml files of roughly 4 MB.

This all goes well.

I use the following Ant xml to run the XSLT task over all these XML files:

    <target name="xsltransform" depends="split" description="Transform XML to SQL...">
            <xslt basedir="${import.dir}/"
                  destdir="${import.dir}/sql/"
                  style="${xsl.filename}" force="true">
                    <mapper type="glob" from="*.xml" to="*.sql" />
                    <factory name="net.sf.saxon.TransformerFactoryImpl"/>
            </xslt>
    </target>

The problem is, as soon as it starts on the first XML file, I see the 'RES' memory in linux top growing with every next XML file. As it is processing multiple (unrelated) xml files, I would suspect it would free up memory in between the translation of each xml file. Well, it doesn't... after two-hundred 4MB xml files, java throws an out-of-memory exception:

BUILD FAILED
/var/lib/hudson/jobs/EPDB_Rebuild_Monthly/workspace/trunk/buildfiles/buildMonthly.xml:67: java.lang.OutOfMemoryError: Java heap space
at net.sf.saxon.tinytree.TinyTree.ensureNodeCapacity(Unknown Source)
at net.sf.saxon.tinytree.TinyTree.addNode(Unknown Source)
at net.sf.saxon.tinytree.TinyBuilder.startElement(Unknown Source)
at net.sf.saxon.event.Stripper.startElement(Unknown Source)
at net.sf.saxon.event.ReceivingContentHandler.startElement(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Unknown Source)
at net.sf.saxon.event.Sender.send(Unknown Source)
at net.sf.saxon.event.Sender.send(Unknown Source)
at net.sf.saxon.Controller.transform(Unknown Source)
at org.apache.tools.ant.taskdefs.optional.TraXLiaison.transform(TraXLiaison.java:194)
at org.apache.tools.ant.taskdefs.XSLTProcess.process(XSLTProcess.java:812)
at org.apache.tools.ant.taskdefs.XSLTProcess.execute(XSLTProcess.java:408)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:390)
at org.apache.tools.ant.Target.performTasks(Target.java:411)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1360)
at org.apache.tools.ant.Project.executeTarget(Project.java:1329)

Is there something I can do to prevent the XSLT task eating up all my memory?
Or should I reconsider my approach?

Body:
We are all going to agree that it should be letting go of the memory, but since it doesn't, you can try breaking up the xslt task in to seperate calls. e.g., using Ant Contrib's for task

<for param="file">
    <fileset dir="${import.dir}"/>
    <sequential>
        <xslt in="@{file}"
              destdir="${import.dir}/sql/"
              style="${xsl.filename}" force="true">
                <mapper type="glob" from="*.xml" to="*.sql" />
                <factory name="net.sf.saxon.TransformerFactoryImpl"/>
        </xslt>
    </sequential>
</for>

If that doesn't do the trick, then since you are using Saxon, you can calling Saxon's java classes directly in a forked JVM. e.g.,

<java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:${import.dir}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql" />
</java>

or you can try both

<for param="file">
    <fileset dir="${import.dir}"/>
    <sequential>
        <basename property="@{file}.base" file="@{file}" suffix="xml"/>
        <java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:@{file}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql/${@{file}.base}.sql" />
        </java>
    </sequential>
</for>

and for bonus points you could try to speed things up a bit by doing it in parallel.

<for param="file">
    <fileset dir="${import.dir}"/>
    <parallel>
        <basename property="@{file}.base" file="@{file}" suffix="xml"/>
        <java classname="net.sf.saxon.Transform" failonerror="true" fork="true">
                <arg value="-s:@{file}" />
                <arg value="-xsl:${xsl.filename}" />
                <arg value="-o:${import.dir}/sql/${@{file}.base}.sql" />
        </java>
    </parallel>
</for>


问:
Unable to display page content accross the entire screen available by using Nebular NbLayoutComponent
I'm using Neular NbLayoutComponent with one column as a main container for an Angular Application as shown below.

```<code><nb-layout windowMode>
 <nb-layout-header fixed ></nb-layout-header>
 <nb-sidebar tag="sidebar" responsive start></nb-sidebar>
 <nb-layout-column>
    Page content here
 </nb-layout-column>
 <nb-layout-footer fixed></nb-layout-footer>
</nb-layout>
</code>```

The content of the tag <nb-layout-column> </nb-layout-column> is not displayed across the entire page width. Even by assigning a width of 100% to the content placed in <nb-layout-column> </nb-layout-column> nothing happens. There is a margin that remains on the right side.

How can I fix this problem?

答:
I solved my problem after read Nebular doc. Before, I assigned a value in percentage to layout column width for responsive behavior. Unfortunately nothing happened. By using a width value in pixel, the page content is displayed across entire available screen proportionally.

Then I implemented a HostListener for resize window event to track screen width change as shown below:

```<code>@HostListener('window:resize') onWindowResize() {
  this.innerWidth = this.getInnerWidth() – 50;
}

getInnerWidth(): number {
  let result = 0;

  if (isPlatformBrowser(this._platformId)) {
    result = window.innerWidth;
  }

  return result;
}
</code>```

The width of layout column is assigned like this:

```<code><nb-layout-column [style.width.px]="innerWidth">
   <router-outlet></router-outlet>
</nb-layout-column>
</code>```

The layout column is adjusted when window is resized. This works normally.

I hope this is can help someone.

Body:
I'm using Neular NbLayoutComponent with one column as a main container for an Angular Application as shown below.

<nb-layout windowMode>
 <nb-layout-header fixed ></nb-layout-header>
 <nb-sidebar tag="sidebar" responsive start></nb-sidebar>
 <nb-layout-column>
    Page content here
 </nb-layout-column>
 <nb-layout-footer fixed></nb-layout-footer>
</nb-layout>

The content of the tag <nb-layout-column> </nb-layout-column> is not displayed across the entire page width. Even by assigning a width of 100% to the content placed in <nb-layout-column> </nb-layout-column> nothing happens. There is a margin that remains on the right side.

How can I fix this problem?

Body:
I solved my problem after read Nebular doc. Before, I assigned a value in percentage to layout column width for responsive behavior. Unfortunately nothing happened. By using a width value in pixel, the page content is displayed across entire available screen proportionally.

Then I implemented a HostListener for resize window event to track screen width change as shown below:

@HostListener('window:resize') onWindowResize() {
  this.innerWidth = this.getInnerWidth() – 50;
}

getInnerWidth(): number {
  let result = 0;

  if (isPlatformBrowser(this._platformId)) {
    result = window.innerWidth;
  }

  return result;
}

The width of layout column is assigned like this:

<nb-layout-column [style.width.px]="innerWidth">
   <router-outlet></router-outlet>
</nb-layout-column>

The layout column is adjusted when window is resized. This works normally.

I hope this is can help someone.


答:
The .NET Core json serializer method you used is generic, like this:

```<code>public static string Serialize<TValue> (TValue value,
    System.Text.Json.JsonSerializerOptions options = default);
</code>```

By design, it only considers the properties in TValue when it serializes, and since you called it from your abstract class, with this, which of course will then be of the abstract class type, it only considers properties in the abstract class.

Basically your call is inferred to be

```<code>return JsonSerializer.Serialize<BaseModel>(this);
</code>```

Fortunately, it is easy to fix, simply switch to calling the non-generic method:

```<code>return JsonSerializer.Serialize(this, GetType());
</code>```

Now it uses runtime information about which type you're actually calling it about instead of the abstract class, and should correctly serialize properties from your descendant type.

Title: Override ToString() is not working in abstract class (.net-core 3.1)

Body:
The .NET Core json serializer method you used is generic, like this:

public static string Serialize<TValue> (TValue value,
    System.Text.Json.JsonSerializerOptions options = default);

By design, it only considers the properties in TValue when it serializes, and since you called it from your abstract class, with this, which of course will then be of the abstract class type, it only considers properties in the abstract class.

Basically your call is inferred to be

return JsonSerializer.Serialize<BaseModel>(this);

Fortunately, it is easy to fix, simply switch to calling the non-generic method:

return JsonSerializer.Serialize(this, GetType());

Now it uses runtime information about which type you're actually calling it about instead of the abstract class, and should correctly serialize properties from your descendant type.


问:
Sentiment analysis of a certain paragraph from a website
I have url of multiple websites in an xlsx file. I ran a loop on the xlsx file and passed the urls as an argument to the following sentiment analysis code.
Now the code is providing me with the analysis of the whole website (the websites only contain text and numbers) but the problem is that I want to run the analysis only on the paragraph that starts with "Managerial function". How may I do the same?
Here's my code:</p>

```<code>article = Article(j)
article.download()
article.parse()
#nltk.download('punkt')
article.nlp()
text = article.summary
obj = TextBlob(text)
sentiment = obj.sentiment.polarity
print(round(sentiment,2))
if sentiment==0:
    print("neutral")
elif sentiment>0:
    print("positive")
elif sentiment<0:
    print("negative")
</code>```

答:
Using regex, something like the below would match a paragraph starting with "Managerial function":

```<code>found=re.search(r'^(Managerial function.*\s)', full_text, re.MULTILINE)
my_paragraph=found.group(0)
</code>```

, where full_text is your whole article text.

Remember to add this import first:

```<code>import re
</code>```

Body:
I have url of multiple websites in an xlsx file. I ran a loop on the xlsx file and passed the urls as an argument to the following sentiment analysis code.
Now the code is providing me with the analysis of the whole website (the websites only contain text and numbers) but the problem is that I want to run the analysis only on the paragraph that starts with "Managerial function". How may I do the same?
Here's my code:

article = Article(j)
article.download()
article.parse()
#nltk.download('punkt')
article.nlp()
text = article.summary
obj = TextBlob(text)
sentiment = obj.sentiment.polarity
print(round(sentiment,2))
if sentiment==0:
    print("neutral")
elif sentiment>0:
    print("positive")
elif sentiment<0:
    print("negative")

Body:
Using regex, something like the below would match a paragraph starting with "Managerial function":

found=re.search(r'^(Managerial function.*\s)', full_text, re.MULTILINE)
my_paragraph=found.group(0)

, where full_text is your whole article text.

Remember to add this import first:

import re


问:
Assigning a value to merged cells in Apple Numbers using AppleScript
As part of a longer AppleScript, I'm copying strings from a list variable into ranges of merged cells in a Numbers 10.0 table.  E.g., if the list is called form_filler and the first range of merged cells is B6:Y7, I first tried:

```<code>set value of cell "B6" to item 1 of form_filler
</code>```

I thought one addresses merged cells by the top-left cell.  But this does something unexpected: it places the string only into cell "B6" and changes the range of merged cells to C6:Y7, excluding the cell I just pasted into.  This behavior occurs consistently with different merged cells throughout the table.  I then tried:

```<code>set value of range "B6:Y7" to item 1 of form_filler
</code>```

but this returned an error; I can't assign a value to the range.

I'm new to AppleScript, but not programming generally (e.g., Python).  What am I missing?  Thanks.

答:
It looks like you have to re-merge those cells. Here's code I just tested using my own tell block structure; you should be able to extrapolate from this (if you include your tell block structure I'll edit my code):

```<code>tell application "Numbers"
    set d to sheet 1 of document 1
    tell d
        set value of cell "B6" of table 1 of it to "test"
        merge range "B6:Y7" of table 1 of it
    end tell
end tell
</code>```

Not sure if this qualifies as a "work-around", but it seems to work, hopefully w/o introducing other issues.

Body:
As part of a longer AppleScript, I'm copying strings from a list variable into ranges of merged cells in a Numbers 10.0 table.  E.g., if the list is called form_filler and the first range of merged cells is B6:Y7, I first tried:

set value of cell "B6" to item 1 of form_filler

I thought one addresses merged cells by the top-left cell.  But this does something unexpected: it places the string only into cell "B6" and changes the range of merged cells to C6:Y7, excluding the cell I just pasted into.  This behavior occurs consistently with different merged cells throughout the table.  I then tried:

set value of range "B6:Y7" to item 1 of form_filler

but this returned an error; I can't assign a value to the range.

I'm new to AppleScript, but not programming generally (e.g., Python).  What am I missing?  Thanks.

Body:
It looks like you have to re-merge those cells. Here's code I just tested using my own tell block structure; you should be able to extrapolate from this (if you include your tell block structure I'll edit my code):

tell application "Numbers"
    set d to sheet 1 of document 1
    tell d
        set value of cell "B6" of table 1 of it to "test"
        merge range "B6:Y7" of table 1 of it
    end tell
end tell

Not sure if this qualifies as a "work-around", but it seems to work, hopefully w/o introducing other issues.


问:
How can I access Microsoft Graph's isOnlineMeeting property?
I am using the Microsoft graph event library in C# but intelisense does not list the property isOnlineMeeting as shown on https://learn.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0

Using the graph explorer I can see that isOnlineMeeting is in the response but not through the Microsoft.Graph.Event library in C#

How would I go about accessing this property?

Here is how I am trying to access the event information:

```<code>private static Booking GetBookingInfo(Event ev)
{
    var Id = ev.Id,
    var Start = Booking.ParseDateTime(ev.Start.DateTime),
    var Meeting = ev.IsOnlineMeeting;
</code>```

答:
Are you using this library: https://github.com/microsoftgraph/msgraph-sdk-dotnet?

If yes, what version are you using?

IsOnlineMeeting is a newer property added to MS Graph API in April 2020. That means that you might need to update the library to a newer version. For me, IsOnlineMeeting property is available in the newest version (3.6.0).

Body:
I am using the Microsoft graph event library in C# but intelisense does not list the property isOnlineMeeting as shown on https://learn.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0

Using the graph explorer I can see that isOnlineMeeting is in the response but not through the Microsoft.Graph.Event library in C#

How would I go about accessing this property?

Here is how I am trying to access the event information:

private static Booking GetBookingInfo(Event ev)
{
    var Id = ev.Id,
    var Start = Booking.ParseDateTime(ev.Start.DateTime),
    var Meeting = ev.IsOnlineMeeting;


问:
page.$eval('#search', el => el[id].value) working only on selected "id" element
Looking at puppeteer documentation I found that page.$eval(selector) runs document.querySelector(selector) within my page :
https://github.com/puppeteer/puppeteer/blob/v3.1.0/docs/api.md#pageevalselector-pagefunction-args

I am trying to select an option from a dropdown at a certain index position that I am able to get. To find what to do I am using chrome console and wrote the following code that works fine :

```<code>document.querySelector("select#ReportViewerControl_ctl04_ctl03_ddValue")[id_ed].value
</code>```

My problem is that when I go to my js file and write the same thing using page.$eval(selector) it does work only for the selected option :

```<code>const dropdowns_V3 = await page.$eval("select#ReportViewerControl_ctl04_ctl03_ddValue", all => all[id_ed].value);
</code>```

For information my dropdown options looks like that and only the selected one got the selected attribute :

```<code><option selected="selected" value="f31211ab-3126-46b3-bd8d-87ce0c262348"><Select a Value></option>

<option value="1000000430">Perimetre 1</option>
</code>```

答:
Since you're selecting an option with an specific id, it will behave exactly how it is behaving.
You can, by the way, use the

const value = await page.evaluate(() => {
  innerValue = document.querySelector('your selector here').value;

  return innerValue;
});
```

EDIT: Whenever you're dealing with the dom content itself, such as getting the innerText of a tag or the value of a selector, and not performing actions, like typing or clicking, preferably use the evaluate method because it has better perfomance and it's easier to get exactly what you want in the browser content.

Using the $, $$, $eval, $$eval, etc., will return a complex object and to get what you want you will need to treat it on the node context.

-

EDIT 2: If by any other reason you prefer to use the $, $$, $eval or $$eval methods, have in mind that the single $ performs a querySelector() action and the double $ performs a querySelectorAll(). The querySelector only returns the first element that matches your selector, while the querySelectorAll will return all the elements that match your selector. With that said, when you use $ an $eval, you must not use the array index notation, since there's only one element returned

Body:
Looking at puppeteer documentation I found that page.$eval(selector) runs document.querySelector(selector) within my page :
https://github.com/puppeteer/puppeteer/blob/v3.1.0/docs/api.md#pageevalselector-pagefunction-args

I am trying to select an option from a dropdown at a certain index position that I am able to get. To find what to do I am using chrome console and wrote the following code that works fine :

document.querySelector("select#ReportViewerControl_ctl04_ctl03_ddValue")[id_ed].value

My problem is that when I go to my js file and write the same thing using page.$eval(selector) it does work only for the selected option :

const dropdowns_V3 = await page.$eval("select#ReportViewerControl_ctl04_ctl03_ddValue", all => all[id_ed].value);

For information my dropdown options looks like that and only the selected one got the selected attribute :

<option selected="selected" value="f31211ab-3126-46b3-bd8d-87ce0c262348"><Select a Value></option>

<option value="1000000430">Perimetre 1</option>

Body:
Since you're selecting an option with an specific id, it will behave exactly how it is behaving.
You can, by the way, use the

const value = await page.evaluate(() => {
  innerValue = document.querySelector('your selector here').value;

  return innerValue;
});

EDIT: Whenever you're dealing with the dom content itself, such as getting the innerText of a tag or the value of a selector, and not performing actions, like typing or clicking, preferably use the evaluate method because it has better perfomance and it's easier to get exactly what you want in the browser content.

Using the $, $$, $eval, $$eval, etc., will return a complex object and to get what you want you will need to treat it on the node context.

-

EDIT 2: If by any other reason you prefer to use the $, $$, $eval or $$eval methods, have in mind that the single $ performs a querySelector() action and the double $ performs a querySelectorAll(). The querySelector only returns the first element that matches your selector, while the querySelectorAll will return all the elements that match your selector. With that said, when you use $ an $eval, you must not use the array index notation, since there's only one element returned


问:
Apollo, optimistic creation, and redirection
I am facing some troubles with my GraphQL optimistic rendering. I'm using Apollo Client, such as:

```<code>const history = useHistory();
const [addItem] = useMutation(ADD_ITEM_QUERY);

const onClick = () => {
    addItem({
        variables: {
            id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
            name: 'Foo Bar'
        },
        optimisticResponse: {
            addItem {
                id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
                name: 'Foo Bar',
                __typename: 'Item'
            }
        },
        update: () => {
            // Update item cached queries

            history.push(`/items);
        }
    });
};
</code>```

The issue comes from the redirect. As far as I understand it, the update function is called twice: a first time with the optimisticResponse, and a second time with the network response (which should normally be the same).

However, let's consider the following scenario:

I create a new item,

I receive the optimistic response, and I'm redirected to the list of items,

I click on "Add an item" to be redirected to the form

I receive the server response, hence I'm redirected again to the list.

What is the correct way to prevent this double redirection?

I thought checking the current cache value. If the value is already the latest one, I won't apply the redirect. Not sure if there is a better way? How do you proceed such a scenario?

答:
You should call history.push outside of the update function. You can do </p>

```<code>addItem({...}).then(() => history.push('/items')).
</code>```

Body:
I am facing some troubles with my GraphQL optimistic rendering. I'm using Apollo Client, such as:

const history = useHistory();
const [addItem] = useMutation(ADD_ITEM_QUERY);

const onClick = () => {
    addItem({
        variables: {
            id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
            name: 'Foo Bar'
        },
        optimisticResponse: {
            addItem {
                id: '16b1119a-9d96-4bc8-96a3-12df349a0c4d',
                name: 'Foo Bar',
                __typename: 'Item'
            }
        },
        update: () => {
            // Update item cached queries

            history.push(`/items);
        }
    });
};

The issue comes from the redirect. As far as I understand it, the update function is called twice: a first time with the optimisticResponse, and a second time with the network response (which should normally be the same).

However, let's consider the following scenario:

I create a new item,

I receive the optimistic response, and I'm redirected to the list of items,

I click on "Add an item" to be redirected to the form

I receive the server response, hence I'm redirected again to the list.

What is the correct way to prevent this double redirection?

I thought checking the current cache value. If the value is already the latest one, I won't apply the redirect. Not sure if there is a better way? How do you proceed such a scenario?

Body:
You should call history.push outside of the update function. You can do

addItem({...}).then(() => history.push('/items')).


问:
Simulation test for Bernoulli trials for increasing sample size in R
In R software, I am trying to generate a simulation plot for bernoulli trial for different sample sizes as below

I have generated the proportions for given sample size and repeated the process 1000 times. But I dont understand, how to plot the graph as given figure.

```<code>m=1000 ###### replications
n=10  ###### sample size
my=function(){
n=10 ######Trials
u=rbinom(n,1,0.5)
}
Simulated_data=t((replicate(m, my())))
Proportions<-apply(Simulated_data,1,sum)/n
Proportions
</code>```

答:
I think what you want is this.

```<code>R <- 50
n <- 1000

set.seed(42)
res <- replicate(R, rbinom(n, 1, .5))
p <- apply(res, 2, function(x) cumsum(x)/seq_along(x))
plot(1:1000, ylim=c(0, 1), type="n")
apply(p, 2, function(x) lines(1:1000, x, col="grey50"))
abline(h=.5)
</code>```

Body:
In R software, I am trying to generate a simulation plot for bernoulli trial for different sample sizes as below

I have generated the proportions for given sample size and repeated the process 1000 times. But I dont understand, how to plot the graph as given figure.

m=1000 ###### replications
n=10  ###### sample size
my=function(){
n=10 ######Trials
u=rbinom(n,1,0.5)
}
Simulated_data=t((replicate(m, my())))
Proportions<-apply(Simulated_data,1,sum)/n
Proportions

Body:
I think what you want is this.

R <- 50
n <- 1000

set.seed(42)
res <- replicate(R, rbinom(n, 1, .5))
p <- apply(res, 2, function(x) cumsum(x)/seq_along(x))
plot(1:1000, ylim=c(0, 1), type="n")
apply(p, 2, function(x) lines(1:1000, x, col="grey50"))
abline(h=.5)


问:
How can I open an html & css file on my Macbook on my iPhone?
I'm making a website (html & css) on my Macbook that's just on localhost.

I'm looking to be able to easily open the website on my iPhone for testing.

Does anyone have any neat ideas on how I can do this?

If this is not the right type of question to ask here would someone be so kind enough to point me to an appropriate forum?

答: Ensure that the two devices are on the same network, make sure that the HTTP server isn't just listening on the loopback interface, then just replace localhost in the URL with the IP address or hostname of the Macbook and load that on the phone's browser.


问:
When glIsTexture is useful
Here is the example opengl commands sequence:

```<code>glGenTextures(1, &texId);
std::cout << (int)glIsTexture(texId) << std::endl; //0
glBindTexture(GL_TEXTURE_2D, texId);
std::cout << (int)glIsTexture(texId) << std::endl; //1
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.getWidth(), img.getHeight(),
             0, GL_BGR, GL_UNSIGNED_BYTE, img.accessPixels()); //when data == 0 glIsTexture returns the same results
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
std::cout << (int)glIsTexture(texId) << std::endl; //1
glDeleteTextures(1, &texId);
std::cout << (int)glIsTexture(texId) << std::endl; //0
</code>```

I wonder when glIsTexture function is useful ? It looks like that the main usage is checking if texture has been deleted. glIsTexture also returns false when a texture has been generated but is not bound and initialized. Do you know any other scenarios ?

答:
I wonder when glIsTexture function is useful ? It looks like that the main usage is checking if texture has been deleted.

If the renderer is properly architectured, then there is no need to check if a texture has been deleted (the code would already know).

I assume the designers felt exposing the state of the texture ID could be useful for either debugging or to implement some kind of pool of textures.

Title: When glIsTexture is useful

Body:
Here is the example opengl commands sequence:

glGenTextures(1, &texId);
std::cout << (int)glIsTexture(texId) << std::endl; //0
glBindTexture(GL_TEXTURE_2D, texId);
std::cout << (int)glIsTexture(texId) << std::endl; //1
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.getWidth(), img.getHeight(),
             0, GL_BGR, GL_UNSIGNED_BYTE, img.accessPixels()); //when data == 0 glIsTexture returns the same results
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
std::cout << (int)glIsTexture(texId) << std::endl; //1
glDeleteTextures(1, &texId);
std::cout << (int)glIsTexture(texId) << std::endl; //0

I wonder when glIsTexture function is useful ? It looks like that the main usage is checking if texture has been deleted. glIsTexture also returns false when a texture has been generated but is not bound and initialized. Do you know any other scenarios ?


问:
symfony sub query with getDQL query
```<code>$sub = $this->entityManager->createQueryBuilder();
$sub->select('d')
    ->from($this->entityManager->getClassMetadata($entityClass)->getName(), 'd')
    ->where("d.number != ''")
    ->orderBy('d.time', 'DESC');

*

    $qb = $this->entityManager->createQueryBuilder();
    $qb->select('p')
        ->from($sub->getDQL(),'p')
        ->groupBy('p.number');

*
</code>```

Please correct above subqueries if anything is wrong in it.
It is showing error
 [Syntax Error] line 0, col 14: Error: Expected Doctrine\ORM\Query\Lexer::T_ALIASED_NAME, got 'SELECT'

答:
Try below code once

```<code>$sub = $this->createQueryBuilder('data');
 $sub->select('d')
     ->from($this->getEntityManager()->getClassMetadata($entityClass)->getName(), 'd')
     ->where("d.number != ''")
     ->orderBy('d.time', 'DESC');

 $qb = $this->createQueryBuilder('data');
 $qb->select('p')
    ->from($sub->getDQL(),'p')
    ->groupBy('p.number');
</code>```

Title: symfony sub query with getDQL query

Body:
$sub = $this->entityManager->createQueryBuilder();
$sub->select('d')
    ->from($this->entityManager->getClassMetadata($entityClass)->getName(), 'd')
    ->where("d.number != ''")
    ->orderBy('d.time', 'DESC');

*

    $qb = $this->entityManager->createQueryBuilder();
    $qb->select('p')
        ->from($sub->getDQL(),'p')
        ->groupBy('p.number');

*

Please correct above subqueries if anything is wrong in it.
It is showing error
 [Syntax Error] line 0, col 14: Error: Expected Doctrine\ORM\Query\Lexer::T_ALIASED_NAME, got 'SELECT'

Body:
Try below code once

$sub = $this->createQueryBuilder('data');
 $sub->select('d')
     ->from($this->getEntityManager()->getClassMetadata($entityClass)->getName(), 'd')
     ->where("d.number != ''")
     ->orderBy('d.time', 'DESC');

 $qb = $this->createQueryBuilder('data');
 $qb->select('p')
    ->from($sub->getDQL(),'p')
    ->groupBy('p.number');


问:
How to copy datas from one table into another one with all columns but not id in Laravel?
I use Laravel 6.x and I need to copy datas from one table to another. As usual both of tables has many columns and I'm looking for a solution where I don't depend on column names. In the future maybe columns will be change and I don't want to touch this part of software on every changes.

I want to do something like this:

INSERT INTO product_copys (SELECT * from products);
```

I want to copy all columns without the id from the products table.

I use Product and ProductCopy models to handle these datas.

Is there any handy solution for this in Laravel, Eloquent?

答:
I found a solution to get columns without id column (thanks to Laravel Tricks). Here is code for the Product model:

    /**
     * Get all columns of model
     *
     * @return Array
     */
    public static function getTableColumns() {
        $model = new Product();
        return $model->getConnection()
            ->getSchemaBuilder()
            ->getColumnListing($model->getTable());
    }

    /**
     * Return model's columns without given columns
     *
     * @param Array $without_columns
     * @return Array
     */
    public static function withoutColumn(Array $without_columns) {
        return array_diff(self::getTableColumns(), $without_columns);
    }
```

<p>And here you can use it:</p>

<pre class="lang-php prettyprint-override"><code>$columns = Product::withoutColumn(['id']);
</code>```

Now need only run a raw SQL query in the controller:

    public function backup() {
        $columns = implode(',', Product::withoutColumn(['id']));

        DB::statement('INSERT INTO product_copys ('.$columns.', date_of_backup) (SELECT ' .
            $columns .', NOW() AS date_of_backup FROM products)');

        return Response::HTTP_OK;
    }
```

Body:
I use Laravel 6.x and I need to copy datas from one table to another. As usual both of tables has many columns and I'm looking for a solution where I don't depend on column names. In the future maybe columns will be change and I don't want to touch this part of software on every changes.

I want to do something like this:

INSERT INTO product_copys (SELECT * from products);

I want to copy all columns without the id from the products table.

I use Product and ProductCopy models to handle these datas.

Is there any handy solution for this in Laravel, Eloquent?

Body:
I found a solution to get columns without id column (thanks to Laravel Tricks). Here is code for the Product model:

    /**
     * Get all columns of model
     *
     * @return Array
     */
    public static function getTableColumns() {
        $model = new Product();
        return $model->getConnection()
            ->getSchemaBuilder()
            ->getColumnListing($model->getTable());
    }

    /**
     * Return model's columns without given columns
     *
     * @param Array $without_columns
     * @return Array
     */
    public static function withoutColumn(Array $without_columns) {
        return array_diff(self::getTableColumns(), $without_columns);
    }

And here you can use it:

$columns = Product::withoutColumn(['id']);

Now need only run a raw SQL query in the controller:

    public function backup() {
        $columns = implode(',', Product::withoutColumn(['id']));

        DB::statement('INSERT INTO product_copys ('.$columns.', date_of_backup) (SELECT ' .
            $columns .', NOW() AS date_of_backup FROM products)');

        return Response::HTTP_OK;
    }


问:
Error: Ternary Operator not work correctly in "cout" object
I'm making a C++ program that input a two-digits number, then print screen method to read that number by letter.
The problem that I'm facing is ternary operator. When I execute code below, output is 1 when input is 11, output is 0 when input is 12. I only post a paragraph of my program. I was shortcut it.
My code snippet :</p>

```<code>switch(tens_position_value)
{
   case 1:
   {
        if (unit_position_value == 1|| unit_position_value==2)
        {
            cout << (unit_position_value == 1) ? "Eleven" : "Twelve";
        }
   }
}
</code>```

答:
<< has higher precedence than ?:, so the result of unit_position_value != 1 (0 or 1) is printed instead of the strings. Add parentheses here:

```<code>cout << ((unit_position_value != 1) ? "Eleven" : "Twelve");
</code>```

Body:
I'm making a C++ program that input a two-digits number, then print screen method to read that number by letter.
The problem that I'm facing is ternary operator. When I execute code below, output is 1 when input is 11, output is 0 when input is 12. I only post a paragraph of my program. I was shortcut it.
My code snippet :

switch(tens_position_value)
{
   case 1:
   {
        if (unit_position_value == 1|| unit_position_value==2)
        {
            cout << (unit_position_value == 1) ? "Eleven" : "Twelve";
        }
   }
}

Body:
<< has higher precedence than ?:, so the result of unit_position_value != 1 (0 or 1) is printed instead of the strings. Add parentheses here:

cout << ((unit_position_value != 1) ? "Eleven" : "Twelve");


问:
How to get the actual width and actual height for a control in WPF platform
I am preparing a custom control in the WPF platform in which I am using a content presenter for displaying a view and I am trying to display a text over the content presenter content using the text block control.
For the given text in the text block, I tried to calculate the actual width and actual height for the text block using the measure method for positioning the text block control, but it doesn't provide the actual width and height for the text block control. So that the text block control is not displaying in the view. The code snippet is provided below:
this.CustomTextBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

Can anyone suggest to me how to calculate the actual width and actual height for controls in the WPF platform and also explain to me why the measuring method is not providing the actual width and actual height for the control in the WPF platform?

I have also attached the project download link below:[https://www.syncfusion.com/downloads/support/directtrac/general/ze/BViewWpf1629602448][DemoProject]

答:
UIElement.Measure is a method that is executed by the framework's layout engine.

Measure is executed during the first layout pass and actually calculates the DesiredSize, which is used in the second layout pass when Arrange is invoked. Arrange may uses (depending on the implementation) DesiredSize to arrange its child elements. Measure has no direct influence on the actual size. It only calculates the maximum available space. The size passed into this method is not mandatory as it can be overridden by the measuring algorithm. The argument is considered to be minimum available space.

If you want to modify the size of a FrameworkElement, set the Width and Height properties.

To prevent the TextBlock from occupying the maximum available horizontal space, just set the HorizontalAlignment to something other than the default value HorizontalAlignment.Stretch:

```<code><!-- Use Padding to add additional space -->
<TextBlock Text="Minimum sized TextBlock"
           HorizontalAlignment="Left" />
</code>```

Body:
UIElement.Measure is a method that is executed by the framework's layout engine.

Measure is executed during the first layout pass and actually calculates the DesiredSize, which is used in the second layout pass when Arrange is invoked. Arrange may uses (depending on the implementation) DesiredSize to arrange its child elements. Measure has no direct influence on the actual size. It only calculates the maximum available space. The size passed into this method is not mandatory as it can be overridden by the measuring algorithm. The argument is considered to be minimum available space.

If you want to modify the size of a FrameworkElement, set the Width and Height properties.

To prevent the TextBlock from occupying the maximum available horizontal space, just set the HorizontalAlignment to something other than the default value HorizontalAlignment.Stretch:

<!-- Use Padding to add additional space -->
<TextBlock Text="Minimum sized TextBlock"
           HorizontalAlignment="Left" />


问:
How to write different dataframes into seperate sheets of a csv file?
I have two different panda.DataFrame (df1 and df2). I want to write each dataframe into a separate sheet in the CSV file. In this link, all dataframes are written in the same sheet.

答:
CSV files don't support sheets.

You can use pd.to_excel and ExcelWriter to write in the same excel file:

first, install the openpyxl module if you don't have

```<code>python -m pip install openpyxl
</code>```

```<code>with pd.ExcelWriter('output.xlsx') as writer:
    df1.to_excel(writer, sheet_name='df1')
    df2.to_excel(writer, sheet_name='df2')
</code>```

Documentation here:

Pandas Docs

Body:
CSV files don't support sheets.

You can use pd.to_excel and ExcelWriter to write in the same excel file:

first, install the openpyxl module if you don't have

python -m pip install openpyxl

with pd.ExcelWriter('output.xlsx') as writer:
    df1.to_excel(writer, sheet_name='df1')
    df2.to_excel(writer, sheet_name='df2')

Documentation here:

Pandas Docs