问:
ADO.Net query suddenly stopped working on my query
I'm using ADO.Net in an ASP.Net application.  All of a sudden my query stopped working.  This is the original query:

```<code>using (var sqlConnection = new SqlConnection(this.connection))
{
    var sql = @"select *
                From Contacts.Departments a
                Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
                Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
                Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
                Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
                Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
                Where a.DepartmentID = @DepartmentID and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";
    ...

    ...
}
</code>```

when it executes I get an error

Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

The results should only return 45 rows so its not very large. When I run the query in SQL Server Management Studio, it's not an issue and I get the 45 rows.

But in my application if I put a top in the statement then it works:

```<code>var sql = @"select top 1000 *
            From Contacts.Departments a
            Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
            Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
            Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
            Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
            Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
            Where a.DepartmentID = @DepartmentID and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";
</code>```

or if I take out the parameterized query and just add the value directly in the string:

```<code>var sql = $@"select *
            From Contacts.Departments a
            Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
            Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
            Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
            Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
            Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
            Where a.DepartmentID = {department_id} and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";
</code>```

This is so odd because I have not touched the code and suddenly it just failed.  When I test the same in my development machine I can recreate the error and solution above.

I'm kinda in a lose on what to check since, the query works when I modify it to the one of the two above.  But, then why would the original fail when trying to retrieve the data from SQL Server 2016

答:
check in your connection string the time out variable

example

Integrated Security = SSPI; Connection Timeout = 30

Body:
I'm using ADO.Net in an ASP.Net application.  All of a sudden my query stopped working.  This is the original query:

using (var sqlConnection = new SqlConnection(this.connection))
{
    var sql = @"select *
                From Contacts.Departments a
                Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
                Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
                Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
                Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
                Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
                Where a.DepartmentID = @DepartmentID and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";
    ...

    ...
}

when it executes I get an error

Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

The results should only return 45 rows so its not very large. When I run the query in SQL Server Management Studio, it's not an issue and I get the 45 rows.

But in my application if I put a top in the statement then it works:

var sql = @"select top 1000 *
            From Contacts.Departments a
            Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
            Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
            Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
            Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
            Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
            Where a.DepartmentID = @DepartmentID and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";

or if I take out the parameterized query and just add the value directly in the string:

var sql = $@"select *
            From Contacts.Departments a
            Left Outer Join Contacts.ContactMapping b on a.DepartmentID = b.DepartmentID
            Left Outer Join Contacts.Contacts c on b.ContactID = c.ContactID
            Left Outer Join Contacts.Divisions d on b.DivisionID = d.DivisionID
            Left Outer Join Contacts.Emails e on b.EmailID = e.EmailID
            Left Outer Join Contacts.Phones f on b.PhoneID = f.PhoneID
            Where a.DepartmentID = {department_id} and c.IsDeleted = 0 and b.IsDeleted = 0 and f.PhoneTypeID = 1;";

This is so odd because I have not touched the code and suddenly it just failed.  When I test the same in my development machine I can recreate the error and solution above.

I'm kinda in a lose on what to check since, the query works when I modify it to the one of the two above.  But, then why would the original fail when trying to retrieve the data from SQL Server 2016


来源: stackexchange

问:
Modify Apollo React function to use parameters
I'm currently using this function in React:

```<code>function GQLFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  if (data) return <WrappedApp data={data.tag} />;
}
</code>```

I want to make this function re-usable with a parameter so tried:

```<code>function GQLFunc(callingApp) {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  if (data) return <callingApp data={data.tag} />;
}
</code>```

Then called it here:

```<code><GQLFunc callingApp={WrappedApp} />
</code>```

What am I doing wrong here?  I'd also like to add a parameter for data = data.tag

答:
You need to use uppercased name of rendered component, f.e.:</p>

```<code>function GQLFunc(props) {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  let CallingApp = props.callingApp;
  if (data) return <CallingApp data={data.tag} />;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently using this function in React:

function GQLFunc() {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return
Loading...
;
  if (error) return
Error :(
;

  if (data) return <WrappedApp data={data.tag} />;
}

I want to make this function re-usable with a parameter so tried:

function GQLFunc(callingApp) {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return
Loading...
;
  if (error) return
Error :(
;

  if (data) return <callingApp data={data.tag} />;
}

Then called it here:

<GQLFunc callingApp={WrappedApp} />

What am I doing wrong here?  I'd also like to add a parameter for data = data.tag

Body:
You need to use uppercased name of rendered component, f.e.:

function GQLFunc(props) {
  const { loading, error, data } = useQuery(GQLTAGS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  let CallingApp = props.callingApp;
  if (data) return <CallingApp data={data.tag} />;
}


问:
How to ensure R and Python scripts use the same collation?
I am using R 3.6 with dplyr 1.4.2 and Python 3.7 with Pandas 1.0.3.

I need to ensure that both my R and Python scripts can sort the same vector of strings in the same order. However, in my local environment this is not the case:

In R:

```<code>library(dplyr)
df <- data.frame(
      x = c('abc(_01', 'aaa_05', 'abc_01', 'abc_01', 'abc_01', 'abc_01', NA, 'abc_01', 'abc_02', 'abc_02', 'abc_03')
)
df %>% arrange(x)
</code>```

Generates:

```<code>         x
1   aaa_05
2   abc_01
3   abc_01
4   abc_01
5   abc_01
6   abc_01
7   abc_02
8   abc_02
9   abc_03
10 abc(_01
11      NA
</code>```

In Python:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': ['abc(_01', 'aaa_05', 'abc_01', 'abc_01', 'abc_01', 'abc_01', np.nan, 'abc_01', 'abc_02', 'abc_02', 'abc_03']
})
df.sort_values(['x']).reset_index(drop=True)
</code>```

Generates:

```<code>          x
0    aaa_05
1   abc(_01
2    abc_01
3    abc_01
4    abc_01
5    abc_01
6    abc_01
7    abc_02
8    abc_02
9    abc_03
10      NaN
</code>```

I believe this is caused by the fact that Python and R use a different collation.

If this is the case, how can I configure both languages to use the same collation?

答:
To guarantee that both Python and R shells use the same collation set the same collation before creating the dataframes.

e.g.:

In R:

```<code>Sys.setlocale(category="LC_COLLATE", locale="C")
Sys.getlocale(category="LC_COLLATE")
</code>```

[1] "C"

In Python:

```<code>import locale
locale.setlocale(locale.LC_COLLATE, "C")
locale.getlocale(locale.LC_COLLATE)
</code>```

(None, None)

Body:
I am using R 3.6 with dplyr 1.4.2 and Python 3.7 with Pandas 1.0.3.

I need to ensure that both my R and Python scripts can sort the same vector of strings in the same order. However, in my local environment this is not the case:

In R:

library(dplyr)
df <- data.frame(
      x = c('abc(_01', 'aaa_05', 'abc_01', 'abc_01', 'abc_01', 'abc_01', NA, 'abc_01', 'abc_02', 'abc_02', 'abc_03')
)
df %>% arrange(x)

Generates:

         x
1   aaa_05
2   abc_01
3   abc_01
4   abc_01
5   abc_01
6   abc_01
7   abc_02
8   abc_02
9   abc_03
10 abc(_01
11      NA

In Python:

import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': ['abc(_01', 'aaa_05', 'abc_01', 'abc_01', 'abc_01', 'abc_01', np.nan, 'abc_01', 'abc_02', 'abc_02', 'abc_03']
})
df.sort_values(['x']).reset_index(drop=True)

Generates:

          x
0    aaa_05
1   abc(_01
2    abc_01
3    abc_01
4    abc_01
5    abc_01
6    abc_01
7    abc_02
8    abc_02
9    abc_03
10      NaN

I believe this is caused by the fact that Python and R use a different collation.

If this is the case, how can I configure both languages to use the same collation?

Body:
To guarantee that both Python and R shells use the same collation set the same collation before creating the dataframes.

e.g.:

In R:

Sys.setlocale(category="LC_COLLATE", locale="C")
Sys.getlocale(category="LC_COLLATE")

[1] "C"

In Python:

import locale
locale.setlocale(locale.LC_COLLATE, "C")
locale.getlocale(locale.LC_COLLATE)

(None, None)


问:
Import strings from .txt and searching for first numeric character - python
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

```<code>'Elm Street 12'
'Baker Street 143'
</code>```

and output

```<code>'Elm Street 12' , 12
'Baker Street 143' , 14
</code>```

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

答:
```<code>import re
regx = re.compile("^('.+ (\d+)')",re.MULTILINE)

with open('Copie de fileinput.txt','r+') as f:
    mod = regx.sub('\\1 , \\2',f.read())
    f.seek(0,0)
    f.write(mod)
</code>```

Note that I understood that there are quotes ' in the file. I doubt of that, but your output have quotes in it, so my regex has quotes.... You will remove thgem if there are no quotes in fact

Intead of recording data in a flat file, you should better use the pickle module

ContentLicense: CC BY-SA 3.0

Body:
I am a total noob with python (programming in fact) but I hope you can help :)

I have a .txt file with a list of strings containing addresses.

I want to import it to Python and then search for the first numberic character and then create a new column for it...like

input

'Elm Street 12'
'Baker Street 143'

and output

'Elm Street 12' , 12
'Baker Street 143' , 14

and save it to .txt.

I am trying to do if from the windows cmd.

Thank you in advance.

Body:
import re
regx = re.compile("^('.+ (\d+)')",re.MULTILINE)

with open('Copie de fileinput.txt','r+') as f:
    mod = regx.sub('\\1 , \\2',f.read())
    f.seek(0,0)
    f.write(mod)

Note that I understood that there are quotes ' in the file. I doubt of that, but your output have quotes in it, so my regex has quotes.... You will remove thgem if there are no quotes in fact

Intead of recording data in a flat file, you should better use the pickle module


问:
Azure CLI edit Content Type file property
I'm trying to update Content Type property of a file located in my Azure $web blob container using Azure CLI. I'm trying to do this because it's wrongly set and my service-worker.js (for my PWA) needs to have "application/javascript" instead of "text/plain; charset=utf-8" in order to be registered.</p>

答:
When using Azure cli, you should use az storage blob update.

The sample code:

```<code>az storage blob update --container-name xxx --name xxx --account-key xxx --account-name xxx --content-type "application/javascript"
</code>```

Body:
When using Azure cli, you should use az storage blob update.

The sample code:

az storage blob update --container-name xxx --name xxx --account-key xxx --account-name xxx --content-type "application/javascript"


问:
Azure automation account - how to use custom service principal for login instead of run as account?
In Azure automation account - how to use already existing service principal for login in powershell runbook instead of run as account ? </p>

<p>we dont get privilege to create service principal at our organisation ..
so would like to use already existing service principal. </p>

答:
Just use the command below.

```<code>$azureAplicationId ="<client-id>"
$azureTenantId= "<tenant-id>"
$azurePassword = ConvertTo-SecureString "<client-secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
</code>```

Body:
In Azure automation account - how to use already existing service principal for login in powershell runbook instead of run as account ?

we dont get privilege to create service principal at our organisation ..
so would like to use already existing service principal.

Body:
Just use the command below.

$azureAplicationId ="<client-id>"
$azureTenantId= "<tenant-id>"
$azurePassword = ConvertTo-SecureString "<client-secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal


问:
Can I include a variable in an `sh` command in zeppelin?
I'm using Zeppelin with Hadoop on a Spark cluster.

I'd like to run a command to check files on s3 and I'd like to use a variable.

This is my code

```<code>%sh

aws s3 ls s3://my-bucket/my_folder/
</code>```

Can I replace my-bucket/my_folder/ with a variable?

答:
What do you mean by "a variable"? A Python variable? If so, I'm not sure. But if you just want to pull the path out onto another line, you can use a shell variable:</p>

```<code>%sh

export AWS_FOLDER=my-bucket/my_folder/
aws s3 ls s3://$AWS_FOLDER
</code>```

Body:
I'm using Zeppelin with Hadoop on a Spark cluster.

I'd like to run a command to check files on s3 and I'd like to use a variable.

This is my code

%sh

aws s3 ls s3://my-bucket/my_folder/

Can I replace my-bucket/my_folder/ with a variable?

Body:
What do you mean by "a variable"? A Python variable? If so, I'm not sure. But if you just want to pull the path out onto another line, you can use a shell variable:

%sh

export AWS_FOLDER=my-bucket/my_folder/
aws s3 ls s3://$AWS_FOLDER


问:
javascript split / join character within quotes
I have some text and need to replace all instances of a character within quotes " z6 " and replace with " / "
I'm not sure how to include quotes within quotes:

```<code>text = text.split("" z6 "").join("" / "");
</code>```

答:
Escape using backslash

```<code>text = text.split("\" z6 \"").join("\" / \"");
</code>```

Or template strings:

```<code>text = text.split(`" z6 "`).join(`" / "`);
</code>```

Or single quotes

```<code>text = text.split('" z6 "').join('" / "');
</code>```

Body:
I have some text and need to replace all instances of a character within quotes " z6 " and replace with " / "
I'm not sure how to include quotes within quotes:

text = text.split("" z6 "").join("" / "");

Body:
Escape using backslash

text = text.split("\" z6 \"").join("\" / \"");

Or template strings:

text = text.split(`" z6 "`).join(`" / "`);

Or single quotes

text = text.split('" z6 "').join('" / "');


问:
SAP HYBRIS - What could be the reasons for a product to be not available for checkout?
I am trying to checkout a product and it is not showing- what could be the possible causes as to why the product is not available for checkout?</p>

答:
It could be possible due to couple of reasons as mentioned following:

1- Live Stock isn't available from the backend (SAP/Microsoft NAV/ or any other ERP that is used in your application where all the products are actually managed.)
2- FrontEnd issue.
3- Basket/Cart issue

If you tell us more log stack trace then I could help more in this.

Many Thanks


问:
Object discriminated union types are merged when using fallback
I am defining an array that needs to accept types of string, and object.  The object types must contain two properties: name and value.  value must be another object, containing an arbitrary set of key: value pairs.

I am trying to define some of the object types using a discriminated union, so that the properties of value for some specific name are known.  However, there always needs to remain a fallback so that when name is not a known string literal, value can still be any arbitrary set.

Here is what I'm working with so far:

interface IFallbackDef {
    name: string;
    value: object;
}
type ValueDef<TName extends string = string, TOptions extends object = {}> = {
    name: TName;
    value: TOptions;
};
type Merged<TValueDef extends ValueDef> = (string | TValueDef | IFallbackDef)[];

interface ITest1Options {
    foo: string;
    bar: string;
}
interface ITest2Options {
    baz: string;
    qux: string;
}

const test: Merged<
    | ValueDef<'test1', ITest1Options>
    | ValueDef<'test2', ITest2Options>
> = [
    'asdf',
    {
        name: 'test1',
        value: {
            foo: 'asdjfkl',
            bar: 'asdf',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            qux: 'asdfkljsdg' // This should be an error
        }
    },
    {
        name: 'test2',
        value: {
            baz: 'blah',
            qux: 'test',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            foo: 'salfdj' // This should be an error
        }
    },
    {
        name: 'asdf',
        value: {
            /**
             * Intellisense shows both sets of properties,
             * should show none.
             */
        },
    },
]
```

The issue I have is that when I include IFallbackDef in the union, all of the types for the various value properties merge.  If I exclude IFallbackDef, the union works correctly, but the last index of the test array will be an error, because name: 'asdf' is unknown.

I assume that because IFallbackDef uses base types, and the shape is the same as IValueDef, it is merging the types... ?  At the moment, I'm kind of at a loss for how to make this work properly.  A fresh set of eyes would be very appreciated.

答:
If you expand out the Merged type you end up with a type like:

```<code>(
    | string
    | { name: "test1", value: { foo: string, bar: string } }
    | { name: "test2", value: { baz: string, qux: string } }
    | { name: string, value: object }
)[]
</code>```

The problem is that that isn't a discriminated union because of the | { name: string, value: object }.  That line breaks discriminated union checking because string is a match for both 'test1' and 'test2', so TypeScript cannot discriminate.

You need to remove that line (e.g., remove IFallbackDef as you suggested) to get discriminated unions working.  Unfortunately, I don't believe there is a workaround that will let you achieve the goal of having things with a specific key type be of a specific value type, but then having things without one of those specific key types be of a different value type.

Depending on your constraints, one option would be to use a different key for the fallback.  For example:

```<code>interface IFallbackDef {
    not-name: string;
    value: object;
}
</code>```

This will allow for discriminated union type checking of the objects with a name key separate from objects with a not-name key.

Body:
I am defining an array that needs to accept types of string, and object.  The object types must contain two properties: name and value.  value must be another object, containing an arbitrary set of key: value pairs.

I am trying to define some of the object types using a discriminated union, so that the properties of value for some specific name are known.  However, there always needs to remain a fallback so that when name is not a known string literal, value can still be any arbitrary set.

Here is what I'm working with so far:

interface IFallbackDef {
    name: string;
    value: object;
}
type ValueDef<TName extends string = string, TOptions extends object = {}> = {
    name: TName;
    value: TOptions;
};
type Merged<TValueDef extends ValueDef> = (string | TValueDef | IFallbackDef)[];

interface ITest1Options {
    foo: string;
    bar: string;
}
interface ITest2Options {
    baz: string;
    qux: string;
}

const test: Merged<
    | ValueDef<'test1', ITest1Options>
    | ValueDef<'test2', ITest2Options>
> = [
    'asdf',
    {
        name: 'test1',
        value: {
            foo: 'asdjfkl',
            bar: 'asdf',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            qux: 'asdfkljsdg' // This should be an error
        }
    },
    {
        name: 'test2',
        value: {
            baz: 'blah',
            qux: 'test',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            foo: 'salfdj' // This should be an error
        }
    },
    {
        name: 'asdf',
        value: {
            /**
             * Intellisense shows both sets of properties,
             * should show none.
             */
        },
    },
]

The issue I have is that when I include IFallbackDef in the union, all of the types for the various value properties merge.  If I exclude IFallbackDef, the union works correctly, but the last index of the test array will be an error, because name: 'asdf' is unknown.

I assume that because IFallbackDef uses base types, and the shape is the same as IValueDef, it is merging the types... ?  At the moment, I'm kind of at a loss for how to make this work properly.  A fresh set of eyes would be very appreciated.

Body:
If you expand out the Merged type you end up with a type like:

(
    | string
    | { name: "test1", value: { foo: string, bar: string } }
    | { name: "test2", value: { baz: string, qux: string } }
    | { name: string, value: object }
)[]

The problem is that that isn't a discriminated union because of the | { name: string, value: object }.  That line breaks discriminated union checking because string is a match for both 'test1' and 'test2', so TypeScript cannot discriminate.

You need to remove that line (e.g., remove IFallbackDef as you suggested) to get discriminated unions working.  Unfortunately, I don't believe there is a workaround that will let you achieve the goal of having things with a specific key type be of a specific value type, but then having things without one of those specific key types be of a different value type.

Depending on your constraints, one option would be to use a different key for the fallback.  For example:

interface IFallbackDef {
    not-name: string;
    value: object;
}

This will allow for discriminated union type checking of the objects with a name key separate from objects with a not-name key.


问:
PHP strip unknown file extension
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

```<code>basename('path/to/file.php','.php')
</code>```

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

答:
Try this:-</p>

```<code>$path = 'path/to/file.php';

$pathParts = pathinfo( $path );

$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];
</code>```

Title: PHP strip unknown file extension

Body:
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Body:
Try this:-

$path = 'path/to/file.php';

$pathParts = pathinfo( $path );

$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];


问:
Data not Saved in file xml
I have this code in ASP.NET MVC: I want to save the data from datareader in xml file I used this code shown below but I have in the file just two lines:

```<code><?xml version="1.0" encoding="utf-8"?>
<Centre_Commercial />
</code>```

My code in the controller:

```<code>XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement nodecentre = new XElement("Centre_Commercial");
document.Add(nodecentre);

while (dr.Read())
{
    nodecentre.Add(new XElement("Num_Centre", Convert.ToInt32(dr[0].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[1].ToString()));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[2].ToString()).Date));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[3].ToString())));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[4].ToString())));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[5].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[6].ToString()));
    nodecentre.Add(new XElement("Num_Centre", dr[7].ToString()));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[8].ToString())));

    document.Save(Server.MapPath(@"~/App_Data/test.Xml"));
}

con.Close();
</code>```

Thanks in advance

答:
Here is another approach.

MS SQL Server will generate/shape XML based on the desired output. It is a regular SELECT ... statement with the additional FOR XML clause. I am using dynamic SQL because I don't have your database, and I don't know your desired output XML.

(1) You would need just slightly modify the SqlCommand variable to accommodate your stored procedure with parameters. (2) Your stored procedure would need to add FOR XML clause.

c#

```<code>void Main()
{
    const string FILENAME = @"e:\temp\file2.xml";

    using (SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=pubs;Data Source=SPACESHIP"))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT TOP(2) * FROM dbo.authors FOR XML PATH('r'), TYPE, ROOT('root')";
        con.Open();

        using (XmlReader reader = cmd.ExecuteXmlReader())
        {
            XDocument xdoc = XDocument.Load(reader);

            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = false;
            settings.IndentChars = "\t";
            // to remove BOM
            settings.Encoding = new UTF8Encoding(false);

            using (var writer = XmlWriter.Create(FILENAME, settings))
            {
                xdoc.Save(writer);
            }
        }
        Console.WriteLine("File '{0}' has been created.", FILENAME);
    }
}
</code>```

Output XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
   <r>
      <au_id>172-32-1176</au_id>
      <au_lname>White</au_lname>
      <au_fname>Johnson</au_fname>
      <phone>408 496-7223</phone>
      <address>10932 Bigge Rd.</address>
      <city>Menlo Park</city>
      <state>CA</state>
      <zip>94025</zip>
      <contract>1</contract>
   </r>
   <r>
      <au_id>213-46-8915</au_id>
      <au_lname>Green</au_lname>
      <au_fname>Marjorie</au_fname>
      <phone>415 986-7020</phone>
      <address>309 63rd St. #411</address>
      <city>Oakland</city>
      <state>CA</state>
      <zip>94618</zip>
      <contract>1</contract>
   </r>
</root>
</code>```

Title: Data not Saved in file xml

Body:
I have this code in ASP.NET MVC: I want to save the data from datareader in xml file I used this code shown below but I have in the file just two lines:

<?xml version="1.0" encoding="utf-8"?>
<Centre_Commercial />

My code in the controller:

XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement nodecentre = new XElement("Centre_Commercial");
document.Add(nodecentre);

while (dr.Read())
{
    nodecentre.Add(new XElement("Num_Centre", Convert.ToInt32(dr[0].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[1].ToString()));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[2].ToString()).Date));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[3].ToString())));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[4].ToString())));
    nodecentre.Add(new XElement("Num_Centre", Convert.ToDateTime(dr[5].ToString())));
    nodecentre.Add(new XElement("Num_Centre", dr[6].ToString()));
    nodecentre.Add(new XElement("Num_Centre", dr[7].ToString()));
    nodecentre.Add(new XElement("Num_Centre", int.Parse(dr[8].ToString())));

    document.Save(Server.MapPath(@"~/App_Data/test.Xml"));
}

con.Close();

Thanks in advance

Body:
Here is another approach.

MS SQL Server will generate/shape XML based on the desired output. It is a regular SELECT ... statement with the additional FOR XML clause. I am using dynamic SQL because I don't have your database, and I don't know your desired output XML.

(1) You would need just slightly modify the SqlCommand variable to accommodate your stored procedure with parameters. (2) Your stored procedure would need to add FOR XML clause.

c#

void Main()
{
    const string FILENAME = @"e:\temp\file2.xml";

    using (SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=pubs;Data Source=SPACESHIP"))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT TOP(2) * FROM dbo.authors FOR XML PATH('r'), TYPE, ROOT('root')";
        con.Open();

        using (XmlReader reader = cmd.ExecuteXmlReader())
        {
            XDocument xdoc = XDocument.Load(reader);

            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = false;
            settings.IndentChars = "\t";
            // to remove BOM
            settings.Encoding = new UTF8Encoding(false);

            using (var writer = XmlWriter.Create(FILENAME, settings))
            {
                xdoc.Save(writer);
            }
        }
        Console.WriteLine("File '{0}' has been created.", FILENAME);
    }
}

Output XML file

<?xml version="1.0" encoding="utf-8"?>
<root>
   <r>
      <au_id>172-32-1176</au_id>
      <au_lname>White</au_lname>
      <au_fname>Johnson</au_fname>
      <phone>408 496-7223</phone>
      <address>10932 Bigge Rd.</address>
      <city>Menlo Park</city>
      <state>CA</state>
      <zip>94025</zip>
      <contract>1</contract>
   </r>
   <r>
      <au_id>213-46-8915</au_id>
      <au_lname>Green</au_lname>
      <au_fname>Marjorie</au_fname>
      <phone>415 986-7020</phone>
      <address>309 63rd St. #411</address>
      <city>Oakland</city>
      <state>CA</state>
      <zip>94618</zip>
      <contract>1</contract>
   </r>
</root>


问:
ExpandedTile - BoxConstraints forces an infinite width
I'm creating an app and when I use the ExpandedTile it gives this error. can you guys help me?

════════ Exception caught by rendering library ════════

The following assertion was thrown during performLayout():
BoxConstraints forces an infinite width.

```<code>class PlayersTile extends StatelessWidget {

  final PlayersData data;

  PlayersTile(this.data);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        child: Row(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Image.network(
                data.image,
                fit: BoxFit.cover,
                height: 150.0,
              ),
            ),
            Flexible(
              flex: 1,
              child: Container(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      data.name,
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 15.0,
                      ),
                    ),
                    Text(
                      "DT\$ ${data.points.toString()}",
                      style: TextStyle(
                          color: Theme.of(context).primaryColor,
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      ),
                    ),
                  ],
                ),
              ),
            ),
            ExpansionTile(
              children: <Widget>[
                Text("teste")
              ],
            )
          ],
        ),
      ),
    );
  }
}
</code>```

答:
You can copy paste run full code below

You can wrap ExpansionTile with Flexible just like you do in Image.network and Container

```<code>Flexible(
          flex: 1,
          child: ExpansionTile(
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';

class PlayersData {
  String name;
  String image;
  int points;

  PlayersData({this.name, this.image, this.points});
}

class PlayersTile extends StatelessWidget {
  final PlayersData data;

  PlayersTile(this.data);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        child: Row(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Image.network(
                data.image,
                fit: BoxFit.cover,
                height: 150.0,
              ),
            ),
            Flexible(
              flex: 1,
              child: Container(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      data.name,
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 15.0,
                      ),
                    ),
                    Text(
                      "DT\$ ${data.points.toString()}",
                      style: TextStyle(
                          color: Theme.of(context).primaryColor,
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            Flexible(
              flex: 1,
              child: ExpansionTile(
                children: <Widget>[Text("teste")],
              ),
            )
          ],
        ),
      ),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            PlayersTile(PlayersData(
                name: "abc",
                image: "https://picsum.photos/250?image=9",
                points: 10)),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I'm creating an app and when I use the ExpandedTile it gives this error. can you guys help me?

════════ Exception caught by rendering library ════════

The following assertion was thrown during performLayout():
BoxConstraints forces an infinite width.

class PlayersTile extends StatelessWidget {

  final PlayersData data;

  PlayersTile(this.data);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        child: Row(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Image.network(
                data.image,
                fit: BoxFit.cover,
                height: 150.0,
              ),
            ),
            Flexible(
              flex: 1,
              child: Container(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      data.name,
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 15.0,
                      ),
                    ),
                    Text(
                      "DT\$ ${data.points.toString()}",
                      style: TextStyle(
                          color: Theme.of(context).primaryColor,
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      ),
                    ),
                  ],
                ),
              ),
            ),
            ExpansionTile(
              children: <Widget>[
                Text("teste")
              ],
            )
          ],
        ),
      ),
    );
  }
}

Body:
You can copy paste run full code below

You can wrap ExpansionTile with Flexible just like you do in Image.network and Container

Flexible(
          flex: 1,
          child: ExpansionTile(

working demo

full code

import 'package:flutter/material.dart';

class PlayersData {
  String name;
  String image;
  int points;

  PlayersData({this.name, this.image, this.points});
}

class PlayersTile extends StatelessWidget {
  final PlayersData data;

  PlayersTile(this.data);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        child: Row(
          children: <Widget>[
            Flexible(
              flex: 1,
              child: Image.network(
                data.image,
                fit: BoxFit.cover,
                height: 150.0,
              ),
            ),
            Flexible(
              flex: 1,
              child: Container(
                padding: EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      data.name,
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 15.0,
                      ),
                    ),
                    Text(
                      "DT\$ ${data.points.toString()}",
                      style: TextStyle(
                          color: Theme.of(context).primaryColor,
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            Flexible(
              flex: 1,
              child: ExpansionTile(
                children: <Widget>[Text("teste")],
              ),
            )
          ],
        ),
      ),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            PlayersTile(PlayersData(
                name: "abc",
                image: "https://picsum.photos/250?image=9",
                points: 10)),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
How do I set a default image to a canvas?
I have a PNG image (in my database) that I want to load into my page in my canvas. I have no idea how to do it. I couldn't figure out how to load the image as a ImageBitmap or anything compatible with canvas. How do I give canvas the bytes and tell it that it's using the png format/set the mime to png?</p>

答:
I would split this into two parts: (1) You'll want to load an image into something an ImageBitmap can use, and (2) you'll want to create the ImageBitmap to put this into your canvas.

This could look something like this:

```<code>const fileName = 'resources/image.png';
const fetched = await fetch(fileName); // Retrieve an image file.
const blob = await fetched.blob(); // Get a blob to represent this image.

const imageBitmap = await createImageBitmap(blob); // Create an imageBitmap from this blob.
const canvas = document.getElementById('canvas'); // Make sure your HTML contains a <canvas> element.
const context = canvas.getContext('2d');

context.drawImage(imageBitmap, 0,0); // Draw this image onto the canvas.

</code>```

Body:
I would split this into two parts: (1) You'll want to load an image into something an ImageBitmap can use, and (2) you'll want to create the ImageBitmap to put this into your canvas.

This could look something like this:

const fileName = 'resources/image.png';
const fetched = await fetch(fileName); // Retrieve an image file.
const blob = await fetched.blob(); // Get a blob to represent this image.

const imageBitmap = await createImageBitmap(blob); // Create an imageBitmap from this blob.
const canvas = document.getElementById('canvas'); // Make sure your HTML contains a <canvas> element.
const context = canvas.getContext('2d');

context.drawImage(imageBitmap, 0,0); // Draw this image onto the canvas.


问:
Flutter web view forms not working properly
I am using flutter web view for loading a form to the application. But the dropdown menus, date pickers and file selectors not working properly.</p>

答:
You can try my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

Dropdown menus are working, also date pickers and file selectors (for example, you can use also camera to get images)!


答:
You can use single quotes and double quotes interchangeably. To solve your specific problem:

text = text.split('" z6 "').join('" / "');
```

Title: javascript split / join character within quotes


问:
Creating XML file with a specific order or attributes using Python
I am trying to create a xml file using lxml, I am well aware that the order of attributes in xml doesn't matter but still I am searching for a method to prevent the attributes in a specific order.

I also tried minidom and that didn't workout too.

In lxml I have the following code:

```<code>from lxml import etree as ET
from collections import OrderedDict
root = ET.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
ET.tostring(root)
</code>```

This part gives the following ouput with the attributes in the order I wanted since I used OrderedDict here:

```<code><Root id="0" start="0" end="200"/>
</code>```

Then I created a Child using the same method:

```<code>child1 = ET.Element("sentence", OrderedDict([("id","0"),("start","0"),("end","255")]))
root.append(child1)
xml_str = ET.tostring(root, pretty_print=True)
print(xml_str)
</code>```

Printing the xml_str gives output as I expect:

```<code><Root id="0" start="0" end="200">\n  <sentence id="0" start="0" end="255"/>\n</Root>
</code>```

But when it comes to writing it down to a xml file:

```<code>with open('op.xml', 'wb') as f:
  f.write(xml_str)
</code>```

The ouput isn't same when written to op.xml file:

```<code><?xml version="1.0"?>

<Root end="200" start="0" id="0">
       <sentence end="255" start="0" id="0"/>
</Root>
</code>```

Clearly seen that the attributes order have changed, is there any way I can get the ouput as I expect i.e attribute orders being maintained.

I have tried using minidom too, but there also it didn't work even after referring to:
Preserve order of attributes when modifying with minidom

答:
Here is a library, which is good at extracting data, not very good at modifying XML files, but also can basically meet your needs.

```<code>from simplified_scrapy import SimplifiedDoc, utils, req
doc = SimplifiedDoc("<Root></Root>")
doc.Root.setAttrs({"id":"0","start":"0","end":"200"})
doc.Root.setContent("<sentence />")
doc.sentence.setAttrs({"id":"0","start":"0","end":"200"})
utils.saveFile("op.xml",doc.html)
</code>```

Result:

```<code><Root id="0" start="0" end="200"><sentence id="0" start="0" end="200" /></Root>
</code>```

Body:
I am trying to create a xml file using lxml, I am well aware that the order of attributes in xml doesn't matter but still I am searching for a method to prevent the attributes in a specific order.

I also tried minidom and that didn't workout too.

In lxml I have the following code:

from lxml import etree as ET
from collections import OrderedDict
root = ET.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
ET.tostring(root)

This part gives the following ouput with the attributes in the order I wanted since I used OrderedDict here:

<Root id="0" start="0" end="200"/>

Then I created a Child using the same method:

child1 = ET.Element("sentence", OrderedDict([("id","0"),("start","0"),("end","255")]))
root.append(child1)
xml_str = ET.tostring(root, pretty_print=True)
print(xml_str)

Printing the xml_str gives output as I expect:

<Root id="0" start="0" end="200">\n  <sentence id="0" start="0" end="255"/>\n</Root>

But when it comes to writing it down to a xml file:

with open('op.xml', 'wb') as f:
  f.write(xml_str)

The ouput isn't same when written to op.xml file:

<?xml version="1.0"?>

<Root end="200" start="0" id="0">
       <sentence end="255" start="0" id="0"/>
</Root>

Clearly seen that the attributes order have changed, is there any way I can get the ouput as I expect i.e attribute orders being maintained.

I have tried using minidom too, but there also it didn't work even after referring to:
Preserve order of attributes when modifying with minidom

Body:
Here is a library, which is good at extracting data, not very good at modifying XML files, but also can basically meet your needs.

from simplified_scrapy import SimplifiedDoc, utils, req
doc = SimplifiedDoc("<Root></Root>")
doc.Root.setAttrs({"id":"0","start":"0","end":"200"})
doc.Root.setContent("<sentence />")
doc.sentence.setAttrs({"id":"0","start":"0","end":"200"})
utils.saveFile("op.xml",doc.html)

Result:

<Root id="0" start="0" end="200"><sentence id="0" start="0" end="200" /></Root>


问:
Typescript type where an object consists of exactly a single property of a set of possible properties
I'm trying to model a particular pattern with the type system where an object consists of exactly a single property of a set of possible properties.

In other words, the type would be a partial type but with only one property allowed.

interface PossibleProperties {
  cat?: AllPropsOfSameType;
  dog?: AllPropsOfSameType;
  cow?: AllPropsOfSameType;
}

interface ShouldBeExactlyOneOfPossibleProperties {
  [P in keyof PossibleProperties]: AllPropsOfSameType; // Wupz, this allows for 0 or more...
}
```

<p>I've seen solutions for requiring at least one property:</p>

<pre class="lang-js prettyprint-override"><code>type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]
</code>```

But I need something like AtMostOne<T, U = {[K in keyof T]: Pick<T, K> }> or ExactlyOne<T, U = {[K in keyof T]: Pick<T, K> }> which could possibly be the intersection type of AtMostOne and AtLeastOne

Any ideas if this is possible?

答:
Answering my own question, but the credit is due to https://github.com/keithlayne as he came up with the solution on https://gitter.im/Microsoft/TypeScript

Credit is also due to https://github.com/fatcerberus who came up with the initial reasoning.

I’m pretty sure there’s no way to model that in TS, simply because of how structural typing works. You can always have extra properties that the type doesn’t explicitly list

Even if you make a union of single-property types, it’s no guarantee that you don’t have any of the others

Hmm... I might be wrong. If you could make a type that maps over the keys and makes a union like {a:string,b:never} | {a:never,b:string} then that could work. Not sure how you’d do it though

Here goes Keith's answer:

type Explode<T> = keyof T extends infer K
    ? K extends unknown
    ? { [I in keyof T]: I extends K ? T[I] : never }
    : never
    : never;
```
<p>in action</p>
<p>This is probably easier to grok:</p>
<pre class="lang-js prettyprint-override"><code>type Split<T, K extends keyof T> = K extends unknown ? { [I in keyof T]: I extends K ? T[I] : never } : never;
type Explode<T> = Split<T, keyof T>;
</code>```

Basically, map over T for each member of keyof T, and return the union.

Body:
I'm trying to model a particular pattern with the type system where an object consists of exactly a single property of a set of possible properties.

In other words, the type would be a partial type but with only one property allowed.

interface PossibleProperties {
  cat?: AllPropsOfSameType;
  dog?: AllPropsOfSameType;
  cow?: AllPropsOfSameType;
}

interface ShouldBeExactlyOneOfPossibleProperties {
  [P in keyof PossibleProperties]: AllPropsOfSameType; // Wupz, this allows for 0 or more...
}

I've seen solutions for requiring at least one property:

type AtLeastOne<T, U = {[K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U]

But I need something like AtMostOne<T, U = {[K in keyof T]: Pick<T, K> }> or ExactlyOne<T, U = {[K in keyof T]: Pick<T, K> }> which could possibly be the intersection type of AtMostOne and AtLeastOne

Any ideas if this is possible?

Body:
Answering my own question, but the credit is due to https://github.com/keithlayne as he came up with the solution on https://gitter.im/Microsoft/TypeScript

Credit is also due to https://github.com/fatcerberus who came up with the initial reasoning.

I’m pretty sure there’s no way to model that in TS, simply because of how structural typing works. You can always have extra properties that the type doesn’t explicitly list

Even if you make a union of single-property types, it’s no guarantee that you don’t have any of the others

Hmm... I might be wrong. If you could make a type that maps over the keys and makes a union like {a:string,b:never} | {a:never,b:string} then that could work. Not sure how you’d do it though

Here goes Keith's answer:

type Explode<T> = keyof T extends infer K
    ? K extends unknown
    ? { [I in keyof T]: I extends K ? T[I] : never }
    : never
    : never;

in action

This is probably easier to grok:

type Split<T, K extends keyof T> = K extends unknown ? { [I in keyof T]: I extends K ? T[I] : never } : never;
type Explode<T> = Split<T, keyof T>;

Basically, map over T for each member of keyof T, and return the union.


问:
Kafka stream sum data after windowed group
I have a warehouse application, in which I need to calculate total stock on hourly basis.

All item movement data are sent to kafka stream (addition / removal).

This means, I can get the hourly aggregated movement using windowed kafka stream, like this

```<code>        sourceStream
                .mapValues((k, v) -> v.getType().equalsIgnoreCase("ADD") ? v.getQuantity() : -1 * v.getQuantity())
                .groupByKey().windowedBy(TimeWindows.of(Duration.ofHours(1)))
                .reduce(Long::sum, Materialized.with(stringSerde, longSerde)).toStream().to("hourly-movement");
</code>```

But how can I get the total stock based on this aggregated result?

For example, with this data set, assuming the starting stock is zero:

09:15 : +50 item

09:20 : +10 item

09:50 : +10 item

10:35 : -40 item

10:55 : -20 item

The aggregated stream result (by window) is this :

item@09:00/10:00 : 70

item@10:00/11:00 : -60

I need to create hourly chart in frontend, means I need this data set:

item@09:00/10:00 : 70 (initial + movement in one hour)

item@10:00/11:00 : 10 (item at 10:00 + movement in next hour, which is 70 - 60)

How can I get such data set? The original source stream is from stream-logistic-movement.

答:
It seem you don't want to do a windowed aggregation, but an overall aggregation but emit the current result hourly.

Thus, you should not use a windowBy() at all, but just a "regular" non-windowed aggregation. After the aggregation, you could use suppress() to emit the result on regular intervals: https://docs.confluent.io/current/streams/javadocs/org/apache/kafka/streams/kstream/Suppressed.html#untilTimeLimit-java.time.Duration-org.apache.kafka.streams.kstream.Suppressed.BufferConfig-

Body:
I have a warehouse application, in which I need to calculate total stock on hourly basis.

All item movement data are sent to kafka stream (addition / removal).

This means, I can get the hourly aggregated movement using windowed kafka stream, like this

        sourceStream
                .mapValues((k, v) -> v.getType().equalsIgnoreCase("ADD") ? v.getQuantity() : -1 * v.getQuantity())
                .groupByKey().windowedBy(TimeWindows.of(Duration.ofHours(1)))
                .reduce(Long::sum, Materialized.with(stringSerde, longSerde)).toStream().to("hourly-movement");

But how can I get the total stock based on this aggregated result?

For example, with this data set, assuming the starting stock is zero:

09:15 : +50 item

09:20 : +10 item

09:50 : +10 item

10:35 : -40 item

10:55 : -20 item

The aggregated stream result (by window) is this :

item@09:00/10:00 : 70

item@10:00/11:00 : -60

I need to create hourly chart in frontend, means I need this data set:

item@09:00/10:00 : 70 (initial + movement in one hour)

item@10:00/11:00 : 10 (item at 10:00 + movement in next hour, which is 70 - 60)

How can I get such data set? The original source stream is from stream-logistic-movement.


问:
Making recursive function more elegant
I've been working to hone my understanding of recursion [and become a better programmer in general]. Today a wrote some code to flatten a tuple of tuples. The code is as follows:

```<code>def recursive_tuple_flatten(tuple_list):
    if type(tuple_list) is tuple:
        if type(tuple_list[0]) is tuple:
            list_of_lists = [list(tuple_list[0]), tuple_list[1:]]
            return recursive_tuple_flatten([i for j in list_of_lists for i in j])
        else:
            return recursive_tuple_flatten(list(tuple_list))
    else:
        if type(tuple_list[-1]) is tuple:
            list_of_lists = [tuple_list[:-1], list(tuple_list[-1])]
            return recursive_tuple_flatten([i for j in list_of_lists for i in j])
        else:
            return tuple_list

k = ((1,(2)),(3,(4,5)))
recursive_tuple_flatten(k)
</code>```

The code works, but I'd really appreciate any advise and coaching to help me improve this code and make it more elegant. Have a great day!

答:
Divide and conquer is a common technique when coming up with a recursive algorithm. In your example prompt, the function should just iterate over all the values in a list and call itself with an array size that is slight smaller. Eventually it will reach a size of 0 (a single value) and you're done.

I haven't written Python code in a long time. Assuming this is a general question on recursive algorithms, this would be how it looks in JavaScript (should be self-explanatory - think of it as pseudocode):

function flatten(arr) {
  if (!Array.isArray(arr)) return [arr];
  return arr.reduce((acc, cur) => [...acc, ...flatten(cur)], []);
}

const input = [[1,[2]],[3,[4,5]]];
const output = flatten([[1,[2]],[3,[4,5]]]);

console.log(output);```

Let me know if you need a solid example in Python.

These steps might help you in coming up with a elegant recursive solution to a problem:

Find a way to reduce the input size n. By induction you can assume your function is already implemented for n - 1

Figure out how to combine the results of smaller input sizes together. This is the "divide and conquer" part.

Determine the base case. Your recursive function needs to stop at some point.

Title: Making recursive function more elegant

Body:
I've been working to hone my understanding of recursion [and become a better programmer in general]. Today a wrote some code to flatten a tuple of tuples. The code is as follows:

def recursive_tuple_flatten(tuple_list):
    if type(tuple_list) is tuple:
        if type(tuple_list[0]) is tuple:
            list_of_lists = [list(tuple_list[0]), tuple_list[1:]]
            return recursive_tuple_flatten([i for j in list_of_lists for i in j])
        else:
            return recursive_tuple_flatten(list(tuple_list))
    else:
        if type(tuple_list[-1]) is tuple:
            list_of_lists = [tuple_list[:-1], list(tuple_list[-1])]
            return recursive_tuple_flatten([i for j in list_of_lists for i in j])
        else:
            return tuple_list

k = ((1,(2)),(3,(4,5)))
recursive_tuple_flatten(k)

The code works, but I'd really appreciate any advise and coaching to help me improve this code and make it more elegant. Have a great day!

Body:
Divide and conquer is a common technique when coming up with a recursive algorithm. In your example prompt, the function should just iterate over all the values in a list and call itself with an array size that is slight smaller. Eventually it will reach a size of 0 (a single value) and you're done.

I haven't written Python code in a long time. Assuming this is a general question on recursive algorithms, this would be how it looks in JavaScript (should be self-explanatory - think of it as pseudocode):

function flatten(arr) {
  if (!Array.isArray(arr)) return [arr];
  return arr.reduce((acc, cur) => [...acc, ...flatten(cur)], []);
}

const input = [[1,[2]],[3,[4,5]]];
const output = flatten([[1,[2]],[3,[4,5]]]);

console.log(output);

Let me know if you need a solid example in Python.

These steps might help you in coming up with a elegant recursive solution to a problem:

Find a way to reduce the input size n. By induction you can assume your function is already implemented for n - 1

Figure out how to combine the results of smaller input sizes together. This is the "divide and conquer" part.

Determine the base case. Your recursive function needs to stop at some point.


问:
trouble in adding twbs:bootstrap into Meteor

C:\Users\HP\demo_app>meteor add twbs:bootstrap  => Errors while adding
  packages:

While selecting package versions: error: Potentially incompatible
  change required to top-level dependency: jquery 1.11.11, was
  3.0.0. Constraints on package "jquery":
  * jquery@1.11.9 || 3.0.0 <- blaze 2.3.4 <- blaze-html-templates 1.1.2
  * jquery@1.0.1 <- twbs:bootstrap 3.3.6

To allow potentially incompatible changes to top-level dependencies,
  you must pass
  --allow-incompatible-update on the command line.

答:
I got same error yesterday while adding bootstrap package to meteor. After research what I did was....

First,removed existing version of jquery....

meteor remove jquery 3.0.0

then,added old version of jquery...

meteor add jquery@1.11.11

then,added bootstrap...

meteor add twbs:bootstrap

This steps worked for me.You can try them.Please let me know if it works for you also.
Thanks.


问:
How to connect to EC2 instance running asp.net core
I have a static IP address attached to my ec2 instance and it's running a web server inside a container using asp.net core with the following Dockerfile:

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WebApplication1.csproj", ""]
RUN dotnet restore "./WebApplication1.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "WebApplication1.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApplication1.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]
</code>```

The debug info says:

```<code>info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:80
</code>```

But how can I connect to it in my browser?

答: Found the answer, big thanks to this guy where I found out Kestrel binds specifically to localhost and I need to explicitly set the url to 0.0.0.0:80 in order to receive outside web traffic. I did this by adding an environment variable (but you can also do cmd line arg) called ASPNETCORE_URL=0.0.0.0:80

Body:
I have a static IP address attached to my ec2 instance and it's running a web server inside a container using asp.net core with the following Dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WebApplication1.csproj", ""]
RUN dotnet restore "./WebApplication1.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "WebApplication1.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApplication1.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]

The debug info says:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://[::]:80

But how can I connect to it in my browser?


问:
Getting the result of jquery .post() function
I need to find out how to access "data" variable outside of the post function.  It will return either valid or invalid so I can finish the main function logic.

Is this the right way to do it:

```<code>$('#form_choose_methods').submit(function(){
    var voucher_code = $('#voucher_code').val();
    var check = $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
    });
    alert(check);
    return false;
});
</code>```

check seems to be the object, but I want to know how to access result of it.

答:
You can access the response in the success callback you use

```<code> $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
       // you can access the response in here
       alert(data);
    });
</code>```

Ajax calls are asynchronous, so you will only have access to the result from the callback whenever it completes..

Body:
I need to find out how to access "data" variable outside of the post function.  It will return either valid or invalid so I can finish the main function logic.

Is this the right way to do it:

$('#form_choose_methods').submit(function(){
    var voucher_code = $('#voucher_code').val();
    var check = $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
    });
    alert(check);
    return false;
});

check seems to be the object, but I want to know how to access result of it.

Body:
You can access the response in the success callback you use

 $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
       // you can access the response in here
       alert(data);
    });

Ajax calls are asynchronous, so you will only have access to the result from the callback whenever it completes..


问:
Is it possible to redirect the users to Huawei App Gallery using with Deferred Links?
Since new generation device of Huawei does not support google services, there is only one app market for that devices is App Gallery.
Currently, i am using "Deferred Deep Links" for App store and Play store to route the users who didn't installed the app when link is opened.

Is there any possibility to route non-gms Huawei phone users to App Gallery to download the app?

答: The App Linking function of our HMS phone already supports a similar function.</p>


问:
Flutter: Favourites feature with SQLite - Issue with first load
I have created a details page and using the example from the Medium article. I am successfully able to perform CRUD operations.

When I load the DetailsPage, I want to check if the table has the ID and if yes, then make the favourites icon yellow.

```<code>class _DetailPageState extends State<DetailPage> {
  bool isFav = false;
  MyImpData myData;
  _DetailPageState(this.myData);

  // reference to our single class that manages the database
  final dbHelper = DatabaseHelper.instance;

  @override
  Widget build(BuildContext context) {
    Widget heading = new Container(...),);

    Widget middleSection = new Expanded(...);

    Widget bottomBanner = new Container(...),);

    Widget body = new Column(...);

    final makeBottom = Container(
      height: 55.0,
      child: BottomAppBar(
        color: Color.fromRGBO(58, 66, 86, 1.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            IconButton(
              icon: buildIcon(),
              onPressed: () {
                _insertOrDelete(myData.id);
              },
            ),
            IconButton(
              icon: Icon(Icons.share, color: Colors.white),
              onPressed: () => share(context, myData),
            )
          ],
        ),
      ),
    );

    return Scaffold(
      appBar: AppBar(...),
      body: Container(...),
      bottomNavigationBar: makeBottom,
    );
  }

  Icon buildIcon() {
    if (isFav) {
      return Icon(Icons.favorite, color: Colors.yellow);
    } else {
      return Icon(Icons.favorite_border, color: Colors.white);
    }
  }

  void share(BuildContext context, MyImpData myData) {...}

  void _insert() async {
    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName: myData.name,
      DatabaseHelper.columnDesc: myData.desc,
      DatabaseHelper.columnLoc: myData.location,
      DatabaseHelper.columnId: myData.id
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _checkFav(String checkId) async {
    final rowsPresent = await dbHelper.queryForFav(checkId);
    if (rowsPresent > 0) {
      print('success');
      isFav = true;
    } else {
      print('Nothing found so inserting you dodo');
      isFav = false;
      //_insert();
    }
    //rowsPresent.forEach((row) => print(row));
  }

  void _insertOrDelete(String id) async {
    final rowsPresent = await dbHelper.queryForFav(id);
    if (rowsPresent > 0) {
      print('Its favourite and removing it');
      _delete();
      isFav = false;
    } else {
      print('Nothing found so inserting you dodo');
      _insert();
      isFav = true;
    }
  }

  void _delete() async {...}
}
</code>```

The DBHelper.dart file has the following for queryForFav(id)

```<code>//Raw query to check if it is in the favourites
  Future<int> queryForFav(String checkId) async {
    Database db = await instance.database;
    int noOfRows = 0;
    try {
      noOfRows = Sqflite.firstIntValue(await db.rawQuery(
          'SELECT COUNT(*) FROM $table WHERE $columnId = ?',
          ['$checkId']));
    } catch (e) {
      print(e);
    }
    return noOfRows;
  }
</code>```

My attempt was to create a flag isFav and set it when I get to check the DB. However, that is always false as there is no query executed. Only when I press the button the actual DB query is executed.
Any help would be appreciated.

答:
Change your IconButton(child, buildIcon(), ...) for this class

```<code>class FavIconWidget extends StatefulWidget {
  final MyImpData myData;

  FavIconWidget(this.myData);

  @override
  _FavIconWidgetState createState() => _FavIconWidgetState();
}

class _FavIconWidgetState extends State<FavIconWidget> {
  final dbHelper = DatabaseHelper.instance;

  Future<bool> get isFav async {
    final rowsPresent = await dbHelper.queryForFav(widget.myData.id);
    if (rowsPresent > 0) {
      print('Its favourite and removing it');
      await _delete();
      return false;
    } else {
      print('Nothing found so inserting you dodo');
      await _insert();
      return true;
    }
  }

  void _insert() async {

    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName: widget.myData.name,
      DatabaseHelper.columnDesc: widget.myData.desc,
      DatabaseHelper.columnLoc: widget.myData.location,
      DatabaseHelper.columnId: widget.myData.id
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _delete() async {}

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
        future: isFav,
        initialData: false,// you can define an initial value while the db returns the real value
        builder: (context, snapshot) {
          if(snapshot.hasError) return const Icon(Icons.error, color: Colors.red); //just in case the db return an error
          return IconButton(
            icon: snapshot.data ? const Icon(Icons.favorite, color: Colors.yellow) :
             Icon(Icons.favorite, color: Colors.white),
            onPressed: () => setState(() {})
          );
        });
  }

}
</code>```

basically it wraps the icon with a FutureBuilder, an special widget that awaits for a future value (in this case the return of a DB row), you can give it an initial value while waiting (in this case I gave it a false), but you can ignore it and check if there is a value with snapshot.hasData and return a CircularProgressIndicator to tell the user you're fetching the data

```<code>return FutureBuilder<bool>(
        future: isFav,
        initialData: false,// you can define an initial value while the db returns the real value
        builder: (context, snapshot) {
          if(snapshot.hasError) return const Icon(Icons.error, color: Colors.red); //just in case the db return an error
          if(snapshot.hasData)
          return IconButton(
            icon: snapshot.data ? const Icon(Icons.favorite, color: Colors.yellow) :
             Icon(Icons.favorite, color: Colors.white),
            onPressed: () => setState(() {})
          );

          return CircularProgressIndicator(); //if there is no initial value and the future is not yet complete
        });
</code>```

I made this StatefulWidget so when you press the button it setState and re-run the isFav future to check again the DB (but it just rebuilds this iconbutton, not your whole page). If you wanted to update your whole page according to that isFav value instead of just the icon then you will have to use that FutureBuilder in all the body of your Scaffold, or at least above in your widget tree where you really need to check that value

Body:
I have created a details page and using the example from the Medium article. I am successfully able to perform CRUD operations.

When I load the DetailsPage, I want to check if the table has the ID and if yes, then make the favourites icon yellow.

class _DetailPageState extends State<DetailPage> {
  bool isFav = false;
  MyImpData myData;
  _DetailPageState(this.myData);

  // reference to our single class that manages the database
  final dbHelper = DatabaseHelper.instance;

  @override
  Widget build(BuildContext context) {
    Widget heading = new Container(...),);

    Widget middleSection = new Expanded(...);

    Widget bottomBanner = new Container(...),);

    Widget body = new Column(...);

    final makeBottom = Container(
      height: 55.0,
      child: BottomAppBar(
        color: Color.fromRGBO(58, 66, 86, 1.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            IconButton(
              icon: buildIcon(),
              onPressed: () {
                _insertOrDelete(myData.id);
              },
            ),
            IconButton(
              icon: Icon(Icons.share, color: Colors.white),
              onPressed: () => share(context, myData),
            )
          ],
        ),
      ),
    );

    return Scaffold(
      appBar: AppBar(...),
      body: Container(...),
      bottomNavigationBar: makeBottom,
    );
  }

  Icon buildIcon() {
    if (isFav) {
      return Icon(Icons.favorite, color: Colors.yellow);
    } else {
      return Icon(Icons.favorite_border, color: Colors.white);
    }
  }

  void share(BuildContext context, MyImpData myData) {...}

  void _insert() async {
    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName: myData.name,
      DatabaseHelper.columnDesc: myData.desc,
      DatabaseHelper.columnLoc: myData.location,
      DatabaseHelper.columnId: myData.id
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _checkFav(String checkId) async {
    final rowsPresent = await dbHelper.queryForFav(checkId);
    if (rowsPresent > 0) {
      print('success');
      isFav = true;
    } else {
      print('Nothing found so inserting you dodo');
      isFav = false;
      //_insert();
    }
    //rowsPresent.forEach((row) => print(row));
  }

  void _insertOrDelete(String id) async {
    final rowsPresent = await dbHelper.queryForFav(id);
    if (rowsPresent > 0) {
      print('Its favourite and removing it');
      _delete();
      isFav = false;
    } else {
      print('Nothing found so inserting you dodo');
      _insert();
      isFav = true;
    }
  }

  void _delete() async {...}
}

The DBHelper.dart file has the following for queryForFav(id)

//Raw query to check if it is in the favourites
  Future<int> queryForFav(String checkId) async {
    Database db = await instance.database;
    int noOfRows = 0;
    try {
      noOfRows = Sqflite.firstIntValue(await db.rawQuery(
          'SELECT COUNT(*) FROM $table WHERE $columnId = ?',
          ['$checkId']));
    } catch (e) {
      print(e);
    }
    return noOfRows;
  }

My attempt was to create a flag isFav and set it when I get to check the DB. However, that is always false as there is no query executed. Only when I press the button the actual DB query is executed.
Any help would be appreciated.

Body:
Change your IconButton(child, buildIcon(), ...) for this class

class FavIconWidget extends StatefulWidget {
  final MyImpData myData;

  FavIconWidget(this.myData);

  @override
  _FavIconWidgetState createState() => _FavIconWidgetState();
}

class _FavIconWidgetState extends State<FavIconWidget> {
  final dbHelper = DatabaseHelper.instance;

  Future<bool> get isFav async {
    final rowsPresent = await dbHelper.queryForFav(widget.myData.id);
    if (rowsPresent > 0) {
      print('Its favourite and removing it');
      await _delete();
      return false;
    } else {
      print('Nothing found so inserting you dodo');
      await _insert();
      return true;
    }
  }

  void _insert() async {

    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnName: widget.myData.name,
      DatabaseHelper.columnDesc: widget.myData.desc,
      DatabaseHelper.columnLoc: widget.myData.location,
      DatabaseHelper.columnId: widget.myData.id
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _delete() async {}

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
        future: isFav,
        initialData: false,// you can define an initial value while the db returns the real value
        builder: (context, snapshot) {
          if(snapshot.hasError) return const Icon(Icons.error, color: Colors.red); //just in case the db return an error
          return IconButton(
            icon: snapshot.data ? const Icon(Icons.favorite, color: Colors.yellow) :
             Icon(Icons.favorite, color: Colors.white),
            onPressed: () => setState(() {})
          );
        });
  }

}

basically it wraps the icon with a FutureBuilder, an special widget that awaits for a future value (in this case the return of a DB row), you can give it an initial value while waiting (in this case I gave it a false), but you can ignore it and check if there is a value with snapshot.hasData and return a CircularProgressIndicator to tell the user you're fetching the data

return FutureBuilder<bool>(
        future: isFav,
        initialData: false,// you can define an initial value while the db returns the real value
        builder: (context, snapshot) {
          if(snapshot.hasError) return const Icon(Icons.error, color: Colors.red); //just in case the db return an error
          if(snapshot.hasData)
          return IconButton(
            icon: snapshot.data ? const Icon(Icons.favorite, color: Colors.yellow) :
             Icon(Icons.favorite, color: Colors.white),
            onPressed: () => setState(() {})
          );

          return CircularProgressIndicator(); //if there is no initial value and the future is not yet complete
        });

I made this StatefulWidget so when you press the button it setState and re-run the isFav future to check again the DB (but it just rebuilds this iconbutton, not your whole page). If you wanted to update your whole page according to that isFav value instead of just the icon then you will have to use that FutureBuilder in all the body of your Scaffold, or at least above in your widget tree where you really need to check that value


问:
logit regression and singular Matrix error in Python
am trying to run logit regression for german credit data (www4.stat.ncsu.edu/~boos/var.select/german.credit.html). To test the code, I have used only numerical variables and tried regressing it with the result using the following code.

```<code>import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np

df = pd.read_csv("germandata.txt",delimiter=' ')
df.columns = ["chk_acc","duration","history","purpose","amount","savings_acc","employ_since","install_rate","pers_status","debtors","residence_since","property","age","other_plans","housing","existing_credit","job","no_people_liab","telephone","foreign_worker","admit"]

#pls note that I am only retaining numeric variables
cols_to_keep = ['admit','duration', 'amount', 'install_rate','residence_since','age','existing_credit','no_people_liab']

# rank of cols_to_keep is 8
print np.linalg.matrix_rank(df[cols_to_keep].values)
data = df[cols_to_keep]

data['intercept'] = 1.0

train_cols = data.columns[1:]

#to check the rank of train_cols, which in this case is 8
print np.linalg.matrix_rank(data[train_cols].values)

#fit logit model
logit = sm.Logit(data['admit'], data[train_cols])
result = logit.fit()
</code>```

All the 8.0 columns seem independent when I check the data. Inspite of this I am getting Singular Matrix Error. Can you please help?

Thanks

答:
I've managed to solve this by removing as well low variance columns:

```<code>from sklearn.feature_selection import VarianceThreshold

def variance_threshold_selector(data, threshold=0.5):
    # https://stackoverflow.com/a/39813304/1956309
    selector = VarianceThreshold(threshold)
    selector.fit(data)
    return data[data.columns[selector.get_support(indices=True)]]

# min_variance = .9 * (1 - .9)  # You can play here with different values.
min_variance = 0.0001
low_variance = variance_threshold_selector(df, min_variance)
print('columns removed:')
df.columns ^ low_variance.columns
df.shape
df.shape
X = low_variance
# (Logit(y_train, X), logit.fit()... etc)
</code>```

To give a bit more of context: I did one-hot encoding to some categorical data prior to this step, and some of the columns had very few 1's

Body:
am trying to run logit regression for german credit data (www4.stat.ncsu.edu/~boos/var.select/german.credit.html). To test the code, I have used only numerical variables and tried regressing it with the result using the following code.

import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np

df = pd.read_csv("germandata.txt",delimiter=' ')
df.columns = ["chk_acc","duration","history","purpose","amount","savings_acc","employ_since","install_rate","pers_status","debtors","residence_since","property","age","other_plans","housing","existing_credit","job","no_people_liab","telephone","foreign_worker","admit"]

#pls note that I am only retaining numeric variables
cols_to_keep = ['admit','duration', 'amount', 'install_rate','residence_since','age','existing_credit','no_people_liab']

# rank of cols_to_keep is 8
print np.linalg.matrix_rank(df[cols_to_keep].values)
data = df[cols_to_keep]

data['intercept'] = 1.0

train_cols = data.columns[1:]

#to check the rank of train_cols, which in this case is 8
print np.linalg.matrix_rank(data[train_cols].values)

#fit logit model
logit = sm.Logit(data['admit'], data[train_cols])
result = logit.fit()

All the 8.0 columns seem independent when I check the data. Inspite of this I am getting Singular Matrix Error. Can you please help?

Thanks

Body:
I've managed to solve this by removing as well low variance columns:

from sklearn.feature_selection import VarianceThreshold

def variance_threshold_selector(data, threshold=0.5):
    # https://stackoverflow.com/a/39813304/1956309
    selector = VarianceThreshold(threshold)
    selector.fit(data)
    return data[data.columns[selector.get_support(indices=True)]]

# min_variance = .9 * (1 - .9)  # You can play here with different values.
min_variance = 0.0001
low_variance = variance_threshold_selector(df, min_variance)
print('columns removed:')
df.columns ^ low_variance.columns
df.shape
df.shape
X = low_variance
# (Logit(y_train, X), logit.fit()... etc)

To give a bit more of context: I did one-hot encoding to some categorical data prior to this step, and some of the columns had very few 1's


问:
Remove blank rows in table
I'm trying to run a macro that selects blank cells in a table column and deletes the entire row.

The script below does everything except the deleting part, which prompts the following error:

run-time error 1004 - "Delete method of Range class failed"

I have used the following code:

```<code>Sub test()
Range("Table1[[New]]").Activate
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
End Sub
</code>```

答:
This One liner also would help

on error resume next 'to continue macro if no empty row is found in table
.Range("Table1").Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

'this delete empty using 1st column as reference for checking blanks
'Use custom names for tables for easy manipulation in codes

Title: Remove blank rows in table

Body:
I'm trying to run a macro that selects blank cells in a table column and deletes the entire row.

The script below does everything except the deleting part, which prompts the following error:

run-time error 1004 - "Delete method of Range class failed"

I have used the following code:

Sub test()
Range("Table1[[New]]").Activate
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
End Sub


问:
spread operator - for object, not recognizing its objects name
I am passing down the props editing, selectedPost from parent component to child component, to use it to set the state in child component.

I do this to check if the previous editing, selectedPost is different from newly passed down props, when the child component is being re-rendered.

I check this difference in my useEffect state, to validate if the value of the current form(post) needs to be updated with the newest value or not.

But I wonder if the logic is faulty, since child component's prevEditing and prevSelectedPost will always update its value same as the passed down props value?

```<code>export default function FeedEdit({editing, selectedPost){

  const [ prevEditing, setPrevEditing ] = useState(editing)
  const [ prevSelectedPost, setPrevSelectedPost ] = useState(selectedPost)

    useEffect(() => {
    if (
      editing &&
      //check if the logic here is correct
      prevEditing !== editing &&
      prevSelectedPost !== selectedPost
    ) {
      const updatedPostForm = {
        title: {
          // ...title,
          value: selectedPost.title,
          valid: true
        },
        image: {
          // ...image,
          value: selectedPost.imagePath,
          valid: true
        },
        content: {
          // ...content,
          value: selectedPost.content,
          valid: true
        }
      }
      setPostForm(updatedPostForm)
      setFormIsValid(true)
    }
  }, [])

}
</code>```

答:
All you have to do is to add these editing and selectedPost into the dependency list. If any of these dependency gets updated, useEffects will kick in. Previously since the dependency was blank, useEffect was not triggering.

```<code>const [ prevEditing, setPrevEditing ] = useState(editing)
const [ prevSelectedPost, setPrevSelectedPost ] = useState(selectedPost)

    useEffect(() => {

  const updatedPostForm = {
    title: {
      // ...title,
      value: selectedPost.title,
      valid: true
    },
    image: {
      // ...image,
      value: selectedPost.imagePath,
      valid: true
    },
    content: {
      // ...content,
      value: selectedPost.content,
      valid: true
    }
  }
  setPostForm(updatedPostForm)

    setFormIsValid(true)

   }, [editing, selectedPost])
</code>```

Body:
I am passing down the props editing, selectedPost from parent component to child component, to use it to set the state in child component.

I do this to check if the previous editing, selectedPost is different from newly passed down props, when the child component is being re-rendered.

I check this difference in my useEffect state, to validate if the value of the current form(post) needs to be updated with the newest value or not.

But I wonder if the logic is faulty, since child component's prevEditing and prevSelectedPost will always update its value same as the passed down props value?

export default function FeedEdit({editing, selectedPost){

  const [ prevEditing, setPrevEditing ] = useState(editing)
  const [ prevSelectedPost, setPrevSelectedPost ] = useState(selectedPost)

    useEffect(() => {
    if (
      editing &&
      //check if the logic here is correct
      prevEditing !== editing &&
      prevSelectedPost !== selectedPost
    ) {
      const updatedPostForm = {
        title: {
          // ...title,
          value: selectedPost.title,
          valid: true
        },
        image: {
          // ...image,
          value: selectedPost.imagePath,
          valid: true
        },
        content: {
          // ...content,
          value: selectedPost.content,
          valid: true
        }
      }
      setPostForm(updatedPostForm)
      setFormIsValid(true)
    }
  }, [])

}

Body:
All you have to do is to add these editing and selectedPost into the dependency list. If any of these dependency gets updated, useEffects will kick in. Previously since the dependency was blank, useEffect was not triggering.

const [ prevEditing, setPrevEditing ] = useState(editing)
const [ prevSelectedPost, setPrevSelectedPost ] = useState(selectedPost)

    useEffect(() => {

  const updatedPostForm = {
    title: {
      // ...title,
      value: selectedPost.title,
      valid: true
    },
    image: {
      // ...image,
      value: selectedPost.imagePath,
      valid: true
    },
    content: {
      // ...content,
      value: selectedPost.content,
      valid: true
    }
  }
  setPostForm(updatedPostForm)

    setFormIsValid(true)

   }, [editing, selectedPost])


问:
How to replace current value to defined string
the query result

```<code>select ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) ) as num_slashes,
 count(*) from test.1 where isdeleted = false  group by ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
 ORDER BY COUNT(*)
</code>```

from database returned :

i would like to replaced the 0, 1, 2
to master1, master2, master3.

what query should I used so the query result will be

答:
I would simplify your query by using a derived table to compute num_slashes and then using a CASE expression to convert that value into a string:

```<code>SELECT CASE num_slashes WHEN 0 THEN 'master1'
                        WHEN 1 THEN 'master2'
                        ELSE 'master3'
       END AS number_slashes,
       COUNT(*) AS count
FROM (
  SELECT ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) ) AS num_slashes
  FROM test.1
  WHERE isdeleted = false
) t
GROUP BY num_slashes
ORDER BY num_slashes
</code>```

Body:
the query result

select ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) ) as num_slashes,
 count(*) from test.1 where isdeleted = false  group by ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
 ORDER BY COUNT(*)

from database returned :

i would like to replaced the 0, 1, 2
to master1, master2, master3.

what query should I used so the query result will be

Body:
I would simplify your query by using a derived table to compute num_slashes and then using a CASE expression to convert that value into a string:

SELECT CASE num_slashes WHEN 0 THEN 'master1'
                        WHEN 1 THEN 'master2'
                        ELSE 'master3'
       END AS number_slashes,
       COUNT(*) AS count
FROM (
  SELECT ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) ) AS num_slashes
  FROM test.1
  WHERE isdeleted = false
) t
GROUP BY num_slashes
ORDER BY num_slashes


答:
You can use:</p>

```<code>select (case ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
            when 1 then 'master1'
            when 2 then 'master2'
            when 3 then 'master3'
        end) as num_slashes,
       count(*)
from test.1
where isdeleted = false
group by ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
order by COUNT(*)
</code>```

Title: How to replace current value to defined string

Body:
You can use:

select (case ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
            when 1 then 'master1'
            when 2 then 'master2'
            when 3 then 'master3'
        end) as num_slashes,
       count(*)
from test.1
where isdeleted = false
group by ( LENGTH(testid) - LENGTH(replace(testid, '/', '')) )
order by COUNT(*)