问:
Unit testing method designed to find specific worksheets in spreadsheet
In an application that is designed to read a specific spreadsheet, assumed to have certain worksheets, there is a method designed to return these worksheets. This is using the Epplus library:

```<code>public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v);
{
    foreach (var sheet in spreadsheet.Workbook.Worksheets)
    {
        if ((sheet.Name).CompareTo(v)==0)
        {
            // matching sheet found
            return sheet;
        }
    }

    // at this point, the sheet has not been found
    // we are assuming the user has supplied the correct spreadsheet, with the required worksheets
    // if not, the program cannot continue, as it is totally dependent on this. It will not work with any old spreadsheet
    throw new Exception("Could not find required Excel worksheet: " + v);
}
</code>```

As is commented in the code, its purpose is to check the worksheets with the required names are there, and return them as ExcelWorksheet objects. They are called three times, as there are three required worksheets.

This method needs to be unit-tested with Microsoft.VisualStudio.TestTools.UnitTesting

```<code>public void findExcelSheet_Test()
{
    // arrange
    ExcelPackage testSpreadsheet = new ExcelPackage();
    ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
    ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
    ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");

    // act

    // assert
}
</code>```

The test method above is a starting point. What would be the best way to go about this?

答:
You are pretty much there. Just need to throw the exception.  But, since you are using Microsoft's Testing tools, you will have to add the attribute to the unit test on the expected exceptions (other tests suites like nunit or xunit have Assert.Throws...):</p>

```<code>[TestMethod]
[ExpectedException(typeof(Exception))]
public void findExcelSheet_Test()
{
    // arrange
    ExcelPackage testSpreadsheet = new ExcelPackage();
    ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
    ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
    ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");

    // act
    findExcelSheet(testSpreadsheet, Path.GetRandomFileName()); //or some other random string

    // assert

}
</code>```

Body:
In an application that is designed to read a specific spreadsheet, assumed to have certain worksheets, there is a method designed to return these worksheets. This is using the Epplus library:

public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v);
{
    foreach (var sheet in spreadsheet.Workbook.Worksheets)
    {
        if ((sheet.Name).CompareTo(v)==0)
        {
            // matching sheet found
            return sheet;
        }
    }

    // at this point, the sheet has not been found
    // we are assuming the user has supplied the correct spreadsheet, with the required worksheets
    // if not, the program cannot continue, as it is totally dependent on this. It will not work with any old spreadsheet
    throw new Exception("Could not find required Excel worksheet: " + v);
}

As is commented in the code, its purpose is to check the worksheets with the required names are there, and return them as ExcelWorksheet objects. They are called three times, as there are three required worksheets.

This method needs to be unit-tested with Microsoft.VisualStudio.TestTools.UnitTesting

public void findExcelSheet_Test()
{
    // arrange
    ExcelPackage testSpreadsheet = new ExcelPackage();
    ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
    ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
    ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");

    // act

    // assert
}

The test method above is a starting point. What would be the best way to go about this?

Body:
You are pretty much there. Just need to throw the exception.  But, since you are using Microsoft's Testing tools, you will have to add the attribute to the unit test on the expected exceptions (other tests suites like nunit or xunit have Assert.Throws...):

[TestMethod]
[ExpectedException(typeof(Exception))]
public void findExcelSheet_Test()
{
    // arrange
    ExcelPackage testSpreadsheet = new ExcelPackage();
    ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
    ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
    ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");

    // act
    findExcelSheet(testSpreadsheet, Path.GetRandomFileName()); //or some other random string

    // assert

}


来源: stackexchange

问:
Is there a way to convert list of string formatted dictionary to a dataframe in Python?
I am practicing how to use beautifulsoup and currently in a pickle as I can't convert the results to a dataframe. Hope to get your help.

In this example, the page I want to scrape can be obtained using the following:

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd

page = requests.get("https://store.moncler.com/en-ca/women/autumn-winter/view-all-outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0-9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')
</code>```

I have managed to isolate to the product section using the following code

```<code>test_class = []

for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf--moncler'):
    for test in section_tag.find_all('article'):
        test_class.append(test.get('data-ytos-track-product-data'))
</code>```

The result of this is a list of string-formatted dictionary which looks like the following:

['{"product_position":0,"product_title":"TREPORT","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676843","product_micro_category":"Outerwear","product_micro_category_id":"3074457345616676843","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2530.0,"product_price_tf":"0","product_discountedPrice_tf":"2126.05","product_id":"1890828705323513","product_variant_id":"1890828705323514","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"1446","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',
  '{"product_position":1,"product_title":"RIMAC","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676854","product_micro_category":"Bomber
  Jacket","product_micro_category_id":"3074457345616676854","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2340.0,"product_price_tf":"0","product_discountedPrice_tf":"1966.39","product_id":"5549023491788128","product_variant_id":"5549023491788129","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"4715","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',

My question is how to convert the result to a pandas dataframe from a list of string formatted dictionary like that?

I have tried to use the code below to start with

```<code>import ast
ast.literal_eval(test_class[1])
</code>```

but to no avail (it gives me below error code).

ValueError: malformed node or string: <_ast.Name object at
  0x000001985A976748>

The end result should store each key of the dictionary into columns in a Dataframe (ie. 'product_position','product_title','product_brand',etc)

Any help / guidance would be much appreciated.

Thanks.

答:
you can use json.loads and then instantiate pandas.DataFrame with the obtained list of  dictionaries:

```<code>d = [json.loads(e) for e in data]
df = pd.DataFrame(d)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am practicing how to use beautifulsoup and currently in a pickle as I can't convert the results to a dataframe. Hope to get your help.

In this example, the page I want to scrape can be obtained using the following:

from bs4 import BeautifulSoup
import requests
import pandas as pd

page = requests.get("https://store.moncler.com/en-ca/women/autumn-winter/view-all-outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0-9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')

I have managed to isolate to the product section using the following code

test_class = []

for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf--moncler'):
    for test in section_tag.find_all('article'):
        test_class.append(test.get('data-ytos-track-product-data'))

The result of this is a list of string-formatted dictionary which looks like the following:

['{"product_position":0,"product_title":"TREPORT","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676843","product_micro_category":"Outerwear","product_micro_category_id":"3074457345616676843","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2530.0,"product_price_tf":"0","product_discountedPrice_tf":"2126.05","product_id":"1890828705323513","product_variant_id":"1890828705323514","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"1446","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',
  '{"product_position":1,"product_title":"RIMAC","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676854","product_micro_category":"Bomber
  Jacket","product_micro_category_id":"3074457345616676854","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"Dark
  blue","product_color":"Dark
  blue","product_price":0.0,"product_discountedPrice":2340.0,"product_price_tf":"0","product_discountedPrice_tf":"1966.39","product_id":"5549023491788128","product_variant_id":"5549023491788129","list":"searchresult","product_quantity":1,"product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"4715","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}',

My question is how to convert the result to a pandas dataframe from a list of string formatted dictionary like that?

I have tried to use the code below to start with

import ast
ast.literal_eval(test_class[1])

but to no avail (it gives me below error code).

ValueError: malformed node or string: <_ast.Name object at
  0x000001985A976748>

The end result should store each key of the dictionary into columns in a Dataframe (ie. 'product_position','product_title','product_brand',etc)

Any help / guidance would be much appreciated.

Thanks.

Body:
you can use json.loads and then instantiate pandas.DataFrame with the obtained list of  dictionaries:

d = [json.loads(e) for e in data]
df = pd.DataFrame(d)


问:
Camera Capture + Stepper Motor
I am having a problem since im new at the opencv python language, any idea when the camera capture the stepper motor will rotate in 90 degrees.</p>

答: I guess you are using opencv 4. In opencv 3 in cv2.findContours writting _, contours, hierarchy was correct because three arguments were returned. However, in opencv 4 only two arguments are returned so change your statement to contours, hierarchy

Title: Camera Capture + Stepper Motor


问:
number rounding to nearest even number with given precision in oracle
I am trying to round a number in oracle the same way as python does: to nearest even number (to a given precision):

```<code>python:
round(0.3125) -> 0.312

Oracle:
select round(0.3125, 3) from dual -> 0.313
</code>```

Oracle can do this by specifying the input as float when rounding to integers:

```<code>select round(2.5f) from dual -> 2

select round(2.5)  from dual -> 3
</code>```

But:

```<code>select round(0.3125f, 3) from dual -> 0.313 and not 0.312.
Any ideas?
</code>```

答:
Oracle supports ROUND_TIES_TO_EVEN (number):

```<code>SELECT ROUND(0.3125, 3)              AS ROUND       -- 0.313
      ,ROUND_TIES_TO_EVEN(0.3125, 3) AS ROUND_EVEN  -- 0.312
FROM dual;
</code>```

db<>fiddle demo

ContentLicense: CC BY-SA 3.0

Body:
I am trying to round a number in oracle the same way as python does: to nearest even number (to a given precision):

python:
round(0.3125) -> 0.312

Oracle:
select round(0.3125, 3) from dual -> 0.313

Oracle can do this by specifying the input as float when rounding to integers:

select round(2.5f) from dual -> 2

select round(2.5)  from dual -> 3

But:

select round(0.3125f, 3) from dual -> 0.313 and not 0.312.
Any ideas?

Body:
Oracle supports ROUND_TIES_TO_EVEN (number):

SELECT ROUND(0.3125, 3)              AS ROUND       -- 0.313
      ,ROUND_TIES_TO_EVEN(0.3125, 3) AS ROUND_EVEN  -- 0.312
FROM dual;

db<>fiddle demo


问:
Select SQL Server DatetimeOffset as .Net DateTimeOffset.Ticks
I send a SQL query and receive FOR JSON .

```<code>SqlCommand comm = new SqlCommand(@"select top (1000) Date,[open],high,low,[close] from dbo.[foo"] where date > @backDate and date <= @Date  order by date FOR JSON AUTO", conn);

comm.Parameters.AddWithValue("@Date", _definition.dateFrom);
comm.Parameters.AddWithValue("@backDate", lowLimit);

string json = (string)comm.ExecuteScalar();

Debug.WriteLine(json);

/* this causes invalid deserialization */
CudaEngine.OHLC[] stream = JsonConvert.DeserializeObject<CudaEngine.OHLC[]>(json);
</code>```

So the DateTimeOffset in json result looks like this:

[{"Date":"2019-07-30T00:29:00Z","open":1.241829000000000e+004,"high":1.245195000000000e+004,

My ohcl struct have to be like this with date as long.

```<code>public struct OHLC
{
    public long UTCdate;
    public double open;
    public double High;
    public double Low;
    public double Close;
}
</code>```

How can I cast date directly from SQL statement to receive a .Net long either ticks   or millisecond? How can I deserialize without the invalidCastException?

答:
Try following :</p>

```<code>    public struct OHLC
    {
        private long _UTCdate { get; set; }

        public DateTime UTCdate
        {
            get { return DateTime.FromBinary(_UTCdate); }
            set { _UTCdate = value.ToBinary(); }
        }
        public double open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
    }
</code>```

Body:
I send a SQL query and receive FOR JSON .

SqlCommand comm = new SqlCommand(@"select top (1000) Date,[open],high,low,[close] from dbo.[foo"] where date > @backDate and date <= @Date  order by date FOR JSON AUTO", conn);

comm.Parameters.AddWithValue("@Date", _definition.dateFrom);
comm.Parameters.AddWithValue("@backDate", lowLimit);

string json = (string)comm.ExecuteScalar();

Debug.WriteLine(json);

/* this causes invalid deserialization */
CudaEngine.OHLC[] stream = JsonConvert.DeserializeObject<CudaEngine.OHLC[]>(json);

So the DateTimeOffset in json result looks like this:

[{"Date":"2019-07-30T00:29:00Z","open":1.241829000000000e+004,"high":1.245195000000000e+004,

My ohcl struct have to be like this with date as long.

public struct OHLC
{
    public long UTCdate;
    public double open;
    public double High;
    public double Low;
    public double Close;
}

How can I cast date directly from SQL statement to receive a .Net long either ticks   or millisecond? How can I deserialize without the invalidCastException?

Body:
Try following :

    public struct OHLC
    {
        private long _UTCdate { get; set; }

        public DateTime UTCdate
        {
            get { return DateTime.FromBinary(_UTCdate); }
            set { _UTCdate = value.ToBinary(); }
        }
        public double open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
    }


问:
SL 4: bind tabitem visibility to checkbox

When I create a new TabItem I create a new CheckBox at the same time.

I would like to bind the TabItem's visibility to the CheckBox, but am having trouble setting up the binding.

```<code>                CheckBox cb = new CheckBox();
                cb.Content = tabItemName;
                cb.Name = tabItemName;

                var visibilityBinding = new Binding("IsChecked");
                visibilityBinding.Mode = BindingMode.TwoWay;
                visibilityBinding.ElementName = cb.Name;  // this could just be a string literal
                visibilityBinding.Converter = new VisibilityConverter();
                m.TabItem.SetBinding(TabItem.VisibilityProperty, visibilityBinding);

                cb.IsChecked = true;
</code>```

At runtime I get this error:

        System.Windows.Data Error: BindingExpression path error: 'IsChecked' property not found on 'Telerik.Windows.Controls.RadTabItem' 'Telerik.Windows.Controls.RadTabItem' (HashCode=66442352). BindingExpression: Path='IsChecked' DataItem='Telerik.Windows.Controls.RadTabItem' (HashCode=66442352); target element is 'Telerik.Windows.Controls.RadTabItem' (Name='Central ...'); target property is 'Visibility' (type 'System.Windows.Visibility')..

What am I doing wrong?  I thought the argument to the Binding ctor was the property on the source object (the CheckBox) that being bound to the property named in the SetBinding() call..

Thanks for any advice...

UPDATE:

I added

        visibilityBinding.Source = cb;

and get this error at runtime:

     Binding.RelativeSource cannot be set while using Binding.Source

答:
Binding.Source() is necessary for binding programmatically, and is exclusive with Binding.ElementName.

So, this works:

```<code>var visibilityBinding = new Binding("IsChecked");
visibilityBinding.Source = cb;
visibilityBinding.Mode = BindingMode.TwoWay;
// visibilityBinding.ElementName = cb.Name;
visibilityBinding.Converter = new VisibilityConverter();
m.TabItem.SetBinding(RadTabItem.VisibilityProperty, visibilityBinding);
</code>```

Hope this helps someone else....

Body:
When I create a new TabItem I create a new CheckBox at the same time.

I would like to bind the TabItem's visibility to the CheckBox, but am having trouble setting up the binding.

                CheckBox cb = new CheckBox();
                cb.Content = tabItemName;
                cb.Name = tabItemName;

                var visibilityBinding = new Binding("IsChecked");
                visibilityBinding.Mode = BindingMode.TwoWay;
                visibilityBinding.ElementName = cb.Name;  // this could just be a string literal
                visibilityBinding.Converter = new VisibilityConverter();
                m.TabItem.SetBinding(TabItem.VisibilityProperty, visibilityBinding);

                cb.IsChecked = true;

At runtime I get this error:

        System.Windows.Data Error: BindingExpression path error: 'IsChecked' property not found on 'Telerik.Windows.Controls.RadTabItem' 'Telerik.Windows.Controls.RadTabItem' (HashCode=66442352). BindingExpression: Path='IsChecked' DataItem='Telerik.Windows.Controls.RadTabItem' (HashCode=66442352); target element is 'Telerik.Windows.Controls.RadTabItem' (Name='Central ...'); target property is 'Visibility' (type 'System.Windows.Visibility')..

What am I doing wrong?  I thought the argument to the Binding ctor was the property on the source object (the CheckBox) that being bound to the property named in the SetBinding() call..

Thanks for any advice...

UPDATE:

I added

        visibilityBinding.Source = cb;

and get this error at runtime:

     Binding.RelativeSource cannot be set while using Binding.Source

Body:
Binding.Source() is necessary for binding programmatically, and is exclusive with Binding.ElementName.

So, this works:

var visibilityBinding = new Binding("IsChecked");
visibilityBinding.Source = cb;
visibilityBinding.Mode = BindingMode.TwoWay;
// visibilityBinding.ElementName = cb.Name;
visibilityBinding.Converter = new VisibilityConverter();
m.TabItem.SetBinding(RadTabItem.VisibilityProperty, visibilityBinding);

Hope this helps someone else....


问:
PHP artisan use domain without port number
When I serve my laravel project with php artisan serve --host=yum-yums.local, I can access the site via http://yum-yums.local:8000

My host file has 127.0.0.1         yum-yums.local

How can I access the site with just yum-yums.local please, with no port number appended?

答:
80 port is the default port number of http so you have to use this command to omit the port number:</p>

```<code>sudo php artisan serve --host=localhost --port=80
</code>```

Body:
80 port is the default port number of http so you have to use this command to omit the port number:

sudo php artisan serve --host=localhost --port=80


问:
Value too long for type character varying(255) SQLite3 to Postgres Django
I have switched from using SQLite3 to Postgres for my Django app.

I have run these commands to get all my data from the SQLite3 database and I wanted to add it to the Postgres database:

```<code>python manage.py dumpdata > db.json
python manage.py loaddata db.json
</code>```

Then I got this error:

```<code>Could not load database.Object(pk=XXXXXXXXXX): value too long for type character varying(255)
</code>```

In my models.py, the max_length is set to 10 and the value of the primary key is 10.

Here is how I set the primary key for that object's model:

models.CharField(max_length=10, unique=True, primary_key=True)
```

Why I am getting that error? I have many other threads about this issue but I haven't yet found an answer that solved my issue.

答:
SQLite uses a form of dynamic typing (bold added):

In SQLite, the datatype of a value is associated with the value itself, not with its container. The dynamic type system of SQLite is backwards compatible with the more common static type systems of other database engines in the sense that SQL statements that work on statically typed databases should work the same way in SQLite. However, the dynamic typing in SQLite allows it to do things which are not possible in traditional rigidly typed databases.

One of the "rigid" things it doesn't do is enforce column lengths:

Note that numeric arguments in parentheses that following the type name (ex: "VARCHAR(255)") are ignored by SQLite - SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values.

It sounds like you have some data that doesn't actually fit inside the column types you have defined. Now that you're migrating to PostgreSQL you may have to manually fix some data or adjust your models accordingly.

Try running something like

select * from app_table order by length(column) desc limit 1;
```

to see what the longest value actually is in that column. Then either extend your model or fix the data.

As an aside, it's not clear if you are migrating your whole workflow to PostgreSQL or just trying to copy data from development to production. I strongly urge you to use Postgres in development if that's the database you'll be targeting in production.

The issue you're having now is a great example of how one RDBMS isn't a drop-in replacement for another. You want to find these issues in development, not when you're trying to deploy to production.

Body:
I have switched from using SQLite3 to Postgres for my Django app.

I have run these commands to get all my data from the SQLite3 database and I wanted to add it to the Postgres database:

python manage.py dumpdata > db.json
python manage.py loaddata db.json

Then I got this error:

Could not load database.Object(pk=XXXXXXXXXX): value too long for type character varying(255)

In my models.py, the max_length is set to 10 and the value of the primary key is 10.

Here is how I set the primary key for that object's model:

models.CharField(max_length=10, unique=True, primary_key=True)

Why I am getting that error? I have many other threads about this issue but I haven't yet found an answer that solved my issue.

Body:
SQLite uses a form of dynamic typing (bold added):

In SQLite, the datatype of a value is associated with the value itself, not with its container. The dynamic type system of SQLite is backwards compatible with the more common static type systems of other database engines in the sense that SQL statements that work on statically typed databases should work the same way in SQLite. However, the dynamic typing in SQLite allows it to do things which are not possible in traditional rigidly typed databases.

One of the "rigid" things it doesn't do is enforce column lengths:

Note that numeric arguments in parentheses that following the type name (ex: "VARCHAR(255)") are ignored by SQLite - SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values.

It sounds like you have some data that doesn't actually fit inside the column types you have defined. Now that you're migrating to PostgreSQL you may have to manually fix some data or adjust your models accordingly.

Try running something like

select * from app_table order by length(column) desc limit 1;

to see what the longest value actually is in that column. Then either extend your model or fix the data.

As an aside, it's not clear if you are migrating your whole workflow to PostgreSQL or just trying to copy data from development to production. I strongly urge you to use Postgres in development if that's the database you'll be targeting in production.

The issue you're having now is a great example of how one RDBMS isn't a drop-in replacement for another. You want to find these issues in development, not when you're trying to deploy to production.


问:
Extract content between pipes using RE2 Regexp_Extract
I have data in certain dimensions that can look like this:

```<code>this|is|an|example
withoutpipe
only1|pipe
</code>```

I want to extract the data between the pipes using RE2 RegEx.

I have tried it with [^|]+ but this does not seem to work.

I want every word to get extracted and need help trying to figure out how.

答:
Google Data Studio uses the RE2 Syntax for Regular Expressions, and the escape sequence for special characters is:

```<code>\\
</code>```

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate using the REGEXP_REPLACE function:

1) Nothing

```<code>REGEXP_REPLACE(Field, "\\|", "")
</code>```

2) Space

```<code>REGEXP_REPLACE(Field, "\\|", " ")
</code>```

3) Comma & Space

```<code>REGEXP_REPLACE(Field, "\\|", ", ")
</code>```

Body:
I have data in certain dimensions that can look like this:

this|is|an|example
withoutpipe
only1|pipe

I want to extract the data between the pipes using RE2 RegEx.

I have tried it with [^|]+ but this does not seem to work.

I want every word to get extracted and need help trying to figure out how.

Body:
Google Data Studio uses the RE2 Syntax for Regular Expressions, and the escape sequence for special characters is:

\\

Created a Google Data Studio Report (Google Sheets Embedded) to demonstrate using the REGEXP_REPLACE function:

1) Nothing

REGEXP_REPLACE(Field, "\\|", "")

2) Space

REGEXP_REPLACE(Field, "\\|", " ")

3) Comma & Space

REGEXP_REPLACE(Field, "\\|", ", ")


问:
Parentheses change O(n) algorithm
If I have a n length string of open ( and close ) parentheses and I have to count the number of time I change the close ) parentheses to open ( every time when I have more close parentheses than the open one at the current moment while traversing from left to right in every substring of that string.

For e.g. : n = 3, s = ) ( ) :

all substring of s will be [ ), ) (, ) ( ), (, ( ), ) ]

we will have to count in all substring, like in ) ( ) we have close = 1 and open = 0, close > open hence count++. Now the currently processed string is ( ( ), and have no more change to do. Similarly, when we do this for all substring count will be 4.

I wrote a brute force code. I'm assuming is there any way to do this using stack or dynamic programming to do in O(n) or something?

My brute force is like :
1. Create every substring of the given string. O(n^2).
2. Iterating through one substring at a time to count the change. O(n)
Hence, total complexity is O(n^3)

答:
The O annotation is not taking into account things like your bookkeeping/state variables etc. It is only related to how often the input data has to be processed.
If I understood your task right, you just need to loop a single time through every character.
Since during that single loop there is no information available to you that tells you something about characters further down the line, you have absolutely no choice than to loop through the entire string a single time.
Therefore O(N) is the best possible complexity for this task.

If your "bruteforce code" loops more than once (aka is not O(N)), post it here and people will look.

Title: Parentheses change O(n) algorithm


问:
Laravel 5.8 check record in the database if exists not working
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

```<code>$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}
</code>```

tried
dd($request->all());
I got

```<code>array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]
</code>```

答:
you can easily do that with laravel unique validation by using Rule class as below

```<code>$this->validate($request, [
    'subject_code_id' => [
        Rule::unique('schedules')->where(function ($query) use($request) {
            return $query->where('teacher_id', $request->teacher); //you can add all conditions here
        }),
    ],
]);
</code>```

for more see unique validation rules here

Body:
I got a schedules table and i want it to have any duplicates. If the user puts same datas in the form that has already in the database it will not go to dd('exists') does anyone know what seems to be the problem?

Here is my update

$schedule = Schedule::findOrFail($id);

$validate = Schedule::where('subject_code_id',$request->subject)
                    ->where('teacher_id',$request->teacher)
                    ->where('room_id',$request->room)
                    ->where('start_time',$request->start_time)
                    ->where('end_time',$request->end_time)
                    ->where('school_year',$request->schoolyr)
                    ->where('day',$request->days)
                    ->where('term',$request->term)
                    ->where('semester',$request->sem)
                    ->count();

if($validate == 1){
          dd('exist');
} else{
            $schedule->update($request->all());
}

tried
dd($request->all());
I got

array:11 [
  "id" => 9
  "term" => "2"
  "semester" => "2"
  "start_time" => "10:30 PM"
  "end_time" => "12:30 AM"
  "scid" => 10
  "teacher_id" => 5
  "room_id" => 6
  "subject_code_id" => 9
  "day" => "SAT"
  "school_year" => "2020"
]

Body:
you can easily do that with laravel unique validation by using Rule class as below

$this->validate($request, [
    'subject_code_id' => [
        Rule::unique('schedules')->where(function ($query) use($request) {
            return $query->where('teacher_id', $request->teacher); //you can add all conditions here
        }),
    ],
]);

for more see unique validation rules here


问:
Cross-compiling boost for Windows on Linux
I'm trying to create mingw binaries for boost on a Linux machine. The mingw compiler is present on my system as /usr/bin/i586-mingw32msvc-g++ and I have been able to create a simple HelloWorld.exe application.

Here is an exact list of my actions:

```<code>$ tar xvf boost_1_46_1.tar.gz
$ cd boost_1_46_1/
$ echo "using gcc : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./bjam toolset=gcc target-os=windows
</code>```

The result is this:

```<code>Building the Boost C++ Libraries.

...found 83 targets...
...updating 9 targets...
common.mkdir bin.v2
common.mkdir bin.v2/libs
common.mkdir bin.v2/libs/regex
common.mkdir bin.v2/libs/regex/build
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows
gcc.compile.c++ bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu_test.o
In file included from /usr/include/unicode/pwin32.h:123,
                 from /usr/include/unicode/umachine.h:47,
                 from /usr/include/unicode/uversion.h:47,
                 from libs/regex/build/has_icu_test.cpp:12:
/usr/include/inttypes.h:290: warning: ISO C++ 1998 does not support ‘long long’
/usr/include/inttypes.h:291: warning: ISO C++ 1998 does not support ‘long long’
libs/regex/build/has_icu_test.cpp: In function ‘int main()’:
libs/regex/build/has_icu_test.cpp:24: warning: unused variable ‘c’
gcc.link bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe
/usr/lib/gcc/i586-mingw32msvc/4.4.4/../../../../i586-mingw32msvc/bin/ld: cannot find -licuuc
collect2: ld returned 1 exit status

    "i586-mingw32msvc-g++" -L"/usr/bin" -L"/usr/lib" -Wl,-R -Wl,"/usr/bin" -Wl,-R -Wl,"/usr/lib" -Wl,-rpath-link -Wl,"/usr/bin" -Wl,-rpath-link -Wl,"/usr/lib" -o "bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe" -Wl,--start-group "bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu_test.o"  -Wl,-Bstatic  -Wl,-Bdynamic -licuuc -licui18n -licudata -Wl,--end-group -g

...failed gcc.link bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe...
...failed updating 1 target...
...updated 8 targets...
Performing configuration checks

    - has_icu builds           : no
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
...found 8 targets...
...updating 6 targets...
common.mkdir bin.v2/libs/math
common.mkdir bin.v2/libs/math/config
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4/debug
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows
gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o
cc1plus: warnings being treated as errors
libs/math/config/has_gcc_visibility.cpp: In function ‘int main()’:
libs/math/config/has_gcc_visibility.cpp:13: error: visibility attribute not supported in this configuration; ignored

    "i586-mingw32msvc-g++"  -ftemplate-depth-128 -O0 -fno-inline -Wall -g -Werror -fvisibility=hidden -DBOOST_ALL_NO_LIB=1  -I"." -c -o "bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o" "libs/math/config/has_gcc_visibility.cpp"

...failed gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o...
...failed updating 1 target...
...updated 5 targets...
    - ../config//has_gcc_visibility builds : no
...found 46 targets...
...updating 1 target...
gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_long_double_support.o
...updated 1 target...
    - ../config//has_long_double_support builds : yes
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
************************************************************
Trying to build Boost.Thread with pthread support.
If you need pthread you should specify the paths.
You can specify them in site-config.jam, user-config.jam
or in the environment.
For example:
PTW32_INCLUDE=C:\Program Files\ptw32\Pre-built2\include
PTW32_LIB=C:\Program Files\ptw32\Pre-built2\lib
************************************************************
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:1079: in virtual-target.register-actual-name from module virtual-target
error: Duplicate name of actual target: <pstage/lib>libboost_date_time.a
error: previous virtual target { common%common.copy-libboost_date_time.a.STATIC_LIB { gcc%gcc.archive-libboost_date_time.a.STATIC_LIB { gcc%gcc.compile.c++-gregorian/greg_month.o.OBJ { gregorian/greg_month.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/greg_weekday.o.OBJ { gregorian/greg_weekday.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/date_generators.o.OBJ { gregorian/date_generators.cpp.CPP } } } }
error: created from ./stage-proper
error: another virtual target { common%common.copy-libboost_date_time.a.STATIC_LIB { gcc%gcc.archive-libboost_date_time.a.STATIC_LIB { gcc%gcc.compile.c++-gregorian/greg_month.o.OBJ { gregorian/greg_month.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/greg_weekday.o.OBJ { gregorian/greg_weekday.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/date_generators.o.OBJ { gregorian/date_generators.cpp.CPP } } } }
error: created from ./stage-proper
error: added properties: <debug-symbols>off <define>NDEBUG <inlining>full <optimization>speed <runtime-debugging>off <variant>release
error: removed properties: <debug-symbols>on <inlining>off <optimization>off <runtime-debugging>on <variant>debug
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:490: in actualize-no-scanner from module object(file-target)@3884
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:135: in object(file-target)@3884.actualize from module object(file-target)@3884
/home/francis/orig/boost_1_46_1/tools/build/v2/build-system.jam:748: in load from module build-system
/home/francis/orig/boost_1_46_1/tools/build/v2/kernel/modules.jam:283: in import from module modules
/home/francis/orig/boost_1_46_1/tools/build/v2/kernel/bootstrap.jam:142: in boost-build from module
/home/francis/orig/boost_1_46_1/boost-build.jam:17: in module scope from module
</code>```

It says libicu is not found on my system, but according to Synaptic Package Manage I have the libicu-dev package installed.

I'm not sure how to get it right. Can anyone help?

Update 1

Following @Luke's recoommendation I now gcc-mingw toolset. So now my build instructions look like this:

```<code>tar xvf boost_1_46_1.tar.gz
cd boost_1_46_1/
echo "using gcc : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./bjam toolset=gcc-mingw target-os=windows
</code>```

Which leads to the following errors:

```<code>error: toolset gcc initialization:
error: version 'mingw' requested but 'g++-mingw' not found and version '4.4.5' of default 'g++' does not match
error: initialized from
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build/toolset.jam:38: in toolset.using from module toolset
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build-system.jam:481: in process-explicit-toolset-requests from module build-system
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build-system.jam:561: in load from module build-system
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/kernel/modules.jam:283: in import from module modules
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/kernel/bootstrap.jam:142: in boost-build from module
/home/francis/orig/boost-mingw/boost_1_46_1/boost-build.jam:17: in module scope from module
</code>```

Update 2

I have also tried specifying gcc-mingw in the user-config.jam file. Then my build instructions look like this:

```<code>tar xvf boost_1_46_1.tar.gz
cd boost_1_46_1/
echo "using gcc-mingw : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./bjam toolset=gcc-mingw target-os=windows
</code>```

Which leads to:

```<code>error: version 'mingw' requested but 'g++-mingw' not found and version '4.4.5' of default 'g++' does not match
</code>```

Update 3

Specifying g++-mingw in the user-config.jam file:

```<code>using g++-mingw : 4.4.4: i586-mingw32msvc-g++ ;
</code>```

...leads to the same error.

答:
Cross-compiling boost 1.72.0 for Windows on Ubuntu 18.04

Install MinGW

```<code>$ sudo apt install mingw-w64 mingw-w64-tools

$ sudo update-alternatives --set i686-w64-mingw32-g++ /usr/bin/i686-w64-mingw32-g++-posix
$ sudo update-alternatives --set i686-w64-mingw32-gcc /usr/bin/i686-w64-mingw32-gcc-posix
$ sudo update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix
$ sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix
</code>```

32-bit Compilation (install path: ./boost-x86)

```<code>$ echo "using gcc :  : i686-w64-mingw32-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./b2 --user-config=./user-config.jam --prefix=./boost-x86 target-os=windows address-model=32 variant=release install
</code>```

64-bit Compilation (install path: ./boost-x64)

```<code>$ echo "using gcc :  : x86_64-w64-mingw32-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./b2 --user-config=./user-config.jam --prefix=./boost-x64 target-os=windows address-model=64 variant=release install
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create mingw binaries for boost on a Linux machine. The mingw compiler is present on my system as /usr/bin/i586-mingw32msvc-g++ and I have been able to create a simple HelloWorld.exe application.

Here is an exact list of my actions:

$ tar xvf boost_1_46_1.tar.gz
$ cd boost_1_46_1/
$ echo "using gcc : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./bjam toolset=gcc target-os=windows

The result is this:

Building the Boost C++ Libraries.

...found 83 targets...
...updating 9 targets...
common.mkdir bin.v2
common.mkdir bin.v2/libs
common.mkdir bin.v2/libs/regex
common.mkdir bin.v2/libs/regex/build
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug
common.mkdir bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows
gcc.compile.c++ bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu_test.o
In file included from /usr/include/unicode/pwin32.h:123,
                 from /usr/include/unicode/umachine.h:47,
                 from /usr/include/unicode/uversion.h:47,
                 from libs/regex/build/has_icu_test.cpp:12:
/usr/include/inttypes.h:290: warning: ISO C++ 1998 does not support ‘long long’
/usr/include/inttypes.h:291: warning: ISO C++ 1998 does not support ‘long long’
libs/regex/build/has_icu_test.cpp: In function ‘int main()’:
libs/regex/build/has_icu_test.cpp:24: warning: unused variable ‘c’
gcc.link bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe
/usr/lib/gcc/i586-mingw32msvc/4.4.4/../../../../i586-mingw32msvc/bin/ld: cannot find -licuuc
collect2: ld returned 1 exit status

    "i586-mingw32msvc-g++" -L"/usr/bin" -L"/usr/lib" -Wl,-R -Wl,"/usr/bin" -Wl,-R -Wl,"/usr/lib" -Wl,-rpath-link -Wl,"/usr/bin" -Wl,-rpath-link -Wl,"/usr/lib" -o "bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe" -Wl,--start-group "bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu_test.o"  -Wl,-Bstatic  -Wl,-Bdynamic -licuuc -licui18n -licudata -Wl,--end-group -g

...failed gcc.link bin.v2/libs/regex/build/gcc-mingw-4.4.4/debug/target-os-windows/has_icu.exe...
...failed updating 1 target...
...updated 8 targets...
Performing configuration checks

    - has_icu builds           : no
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
...found 8 targets...
...updating 6 targets...
common.mkdir bin.v2/libs/math
common.mkdir bin.v2/libs/math/config
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4/debug
common.mkdir bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows
gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o
cc1plus: warnings being treated as errors
libs/math/config/has_gcc_visibility.cpp: In function ‘int main()’:
libs/math/config/has_gcc_visibility.cpp:13: error: visibility attribute not supported in this configuration; ignored

    "i586-mingw32msvc-g++"  -ftemplate-depth-128 -O0 -fno-inline -Wall -g -Werror -fvisibility=hidden -DBOOST_ALL_NO_LIB=1  -I"." -c -o "bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o" "libs/math/config/has_gcc_visibility.cpp"

...failed gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_gcc_visibility.o...
...failed updating 1 target...
...updated 5 targets...
    - ../config//has_gcc_visibility builds : no
...found 46 targets...
...updating 1 target...
gcc.compile.c++ bin.v2/libs/math/config/gcc-mingw-4.4.4/debug/target-os-windows/has_long_double_support.o
...updated 1 target...
    - ../config//has_long_double_support builds : yes
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
************************************************************
Trying to build Boost.Thread with pthread support.
If you need pthread you should specify the paths.
You can specify them in site-config.jam, user-config.jam
or in the environment.
For example:
PTW32_INCLUDE=C:\Program Files\ptw32\Pre-built2\include
PTW32_LIB=C:\Program Files\ptw32\Pre-built2\lib
************************************************************
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:1079: in virtual-target.register-actual-name from module virtual-target
error: Duplicate name of actual target: <pstage/lib>libboost_date_time.a
error: previous virtual target { common%common.copy-libboost_date_time.a.STATIC_LIB { gcc%gcc.archive-libboost_date_time.a.STATIC_LIB { gcc%gcc.compile.c++-gregorian/greg_month.o.OBJ { gregorian/greg_month.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/greg_weekday.o.OBJ { gregorian/greg_weekday.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/date_generators.o.OBJ { gregorian/date_generators.cpp.CPP } } } }
error: created from ./stage-proper
error: another virtual target { common%common.copy-libboost_date_time.a.STATIC_LIB { gcc%gcc.archive-libboost_date_time.a.STATIC_LIB { gcc%gcc.compile.c++-gregorian/greg_month.o.OBJ { gregorian/greg_month.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/greg_weekday.o.OBJ { gregorian/greg_weekday.cpp.CPP } } { gcc%gcc.compile.c++-gregorian/date_generators.o.OBJ { gregorian/date_generators.cpp.CPP } } } }
error: created from ./stage-proper
error: added properties: <debug-symbols>off <define>NDEBUG <inlining>full <optimization>speed <runtime-debugging>off <variant>release
error: removed properties: <debug-symbols>on <inlining>off <optimization>off <runtime-debugging>on <variant>debug
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:490: in actualize-no-scanner from module object(file-target)@3884
/home/francis/orig/boost_1_46_1/tools/build/v2/build/virtual-target.jam:135: in object(file-target)@3884.actualize from module object(file-target)@3884
/home/francis/orig/boost_1_46_1/tools/build/v2/build-system.jam:748: in load from module build-system
/home/francis/orig/boost_1_46_1/tools/build/v2/kernel/modules.jam:283: in import from module modules
/home/francis/orig/boost_1_46_1/tools/build/v2/kernel/bootstrap.jam:142: in boost-build from module
/home/francis/orig/boost_1_46_1/boost-build.jam:17: in module scope from module

It says libicu is not found on my system, but according to Synaptic Package Manage I have the libicu-dev package installed.

I'm not sure how to get it right. Can anyone help?

Update 1

Following @Luke's recoommendation I now gcc-mingw toolset. So now my build instructions look like this:

tar xvf boost_1_46_1.tar.gz
cd boost_1_46_1/
echo "using gcc : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./bjam toolset=gcc-mingw target-os=windows

Which leads to the following errors:

error: toolset gcc initialization:
error: version 'mingw' requested but 'g++-mingw' not found and version '4.4.5' of default 'g++' does not match
error: initialized from
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build/toolset.jam:38: in toolset.using from module toolset
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build-system.jam:481: in process-explicit-toolset-requests from module build-system
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/build-system.jam:561: in load from module build-system
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/kernel/modules.jam:283: in import from module modules
/home/francis/orig/boost-mingw/boost_1_46_1/tools/build/v2/kernel/bootstrap.jam:142: in boost-build from module
/home/francis/orig/boost-mingw/boost_1_46_1/boost-build.jam:17: in module scope from module

Update 2

I have also tried specifying gcc-mingw in the user-config.jam file. Then my build instructions look like this:

tar xvf boost_1_46_1.tar.gz
cd boost_1_46_1/
echo "using gcc-mingw : 4.4.4: i586-mingw32msvc-g++ ;" > user-config.jam
./bootstrap.sh
./bjam toolset=gcc-mingw target-os=windows

Which leads to:

error: version 'mingw' requested but 'g++-mingw' not found and version '4.4.5' of default 'g++' does not match

Update 3

Specifying g++-mingw in the user-config.jam file:

using g++-mingw : 4.4.4: i586-mingw32msvc-g++ ;

...leads to the same error.

Body:
Cross-compiling boost 1.72.0 for Windows on Ubuntu 18.04

Install MinGW

$ sudo apt install mingw-w64 mingw-w64-tools

$ sudo update-alternatives --set i686-w64-mingw32-g++ /usr/bin/i686-w64-mingw32-g++-posix
$ sudo update-alternatives --set i686-w64-mingw32-gcc /usr/bin/i686-w64-mingw32-gcc-posix
$ sudo update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix
$ sudo update-alternatives --set x86_64-w64-mingw32-gcc /usr/bin/x86_64-w64-mingw32-gcc-posix

32-bit Compilation (install path: ./boost-x86)

$ echo "using gcc :  : i686-w64-mingw32-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./b2 --user-config=./user-config.jam --prefix=./boost-x86 target-os=windows address-model=32 variant=release install

64-bit Compilation (install path: ./boost-x64)

$ echo "using gcc :  : x86_64-w64-mingw32-g++ ;" > user-config.jam
$ ./bootstrap.sh
$ ./b2 --user-config=./user-config.jam --prefix=./boost-x64 target-os=windows address-model=64 variant=release install


问:
Should I add other files to git except .cpp?
When I created a C++ console project in Visual Studio, I found that besides .cpp files, I had other files like .sln, .vcxproj, .filters, .user.

Should I add them to Git repo?

答:
You can download a .gitignore for Visual Studio. It will make sure only what's necessary to open and work on the project would be tracked, the rest would be ignored.

You can download one from here:

https://github.com/github/gitignore/blob/master/VisualStudio.gitignore


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答: In Perl, arrays and lists are essentially the same thing, but your second example uses neither.  Square brackets surround an array reference (a scalar value), and "assigning" a scalar to an array with something like my @array = $scalar is equivalent to my @array = ($scalar).  Thus, the only element of @array in your second example is an array reference.

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?


问:
write a byte at address in .data segment in RISC-V assembly
I am writing a RISC-V assembly program that need to store a word (saved into a register) into a .data segment:

```<code>.section .rodata
msg:
    .string "Hello World\n"

.section .data
num:
    .word 97

.section .text
.global _start

_start:

    li a1, 100
    sw a1, num

    loop:
        j loop
</code>```

But when the program reaches sw a1, num I get the error "illegal operands `sw a1,num'".
How can I store datas into a memory location inside .data segment? could you give me some hints?

答:
The syntax of the store-word (sw) instruction is

```<code>sw rs2, offset(rs1)
</code>```

where offset is a 12 bit immediate operand.

When you write sw a1, num you get an syntax error and the assembler fails with:

```<code>foo.s: : Assembler messages:
foo.s::13: Error: illegal operands `sw a1,num'
</code>```

Perhaps the simplest way to solve this is to use the load-address (la) pseudo-instruction:

```<code>li a1, 100
la t0, num
sw a1, 0(t0)
</code>```

Since the la instruction completely loads the address into a register we have to use 0 as offset.

The la pseudo-instruction expands to program-counter (PC) relative addressing, i.e. check with objdump:

```<code>00000000000100b0 <_start>:
   100b0:   06400593            addi    a1,zero,100
   100b4:   00001297            auipc   t0,0x1
   100b8:   01028293            addi    t0,t0,16 # 110c4 <__DATA_BEGIN__>
   100bc:   00b2a023            sw  a1,0(t0)
</code>```

Alternatively, you can use absolute addressing:

```<code>li a1, 100
lui t0, %hi(num)
sw a1, %lo(num)(t0)
</code>```

Note that the %hi() and %lo() assembler macros split a 32 bit address into its high 20 bits and low 12 bits parts (i.e. %hi(num) + sign_ext(%lo(num)) = num).

Body:
I am writing a RISC-V assembly program that need to store a word (saved into a register) into a .data segment:

.section .rodata
msg:
    .string "Hello World\n"

.section .data
num:
    .word 97

.section .text
.global _start

_start:

    li a1, 100
    sw a1, num

    loop:
        j loop

But when the program reaches sw a1, num I get the error "illegal operands `sw a1,num'".
How can I store datas into a memory location inside .data segment? could you give me some hints?

Body:
The syntax of the store-word (sw) instruction is

sw rs2, offset(rs1)

where offset is a 12 bit immediate operand.

When you write sw a1, num you get an syntax error and the assembler fails with:

foo.s: : Assembler messages:
foo.s::13: Error: illegal operands `sw a1,num'

Perhaps the simplest way to solve this is to use the load-address (la) pseudo-instruction:

li a1, 100
la t0, num
sw a1, 0(t0)

Since the la instruction completely loads the address into a register we have to use 0 as offset.

The la pseudo-instruction expands to program-counter (PC) relative addressing, i.e. check with objdump:

00000000000100b0 <_start>:
   100b0:   06400593            addi    a1,zero,100
   100b4:   00001297            auipc   t0,0x1
   100b8:   01028293            addi    t0,t0,16 # 110c4 <__DATA_BEGIN__>
   100bc:   00b2a023            sw  a1,0(t0)

Alternatively, you can use absolute addressing:

li a1, 100
lui t0, %hi(num)
sw a1, %lo(num)(t0)

Note that the %hi() and %lo() assembler macros split a 32 bit address into its high 20 bits and low 12 bits parts (i.e. %hi(num) + sign_ext(%lo(num)) = num).


问:
onclick function pass parameters
How can I pass a variable to the onclick function? When using

```<code>var number = 123;
document.getElementById('myButton').onclick = myFunction(number);
</code>```

It will run that function before even clicking the button because the function will be called and the return value will be put into the onclick, which doesnt help me

Without the "()" it will only call the function once I click the button, but how do I pass a variable then ?

```<code>var number = 123;
document.getElementById('myButton').onclick = myFunction;

function myFunction(i) {
    i += 10;
    alert(i);
}
</code>```

答:
One option would be to make the onclick an anonymous function to call myFunction.

var number = 123;
document.getElementById('myButton').onclick = () => {
  myFunction(number)
}

function myFunction(i) {
  i += 10;
  alert(i);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><buton id="myButton"> Test button </buton></code>```

Title: onclick function pass parameters

Body:
How can I pass a variable to the onclick function? When using

var number = 123;
document.getElementById('myButton').onclick = myFunction(number);

It will run that function before even clicking the button because the function will be called and the return value will be put into the onclick, which doesnt help me

Without the "()" it will only call the function once I click the button, but how do I pass a variable then ?

var number = 123;
document.getElementById('myButton').onclick = myFunction;

function myFunction(i) {
    i += 10;
    alert(i);
}

Body:
One option would be to make the onclick an anonymous function to call myFunction.

var number = 123;
document.getElementById('myButton').onclick = () => {
  myFunction(number)
}

function myFunction(i) {
  i += 10;
  alert(i);
}

<buton id="myButton"> Test button </buton>


问:
Chart.js draw y-axis only up to point
I'm wondering how to draw the y-axis only up to the point of one dataset. Like in this example:

So far I've tried a hacky version by adding an inversed white background on the dataset, but because I have some offset on the x-axis the white background cuts suddently, and the Y-axis lines becomes hidden.

Does anyone know how to loop through each grid line and give it the correct length?

答:
You can draw you own lines directly on to the canvas using the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw dashed lines for individual points from the dataset.

const data = [1, 3, 2];
new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
         var x = xAxis.getPixelForValue(undefined, index);
         var yTop = yAxis.getPixelForValue(data[index]);
         ctx.save();
         ctx.setLineDash([10, 5]);
         ctx.strokeStyle = '#888888';
         ctx.beginPath();
         ctx.moveTo(x, yAxis.bottom);
         ctx.lineTo(x, yTop);
         ctx.stroke();
         ctx.restore();
      });
    }
  }],
  data: {
    labels: ["A", "B", "C"],
    datasets: [{
      label: "My First Dataset",
      data: [1, 3, 2],
      fill: false,
      borderColor: "rgb(75, 192, 192)",
      lineTension: 0.3
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        offset: true,
        gridLines: {
          color: 'white'
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          max: 4,
          stepSize: 1
        }
      }]
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  max-width: 200px;
}</code>```

<canvas id="myChart" width="10" height="10"></canvas>```

Title: Chart.js draw y-axis only up to point

Body:
You can draw you own lines directly on to the canvas using the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw dashed lines for individual points from the dataset.

const data = [1, 3, 2];
new Chart(document.getElementById("myChart"), {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
         var x = xAxis.getPixelForValue(undefined, index);
         var yTop = yAxis.getPixelForValue(data[index]);
         ctx.save();
         ctx.setLineDash([10, 5]);
         ctx.strokeStyle = '#888888';
         ctx.beginPath();
         ctx.moveTo(x, yAxis.bottom);
         ctx.lineTo(x, yTop);
         ctx.stroke();
         ctx.restore();
      });
    }
  }],
  data: {
    labels: ["A", "B", "C"],
    datasets: [{
      label: "My First Dataset",
      data: [1, 3, 2],
      fill: false,
      borderColor: "rgb(75, 192, 192)",
      lineTension: 0.3
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        offset: true,
        gridLines: {
          color: 'white'
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          max: 4,
          stepSize: 1
        }
      }]
    }
  }
});

canvas {
  max-width: 200px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="10" height="10"></canvas>


问:
handle two diffrent http json response swift
I have an API that gives me two different responses.

here is when data is correct and I have objects:

```<code>{ "latlng": [My Objects] }
</code>```

and here is when my data is empty:

```<code>[]
</code>```

so my question is how to handle this empty response when I'm using jsonDecoder?

my networking function:

```<code> func performNetworkingTaskWithParams<T: Codable>(endpoint: EndPointType, type: T.Type, params: [String : String],completion: ((_ response: T)-> Void)?) {
    let url = endpoint.baseURL.appendingPathComponent(endpoint.path)

    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept" : "application/json",
        "Content-Type" : "application/x-www-form-urlencoded"
    ]

    var urlRequest = URLRequest(url: url)

    let session = URLSession(configuration: config)

    urlRequest.encodeParameters(parameters: params)

    let taskSession = session.dataTask(with: urlRequest) { (data, response, error) in
        if let myError = error {
            print("request error:\(myError)")
            return
        }

        guard let responseData = data else {
            print("response is null!")
            return
        }

        let response = Response(data: responseData)

        guard let decoded = response.decode(type) else {
            print("cannot decode data!")
            return
        }
        completion?(decoded)
    }

    taskSession.resume()
}
</code>```

答:
In your codable struct, you should implement custom init and set your data as a optional

init(from decoder: Decoder) throws {
     let values = try decoder.container(keyedBy: CodingKeys.self)
     YourField = try? values.decode(TypeOFField.self, forKey: .yourfiled)
}
```

Body:
I have an API that gives me two different responses.

here is when data is correct and I have objects:

{ "latlng": [My Objects] }

and here is when my data is empty:

[]

so my question is how to handle this empty response when I'm using jsonDecoder?

my networking function:

 func performNetworkingTaskWithParams<T: Codable>(endpoint: EndPointType, type: T.Type, params: [String : String],completion: ((_ response: T)-> Void)?) {
    let url = endpoint.baseURL.appendingPathComponent(endpoint.path)

    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = [
        "Accept" : "application/json",
        "Content-Type" : "application/x-www-form-urlencoded"
    ]

    var urlRequest = URLRequest(url: url)

    let session = URLSession(configuration: config)

    urlRequest.encodeParameters(parameters: params)

    let taskSession = session.dataTask(with: urlRequest) { (data, response, error) in
        if let myError = error {
            print("request error:\(myError)")
            return
        }

        guard let responseData = data else {
            print("response is null!")
            return
        }

        let response = Response(data: responseData)

        guard let decoded = response.decode(type) else {
            print("cannot decode data!")
            return
        }
        completion?(decoded)
    }

    taskSession.resume()
}


问:
Cookie vs. Session based flash message
A neat feature which I found in CakePHP was the ability to set a flash message, say on some save script, then have that message displayed on the following page. Something like, Post updated, or Error - no file found.

The way Cake does it is with this session object. I am trying to avoid sessions like the plague because of their odd requirements for scalability. Can I not just simply store the flash message in a cookie (client side) and then delete that cookie once it's displayed on the following page? What would be some pros/cons to this approach - or more simply, why does Cake uses session (I'm assuming that relates to the _SESSION collection).

Cheers!

p.s. In my implementation I also make it fade out with a setTimeout command in javascript. I find that's a nice way to end the whole process.

答:
I don't see why you can't use a cookie with an expiration of say 10 minutes from creation date.  Downside if the user walks away and comes back in 11 minutes they might not see the flash cookie message...but you won't have to worry about flooding a client with cookies.

Just make some simple content rules to ensure that no privileged information is put into a flash message and you should be good.

A simple implementation could be something procedural like:

```<code>function setFlash($id ,$message){
   setcookie("flash_{$id}", $message, time() + 60 * 10);
}

function getFlashes(){
   $flashes = array();
   foreach($_COOKIE as $id => $value){
        if(strpos($id, "flash_") === 0){
             $flashes[$id] = $value;
             //clear flash and set expiration to 10 minutes in past
             setcookie($id, "", time() * 60 * -10);

         }
  }
  return $flashes;
   //Input cleansing not included for brevity/clarity
}
</code>```

Alternatively if the flash is originating soley from the client side, you can use something like https://github.com/marcuswestin/store.js to try and use localSession store to manage flash messages.

Title: Cookie vs. Session based flash message

Body:
I don't see why you can't use a cookie with an expiration of say 10 minutes from creation date.  Downside if the user walks away and comes back in 11 minutes they might not see the flash cookie message...but you won't have to worry about flooding a client with cookies.

Just make some simple content rules to ensure that no privileged information is put into a flash message and you should be good.

A simple implementation could be something procedural like:

function setFlash($id ,$message){
   setcookie("flash_{$id}", $message, time() + 60 * 10);
}

function getFlashes(){
   $flashes = array();
   foreach($_COOKIE as $id => $value){
        if(strpos($id, "flash_") === 0){
             $flashes[$id] = $value;
             //clear flash and set expiration to 10 minutes in past
             setcookie($id, "", time() * 60 * -10);

         }
  }
  return $flashes;
   //Input cleansing not included for brevity/clarity
}

Alternatively if the flash is originating soley from the client side, you can use something like https://github.com/marcuswestin/store.js to try and use localSession store to manage flash messages.


问:
How do I use the annotation and micro in the mod of the test scope?
The structure of my code as below.

I ran 'cargo run' and it works. But when I ran 'cargo test', I got the errors as below. Could you please tell me why and how can I fix them?

error: cannot find attribute get in this scope

error: cannot find macro routes in this scope

src/main.rs

```<code>#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

mod common;

fn main() {
    common::run();
}
</code>```

src/common.rs

```<code>#[get("/hello")]
pub fn hello() -> &'static str {
    "hello"
}

pub fn run() {
    rocket::ignite().mount("/", routes![hello]).launch();
}
</code>```

tests/development.rs

```<code>#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[cfg(test)]
mod common;

#[test]
fn test_development_config() {
    common::run();
}
</code>```

tests/common.rs

```<code>use rocket::http::Status;
use rocket::local::Client;

#[get("/check_config")]
fn check_config() -> &'static str {
    "hello"
}

pub fn run() {
    let rocket = rocket::ignite().mount("/", routes![check_config]);

    let client = Client::new(rocket).unwrap();
    let response = client.get("/hello").dispatch();
    assert_eq!(response.status(), Status::Ok);
}
</code>```

答:
Each .rs file in the tests/ folder is separately compiled and executed as a test. So development.rs is compiled, "includes" common.rs and it works. But then common.rs is compiled individually and it fails because there is no #[macro_use] extern crate rocket; anywhere.

One solution would be to put your common.rs into tests/common/mod.rs. Files in sub-directories of tests are not automatically compiled as test.

Body:
The structure of my code as below.

I ran 'cargo run' and it works. But when I ran 'cargo test', I got the errors as below. Could you please tell me why and how can I fix them?

error: cannot find attribute get in this scope

error: cannot find macro routes in this scope

src/main.rs

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

mod common;

fn main() {
    common::run();
}

src/common.rs

#[get("/hello")]
pub fn hello() -> &'static str {
    "hello"
}

pub fn run() {
    rocket::ignite().mount("/", routes![hello]).launch();
}

tests/development.rs

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[cfg(test)]
mod common;

#[test]
fn test_development_config() {
    common::run();
}

tests/common.rs

use rocket::http::Status;
use rocket::local::Client;

#[get("/check_config")]
fn check_config() -> &'static str {
    "hello"
}

pub fn run() {
    let rocket = rocket::ignite().mount("/", routes![check_config]);

    let client = Client::new(rocket).unwrap();
    let response = client.get("/hello").dispatch();
    assert_eq!(response.status(), Status::Ok);
}


问:
Parsing expressions with suffixes using pyparsing
I want to parse the following (simplified) recursive expressions using PyParsing:

```<code>foo
(foo + bar)
foo'attribute
foo + bar'attribute
foo.field
(foo'attribute + foo.field)'attribute
</code>```

I came up with the following parser which works for all of the above expressions:

        identifier = Word(alphas)
        expr = (
            infixNotation(
                identifier,
                [
                    (Literal(".") + identifier, 1, opAssoc.LEFT),
                    (Literal("'") + identifier, 1, opAssoc.LEFT),
                    (Literal("+"), 2, opAssoc.LEFT),
                ],
            )
            + StringEnd()
        )
```

<p>What fails, however, are expressions that involve <code>.field</code> and the <code>'attribute</code> suffix together. While <code>foo.field'attribute</code> is accepted, <code>foo'attribute.field</code> yields</p>

<pre class="lang-py prettyprint-override"><code>pyparsing.ParseException: Expected end of text (at char 13), (line:1, col:14)
</code>```

When exchanging the tuples for attribute and field of the infixNotation, the second expression parses and the first doesn't. Seems like the order/precedence is relevant.

Any ideas how to parse arbitrary recursive appearances of different suffixes?

答:
Each tuple in the list defines its own level of precedence. When one operator has a higher precedence than another, the lower precedence operator can only be used as an operand of the higher precedence one by using parentheses (note that (foo'attribute).field parses fine).

For unary operators, you usually want a single level of precedence for all postfix operators (and another for all prefix operators if you had any). The way you do that in pyparsing is by using a tuple containing a single rule that can match both operators:

```<code>(oneOf(". '") + identifier, 1, opAssoc.LEFT),
</code>```

Body:
I want to parse the following (simplified) recursive expressions using PyParsing:

foo
(foo + bar)
foo'attribute
foo + bar'attribute
foo.field
(foo'attribute + foo.field)'attribute

I came up with the following parser which works for all of the above expressions:

        identifier = Word(alphas)
        expr = (
            infixNotation(
                identifier,
                [
                    (Literal(".") + identifier, 1, opAssoc.LEFT),
                    (Literal("'") + identifier, 1, opAssoc.LEFT),
                    (Literal("+"), 2, opAssoc.LEFT),
                ],
            )
            + StringEnd()
        )

What fails, however, are expressions that involve .field and the 'attribute suffix together. While foo.field'attribute is accepted, foo'attribute.field yields

pyparsing.ParseException: Expected end of text (at char 13), (line:1, col:14)

When exchanging the tuples for attribute and field of the infixNotation, the second expression parses and the first doesn't. Seems like the order/precedence is relevant.

Any ideas how to parse arbitrary recursive appearances of different suffixes?

Body:
Each tuple in the list defines its own level of precedence. When one operator has a higher precedence than another, the lower precedence operator can only be used as an operand of the higher precedence one by using parentheses (note that (foo'attribute).field parses fine).

For unary operators, you usually want a single level of precedence for all postfix operators (and another for all prefix operators if you had any). The way you do that in pyparsing is by using a tuple containing a single rule that can match both operators:

(oneOf(". '") + identifier, 1, opAssoc.LEFT),


问:
What to put in msg.criteria for fetching emails in Node-RED email node?
I have two flows using the node-red-node-email node in Node-RED.

The first one uses predefined value for fetching all emails (Criteria: All). It works properly and fetches two emails I have in my Inbox:

The second one should emulate the same, but thru specifying msg.criteria:

I created a flow with a change node setting the value.

The info page for the email module refers to a doc page for another module and does not give a clear example, but I assumed I should add a string value of [ ALL ]. Here's the relevant part of the change module:

```<code>"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "[ 'ALL' ]",
        "tot": "str"
    }
</code>```

In result the email node changes to connecting then to fetching and remains in this state. The Node-RED web server does not respond for a while.

I also tried specifying msg.criteria as a JSON object the following way (in result I get an "Invalid 'to' JSON property" in debug):

```<code>"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "[ 'ALL' ]",
        "tot": "json"
    }
],
</code>```

or the following way (in result I have no response at all; the email node does not even go to connecting state):

```<code>"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "{ [ 'ALL' ] }",
        "tot": "json"
    }
],
</code>```

What type should msg.criteria be and what data should it contain to fetch all emails (and by extension other criteria)?

答:
As I mentioned in my second comment, this is most likely to do with how you set up the change node with the JSON array.

The following change node config works as expected.

Note that ALL is wrapped with double quotes, not single quotes. This is important as the Change node throws an error when single quotes are set and doesn't actually add the field to the msg object.

Body:
I have two flows using the node-red-node-email node in Node-RED.

The first one uses predefined value for fetching all emails (Criteria: All). It works properly and fetches two emails I have in my Inbox:

The second one should emulate the same, but thru specifying msg.criteria:

I created a flow with a change node setting the value.

The info page for the email module refers to a doc page for another module and does not give a clear example, but I assumed I should add a string value of [ ALL ]. Here's the relevant part of the change module:

"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "[ 'ALL' ]",
        "tot": "str"
    }

In result the email node changes to connecting then to fetching and remains in this state. The Node-RED web server does not respond for a while.

I also tried specifying msg.criteria as a JSON object the following way (in result I get an "Invalid 'to' JSON property" in debug):

"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "[ 'ALL' ]",
        "tot": "json"
    }
],

or the following way (in result I have no response at all; the email node does not even go to connecting state):

"rules": [
    {
        "t": "set",
        "p": "criteria",
        "pt": "msg",
        "to": "{ [ 'ALL' ] }",
        "tot": "json"
    }
],

What type should msg.criteria be and what data should it contain to fetch all emails (and by extension other criteria)?


问:
finding astrology signs according to your month and date, simpler way to do it? instead of 12 if function
```<code>if month == 12:
    if 0 < date < 23:
        return 'SAG'
    if 23 <= date < 32:
        return 'CAP'
if month == 1:
    if 0 < date < 21:
        return 'CAP'
    if 21 <= date < 32:
        return 'AQU'
if month == 2:
    if 0 < date < 20:
        return 'AQU'
    if 20 <= date < 30:
        return 'PIS'
if month == 3:
    if 0 < date < 21:
            return 'PIS'
    if 21 <= date < 32:
            return 'ARI'
</code>```

<p>I am looking for a simpler and more effective way of completing my function of finding astrological sign according to month and date, is there a more effective method or is using 12 if loops a must?    </p>

答:
Dates are always tough to work with and mapping the lunar calendar to the solar calendar present special problems. It becomes easier if you approach it from a days in the year problem instead of a dates problem. </p>

```<code>import numpy as np
from datetime import datetime as dt

def getSign(birthDate):
    #get day of year of birth
    dayOfBirth = (birthDate - dt(birthDate.year, 1, 1)).days

        #adjust for leap years
    if birthDate.year%4==0 and dayOfBirth > 60:
        dayOfBirth -= 1

    #build dict of max day for each sign. capricorn  is set twice due to straddling of solar year
    signs = {20:'Capricorn', 49:'Aquarius', 79:'Pisces', 109:'Aries', 140:'Taurus', 171:'Genini', 203:'Cancer', 234:'Leo', 265:'Virgo', 295:'Libra', 325:'Scorpio', 355:'Sagitarius', 365:'Capricorn'}

    #create numpy array of maximum days
    daysArray = np.array(list(signs.keys()))

    #get sign max days closest to but larger than dayOfBirth
    maxDayCount = min(daysArray[daysArray >= dayOfBirth])

    return signs[maxDayCount]

>>> getSign(dt(2000, 3, 22))
'Aries'
>>> getSign(dt(2000, 1, 1))
'Capricorn'
>>> getSign(dt(2000, 12, 22))
'Sagitarius'
>>> getSign(dt(2000, 12, 31))
'Capricorn'
</code>```

Body:
if month == 12:
    if 0 < date < 23:
        return 'SAG'
    if 23 <= date < 32:
        return 'CAP'
if month == 1:
    if 0 < date < 21:
        return 'CAP'
    if 21 <= date < 32:
        return 'AQU'
if month == 2:
    if 0 < date < 20:
        return 'AQU'
    if 20 <= date < 30:
        return 'PIS'
if month == 3:
    if 0 < date < 21:
            return 'PIS'
    if 21 <= date < 32:
            return 'ARI'

I am looking for a simpler and more effective way of completing my function of finding astrological sign according to month and date, is there a more effective method or is using 12 if loops a must?

Body:
Dates are always tough to work with and mapping the lunar calendar to the solar calendar present special problems. It becomes easier if you approach it from a days in the year problem instead of a dates problem.

import numpy as np
from datetime import datetime as dt

def getSign(birthDate):
    #get day of year of birth
    dayOfBirth = (birthDate - dt(birthDate.year, 1, 1)).days

        #adjust for leap years
    if birthDate.year%4==0 and dayOfBirth > 60:
        dayOfBirth -= 1

    #build dict of max day for each sign. capricorn  is set twice due to straddling of solar year
    signs = {20:'Capricorn', 49:'Aquarius', 79:'Pisces', 109:'Aries', 140:'Taurus', 171:'Genini', 203:'Cancer', 234:'Leo', 265:'Virgo', 295:'Libra', 325:'Scorpio', 355:'Sagitarius', 365:'Capricorn'}

    #create numpy array of maximum days
    daysArray = np.array(list(signs.keys()))

    #get sign max days closest to but larger than dayOfBirth
    maxDayCount = min(daysArray[daysArray >= dayOfBirth])

    return signs[maxDayCount]

>>> getSign(dt(2000, 3, 22))
'Aries'
>>> getSign(dt(2000, 1, 1))
'Capricorn'
>>> getSign(dt(2000, 12, 22))
'Sagitarius'
>>> getSign(dt(2000, 12, 31))
'Capricorn'


问:
Java - Multilevel sort of a 2D array of integers
I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java,
where the first numbers takes priority.

so a dataset like this:-

```<code>{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}
</code>```

Should return something like this:-

```<code>{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}
</code>```

答:
How about this:</p>

```<code>for(int i = 0; i < arr.length; i++)
{
    int min = i;

    for(int j = i; j < arr.length; j++)
    {
        if(arr[min][0] > arr[j][0])
        {
            min = j;
        }
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}

for(int i = 0; i < arr.length; i++)
{
    int min = i;
    for(int j = i; j < arr.length; j++)
    {
        if(arr[j][0] != arr[i][0])
        break;

        if(arr[min][1] > arr[j][1])
        min = j;
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}
</code>```

Body:
I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java,
where the first numbers takes priority.

so a dataset like this:-

{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}

Should return something like this:-

{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}

Body:
How about this:

for(int i = 0; i < arr.length; i++)
{
    int min = i;

    for(int j = i; j < arr.length; j++)
    {
        if(arr[min][0] > arr[j][0])
        {
            min = j;
        }
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}

for(int i = 0; i < arr.length; i++)
{
    int min = i;
    for(int j = i; j < arr.length; j++)
    {
        if(arr[j][0] != arr[i][0])
        break;

        if(arr[min][1] > arr[j][1])
        min = j;
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}


答:
Here's a way to do it:</p>

```<code>import java.util.*;

public class Test
{
     public static void main(String []args)
     {
         Integer[][] a = {
                    {1,2},
                    {2,9},
                    {2,7},
                    {2,8},
                    {5,6},
                    {5,8},
                    {5,2},
                    {4,1},
                    {4,4}
                  };

        Arrays.sort(a, new Comparator<Integer[]>()
        {
            public int compare(Integer[] a, Integer[] b)
            {
                int res = a[0].compareTo(b[0]);
                if(res!=0)
                    return res;
                return a[1].compareTo(b[1]);
            }
        });

        System.out.println(Arrays.deepToString(a));
     }
}
</code>```

Title: Java - Multilevel sort of a 2D array of integers

Body:
Here's a way to do it:

import java.util.*;

public class Test
{
     public static void main(String []args)
     {
         Integer[][] a = {
                    {1,2},
                    {2,9},
                    {2,7},
                    {2,8},
                    {5,6},
                    {5,8},
                    {5,2},
                    {4,1},
                    {4,4}
                  };

        Arrays.sort(a, new Comparator<Integer[]>()
        {
            public int compare(Integer[] a, Integer[] b)
            {
                int res = a[0].compareTo(b[0]);
                if(res!=0)
                    return res;
                return a[1].compareTo(b[1]);
            }
        });

        System.out.println(Arrays.deepToString(a));
     }
}


问:
Displaying array elements in a TextView
****I am very new to Java and android studio and am trying to  display an individual element of my array into my textView wordTextView with every click of a button. When I click the button on the emulator nothing is being displayed. I have also tried to use a for loop yet I cannot seem to get that to work either. Any help would be greatly appreciated****

```<code>public class MainActivity extends AppCompatActivity {

    int i = 0;

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

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
    }

    public void getNextWord(String string) {
        String [] array = {"Noun", "Adjective", "Proper Noun", "Name"};
        TextView wordTextView = findViewById(R.id.wordTextView);
        wordTextView.setText(array[i]);
    }
}
</code>```

Here is the .xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="nextWord"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/wordTextView"
        android:layout_width="155dp"
        android:layout_height="153dp"
        android:layout_marginTop="84dp"
        android:gravity="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/enterEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="280dp"
        android:ems="10"
        android:hint="Something"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/wordTextView" />

    <Button
        android:id="@+id/nextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:onClick="nextWord"
        android:text="Next"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/enterEditText"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
You can do something like this:</p>

```<code>public class MainActivity extends AppCompatActivity {

    int i = 0;

    TextView wordTextView; // declare your textView here

    // no need to create array again in "getNextWord" method
    String[] array = {"Noun", "Adjective", "Proper Noun", "Name"};

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

        // initialise text view here
        wordTextView = findViewById(R.id.wordTextView);
    }

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
        getNextWord() // call this method here, without passing string
    }

    public void getNextWord() {
        // you need to check the value of "i", it should not be greater than "array" size.
        // you can simply do
        // i = i% array.length
        // or you can check index with if-condition
        // otherwise you will get "ava.lang.ArrayIndexOutOfBoundsException" if i >= array.length
        wordTextView.setText(array[i]);
    }
}
</code>```

Title: Displaying array elements in a TextView

Body:
****I am very new to Java and android studio and am trying to  display an individual element of my array into my textView wordTextView with every click of a button. When I click the button on the emulator nothing is being displayed. I have also tried to use a for loop yet I cannot seem to get that to work either. Any help would be greatly appreciated****

public class MainActivity extends AppCompatActivity {

    int i = 0;

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

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
    }

    public void getNextWord(String string) {
        String [] array = {"Noun", "Adjective", "Proper Noun", "Name"};
        TextView wordTextView = findViewById(R.id.wordTextView);
        wordTextView.setText(array[i]);
    }
}

Here is the .xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="nextWord"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/wordTextView"
        android:layout_width="155dp"
        android:layout_height="153dp"
        android:layout_marginTop="84dp"
        android:gravity="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/enterEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="280dp"
        android:ems="10"
        android:hint="Something"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/wordTextView" />

    <Button
        android:id="@+id/nextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:onClick="nextWord"
        android:text="Next"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/enterEditText"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
You can do something like this:

public class MainActivity extends AppCompatActivity {

    int i = 0;

    TextView wordTextView; // declare your textView here

    // no need to create array again in "getNextWord" method
    String[] array = {"Noun", "Adjective", "Proper Noun", "Name"};

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

        // initialise text view here
        wordTextView = findViewById(R.id.wordTextView);
    }

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
        getNextWord() // call this method here, without passing string
    }

    public void getNextWord() {
        // you need to check the value of "i", it should not be greater than "array" size.
        // you can simply do
        // i = i% array.length
        // or you can check index with if-condition
        // otherwise you will get "ava.lang.ArrayIndexOutOfBoundsException" if i >= array.length
        wordTextView.setText(array[i]);
    }
}