问:
Angular2 wait for @Input object to be fully initialized
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

```<code>@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}
</code>```

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

```<code><child-view [myObj]="myObjInParent"/>
</code>```

答:
One way you could possibly do it is to place an *ngIf on the  like this

```<code><child-view *ngIf="myObjInParent" [myObj]="myObjInParent"/>
</code>```

That would essentially display the component only after the myObjInParent changes from undefined to your value. Not the best solution, but it works.

Also you can make a copy of an object using an ES6 spread operator

```<code>this.copy = {...myObj}
</code>```

using a three dot notation. Hope I could help!

Body:
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

<child-view [myObj]="myObjInParent"/>

Body:
One way you could possibly do it is to place an *ngIf on the  like this

<child-view *ngIf="myObjInParent" [myObj]="myObjInParent"/>

That would essentially display the component only after the myObjInParent changes from undefined to your value. Not the best solution, but it works.

Also you can make a copy of an object using an ES6 spread operator

this.copy = {...myObj}

using a three dot notation. Hope I could help!


来源: stackexchange

问:
How to return data from array like this with jQuery?
For example, I have JavaScript array like this:

```<code>var data = [
{text:'Business', aid:'6'},
{text:'Careers', aid:'29'},
{text:'Credits', aid:'28'},
{text:'Insurance', aid:'30'}
];
</code>```

Now, in URl is passed ID and I need to grab 'text' from this array based on that ID like:

```<code>$('#category').val(data, function(item) {return item.aid['6'].text;} ); // = Business
</code>```

So I want to populate form field #category with text from array based on passed URL ID = aid?

Thanks in advance

答:
Use the filter[MDN] method to get the right object:

```<code>var aid = 28,
    match = data.filter(function(elem) { return elem.aid == aid; });

if (match.length) {
    $('#category').val(match[0].text);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, I have JavaScript array like this:

var data = [
{text:'Business', aid:'6'},
{text:'Careers', aid:'29'},
{text:'Credits', aid:'28'},
{text:'Insurance', aid:'30'}
];

Now, in URl is passed ID and I need to grab 'text' from this array based on that ID like:

$('#category').val(data, function(item) {return item.aid['6'].text;} ); // = Business

So I want to populate form field #category with text from array based on passed URL ID = aid?

Thanks in advance

Body:
Use the filter[MDN] method to get the right object:

var aid = 28,
    match = data.filter(function(elem) { return elem.aid == aid; });

if (match.length) {
    $('#category').val(match[0].text);
}


问:
Visual Studio Code - Type Script - Unable to load tsconfig.json and packages.json schemas
I'm working on an Angular front end in Visual Studio Code for an app with a C# windows service back end. After spending a few days on the back end without touching the front end, I found that Visual Studio Code would no longer automatically recompile my typescript code every time I saved. Instead, I would have to ctrl+c out of the process and run "npm start" again.

I ensured that compileOnSave was set to true in my tsconfig.json. In doing so, I notice a warning:

```<code>Problems loading reference 'http://json.schemastore.org/tsconfig': Unable to load schema from 'http://json.schemastore.org/tsconfig': Unable to to connect to http://json.schemastore.org/tsconfig. Error: getaddrinfo ENOTFOUND json.schemastore.org json.schemastore.org:80
</code>```

I noticed a similar warning for packages.json. I'm able to load the schema on the links on Google Chrome.

What could be a possible fix? Could I download the schema and load it in Visual Studio Code manually?

答:
just follow these simple steps

click on the Settings icon at the bottom left of your vscode

search for JSON

you should see the schema download, it should be enabled

just turn it off

This worked for me.

Body:
I'm working on an Angular front end in Visual Studio Code for an app with a C# windows service back end. After spending a few days on the back end without touching the front end, I found that Visual Studio Code would no longer automatically recompile my typescript code every time I saved. Instead, I would have to ctrl+c out of the process and run "npm start" again.

I ensured that compileOnSave was set to true in my tsconfig.json. In doing so, I notice a warning:

Problems loading reference 'http://json.schemastore.org/tsconfig': Unable to load schema from 'http://json.schemastore.org/tsconfig': Unable to to connect to http://json.schemastore.org/tsconfig. Error: getaddrinfo ENOTFOUND json.schemastore.org json.schemastore.org:80

I noticed a similar warning for packages.json. I'm able to load the schema on the links on Google Chrome.

What could be a possible fix? Could I download the schema and load it in Visual Studio Code manually?

ContentLicense: CC BY-SA 4.0


问:
NextJS: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined
Using Nextjs and I've created an index.js in the /pages directory and created meta.js in the /components/meta/ directory.

As my app rebuilds I get the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

As seen below I am importing Meta correctly, it is also a default export. Curious where I'm going wrong.

pages/index.js

```<code>// import Head from 'next/head'
import Meta from '../components/meta/meta';

export default () => (
  <div>
    <Meta />
    <p>Hello world! Welcome to</p>
    <h1>Moonholdings.io</h1>
  </div>
)
</code>```

components/meta/meta.js

```<code>import Head from 'next/head'

export default () => (
  <Head>
    <title>Moonholdings.io</title>
    <meta name="description" content="Your Cryptocurrency Portfolio" />>
    <meta name="keywords" content="cryptocurrency, crypto, portfolio, bitcoin, ethereum, holdings"/>
    <meta name="robots" content="index, follow" />
    <meta name="viewport" content="initial-scale=1.0, width=device-width" />
  </Head>
)
</code>```

Project structure

答:
I got the same error when importing "Link" with Curly Braces "{}" from "next/link" and using "<Link></Link>" as shown below:

import { Link } from 'next/link';

const Hello = () => {
  return (
    <Link href='/hello'>
      Hello
    </Link>
  )
}

export default Hello;
```
<p>So, I imported <strong>"Link" without Curly Braces "{}"</strong> then the error was solved:</p>
<pre class="lang-js prettyprint-override"><code>// "{}" are removed from "Link"
import Link from 'next/link';

const Hello = () => {
  return (
    <Link href='/hello'>
      Hello
    </Link>
  )
}

export default Hello;
</code>```

Body:
Using Nextjs and I've created an index.js in the /pages directory and created meta.js in the /components/meta/ directory.

As my app rebuilds I get the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

As seen below I am importing Meta correctly, it is also a default export. Curious where I'm going wrong.

pages/index.js

// import Head from 'next/head'
import Meta from '../components/meta/meta';

export default () => (

    <Meta />

Hello world! Welcome to

Moonholdings.io

)

components/meta/meta.js

import Head from 'next/head'

export default () => (

    <title>Moonholdings.io</title>
    <meta name="description" content="Your Cryptocurrency Portfolio" />>
    <meta name="keywords" content="cryptocurrency, crypto, portfolio, bitcoin, ethereum, holdings"/>
    <meta name="robots" content="index, follow" />
    <meta name="viewport" content="initial-scale=1.0, width=device-width" />

)

Project structure

Body:
I got the same error when importing "Link" with Curly Braces "{}" from "next/link" and using "<Link></Link>" as shown below:

import { Link } from 'next/link';

const Hello = () => {
  return (
    <Link href='/hello'>
      Hello
    </Link>
  )
}

export default Hello;

So, I imported "Link" without Curly Braces "{}" then the error was solved:

// "{}" are removed from "Link"
import Link from 'next/link';

const Hello = () => {
  return (
    <Link href='/hello'>
      Hello
    </Link>
  )
}

export default Hello;


问:
c# stringbuilder tostring double quote issue
I have an issue when converting a string from stringbuilder to string.
The issue is similar to this issue but slightly different:

This is my code simplified:

```<code>StringBuilder sb = new StringBuilder();
sb.Append("\"");
sb.Append("Hello World");
sb.Append("\"");

string test = sb.ToString();
</code>```

Now in the debugger the sb value is:

```<code>"Hello World"
</code>```

In the debugger the test string value is changed to:

```<code>\"Hello World\"
</code>```

When returning the test string value back to the browser the velue is STILL escaped:

```<code>\"Hello World\"
</code>```

I have tried using the string replace:

```<code>test = test.Replace("\"", "");
</code>```

no luck, I tried appending the ASCII character instead of \" and I have also tried a different append

```<code>sb.Append('"');
</code>```

All these with no luck. Can somebody maybe point me in the right direction of why I'm still getting the escape character and how to get rid of it.

Thanks and appreciate any input.

答:
This question and answer thread kept on coming up when searching for the solution.
The confusion, for me, was that the Debugger escaping looks exactly the same as the JSON serializer behaviour that was being applied later when I returned the string to a client. So the code at the top of the thread (and my code) worked correctly.

Once I realised that, I converted the piece of code I was working on return an array (string[] in this case) and store that rather than the original string object. Later the JSONResult serializer then dealt with converting the array correctly.

Body:
I have an issue when converting a string from stringbuilder to string.
The issue is similar to this issue but slightly different:

This is my code simplified:

StringBuilder sb = new StringBuilder();
sb.Append("\"");
sb.Append("Hello World");
sb.Append("\"");

string test = sb.ToString();

Now in the debugger the sb value is:

"Hello World"

In the debugger the test string value is changed to:

\"Hello World\"

When returning the test string value back to the browser the velue is STILL escaped:

\"Hello World\"

I have tried using the string replace:

test = test.Replace("\"", "");

no luck, I tried appending the ASCII character instead of \" and I have also tried a different append

sb.Append('"');

All these with no luck. Can somebody maybe point me in the right direction of why I'm still getting the escape character and how to get rid of it.

Thanks and appreciate any input.


问:
The term alias is not recognized
While trying to get the debug certificate fingerprint to be used in firebase we got an error claiming that keytool is not recognized, but we downloaded jdk and set the path then this error appeared:</p>

```<code>-alias : The term '-alias' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystor ...
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (-alias:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
You should use this command, it will work!

```<code>keytool -list -v -alias androiddebugkey -keystore "%USERPROFILE%/.android/debug.keystore"
</code>```

Password will be: android

Title: The term alias is not recognized

Body:
While trying to get the debug certificate fingerprint to be used in firebase we got an error claiming that keytool is not recognized, but we downloaded jdk and set the path then this error appeared:

-alias : The term '-alias' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystor ...
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (-alias:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Body:
You should use this command, it will work!

keytool -list -v -alias androiddebugkey -keystore "%USERPROFILE%/.android/debug.keystore"

Password will be: android


问:
In R grid package , how to use viewport for merge ggplot2 plots
I want to merge geom_point() and geom_boxplot() into one plot as attached image.Below code can't work.Anyone can help on this? Thanks!

```<code>library(grid)
library(ggplot2)
grid.newpage()
vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)
push.Viewport(vp)
ggplot(mtcars) + geom_point(aes(mpg, disp))

vp_sub <- viewport(x=0.5,y=0.7,width=0.3,height=0.3)
push.viewport(vp_sub)
ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
</code>```

答:
Using viewport you could accomplish your task this way. If you want to save in a png then just comment out the line #png("my_plot.png")

```<code>library(grid)
library(ggplot2)
grid.newpage()

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)vp_sub <- viewport(x=0.73,y=0.8,width=0.4,height=0.3)

#png("my_plot.png")
print(p1, vp=vp)
print(p2, vp=vp_sub)
dev.off()
</code>```

Body:
I want to merge geom_point() and geom_boxplot() into one plot as attached image.Below code can't work.Anyone can help on this? Thanks!

library(grid)
library(ggplot2)
grid.newpage()
vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)
push.Viewport(vp)
ggplot(mtcars) + geom_point(aes(mpg, disp))

vp_sub <- viewport(x=0.5,y=0.7,width=0.3,height=0.3)
push.viewport(vp_sub)
ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

Body:
Using viewport you could accomplish your task this way. If you want to save in a png then just comment out the line #png("my_plot.png")

library(grid)
library(ggplot2)
grid.newpage()

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))

vp <- viewport(x=0.5,y=0.5,width = 1,height = 1)vp_sub <- viewport(x=0.73,y=0.8,width=0.4,height=0.3)

#png("my_plot.png")
print(p1, vp=vp)
print(p2, vp=vp_sub)
dev.off()


问:
Why would people use `$a = $b = 2;` in PHP?
Why would people use this format? Whats different between this and $a=2; $b=2;?

答: Nothing. They are exactly the same, it's just a matter of personal preference or coding style. Also, if you redefine $b, $a will not change, which is expected.


问:
How after completing any task in the loop, pass a value to another method, return to the loop, and wait for the next task to complete?
There are 2 methods, one method depends on the other. I need to send several files to the server in parallel, which answer from the server comes first, and send it to DownloadFileAsync method, and do the same with the rest (without waiting for all answers at once, send them (answers from the server) to DownloadFileAsync() method, as they are received).

```<code>public async Task CompressAllFilesAsync(List<UserFile> files, string outputpath)
{
    await UploadAllFilesAsync(files);
    await DownloadAllFilesAsync(files, outputpath);
}

public async Task UploadAllFilesAsync(List<UserFile> files)
{
    IEnumerable<Task> allTasks = files.Select(async (file, i) =>
        files[i].FileLink = await UploadFileAsync(files[i])
    );

    await Task.WhenAll(allTasks);
}

public async Task DownloadAllFilesAsync(List<UserFile> files, string outputpath)
{
    IEnumerable<Task> allTasks = files.Select((file, i) =>
        DownloadFileAsync(files[i].FileLink,
        Path.Combine(outputpath, $"{files[i].FileName}")
    ));

    await Task.WhenAll(allTasks);
}
</code>```

Now the program is waiting for all answers from the server (links to downloadable files) before running the DownloadAllFilesAsync() method.

答:
```<code>for (int i = 0; i < fileToSend; i++)
{
   Task task = new Task(() =>
   {
      SendFile(file[i]);
   });
   task.Start();
}
</code>```

This way you're gonna create a background task that will send your files in paralell

Body:
There are 2 methods, one method depends on the other. I need to send several files to the server in parallel, which answer from the server comes first, and send it to DownloadFileAsync method, and do the same with the rest (without waiting for all answers at once, send them (answers from the server) to DownloadFileAsync() method, as they are received).

public async Task CompressAllFilesAsync(List<UserFile> files, string outputpath)
{
    await UploadAllFilesAsync(files);
    await DownloadAllFilesAsync(files, outputpath);
}

public async Task UploadAllFilesAsync(List<UserFile> files)
{
    IEnumerable<Task> allTasks = files.Select(async (file, i) =>
        files[i].FileLink = await UploadFileAsync(files[i])
    );

    await Task.WhenAll(allTasks);
}

public async Task DownloadAllFilesAsync(List<UserFile> files, string outputpath)
{
    IEnumerable<Task> allTasks = files.Select((file, i) =>
        DownloadFileAsync(files[i].FileLink,
        Path.Combine(outputpath, $"{files[i].FileName}")
    ));

    await Task.WhenAll(allTasks);
}

Now the program is waiting for all answers from the server (links to downloadable files) before running the DownloadAllFilesAsync() method.

Body:
for (int i = 0; i < fileToSend; i++)
{
   Task task = new Task(() =>
   {
      SendFile(file[i]);
   });
   task.Start();
}

This way you're gonna create a background task that will send your files in paralell


问:
Simplifying/collapsing blocks of df.iterrows() where another row is selected based on a value in the current row
I need help :) I've got a python script in which a snippet that repeats df.iterrows() a couple of times takes a good half hour to run. I've seen a lot of examples using lambda functions but this is where apparently I meet my limitations. It's too complex for me to figure out I guess.

Current code (simplified snippet):

for index, row in df.iterrows():
    if row["series"] == -1 and row["sort"] == 1 and row["amount_t-2"] != 0:
        index_match = df[
            (df["sort"] == 4)
            & (df["year"] == (row["year"] - 1))
            & (df["amount_t-1"] == (row["amount_t-2"]))
            & (df["cola"] == (row["cola"]))
            & (df["colb"] == (row["colb"]))
        ].index.tolist()
        if len(index_match) == 1:
            df.loc[index, "series"] = df.loc[index_match[0], "series"]
            df.loc[index, "colc"] = "done"
            df.loc[index, "cold"] = ""
```
<p>This snippet is repeated a number of times for different configurations/values. What's done here is looping through the entire dataset, creating a time series by setting the 'series' column to the same (index) number if certain conditions are met (i.e. if the values are linked)</p>
<p>Little background: the dataset consists of budgetary tables in which each row represents the state of a budget article for a certain budget phase/time (sort field: 1=budget, 2=first supplement, 3=second supplement, 4=actuals). In order to be able to trace a certain budget article through time, I want to link all relevant rows through a common value for the field 'series'.</p>
<p>When searching for a row to link to the current row, I filter the df by: 'previous phase' (sort-1 or in this case 4 if sort=1), 'year of previous phase' (same year for sort=2,3,4, previous if sort=1), matching value/amounts and matching article name etc.</p>
<hr />
<p>So far, I've been meddling with something like the following code, but cannot get it to work. Am I at least close?</p>
<pre class="lang-py prettyprint-override"><code>df['series'] = df.apply(lambda x: df.query("sort == 4 and year == @x['year']-1 and `amount_t-1` == @x['amount_t-2'] and cola == @x['cola'] and colb == @x['colb']").index[0] if x['series'] == -1 and x['sort'] == 1 and x['amount_t-2'] != 0, axis=1)
</code>```

Thanks in advance,

Chris

Edit: Sample data

Before script starts, database contains:

```<code>year sort cola series
2020   1  I.1   1
2020   2  I.1   1
2020   3  I.1   1
2020   4  I.1   1
2021   1  I.2   1 (cola, being article name, is renamed to I.2 for this year)
2021   2  I.2   1
2021   3  I.2   1
2022   1  I.2   1 (note that 2021.4 is not present yet but 2022.1 is)
</code>```

During script execution (before this snippet!) some rows are added:

```<code>2021   4  I.1  -1 (each row is added with a series id of -1 as default)
2021   4  I.2  -1 (this is the row we're looking for in series 1)
2021   4  I.3  -1 (all other rows I.1, I.3, I.* and II.* thru XX.* also get a series number, just not number 1...)
</code>```

So, superficially (and for many cases also in reality), it seems like the series number corresponds with col.a (article name/number). However, article name/numbers may change over time or articles may be split or merged leading to a break in the series. Thus, I cannot simply use the article number as a guide.

Instead, I compare the amount_t in the current row to the amount_t-1 in the candidate row for previous in the series as a double check.

In the example above, the script should yield:

```<code>year sort cola series
2020   1  I.1   1
2020   2  I.1   1
2020   3  I.1   1
2020   4  I.1   1
2021   1  I.2   1
2021   2  I.2   1
2021   3  I.2   1
2021   4  I.1   2
2021   4  I.2   1 <-- this one right here :)
2021   4  I.3   3
2022   1  I.2   1
</code>```

Hope this clarifies.

答:
I would suggest you refactor your code in a bit more idiomatic way and use pandas .at method instead of .loc, since it is much faster, like this:

# Get the first condition out of the 'for loop'
sub_df = df.loc[(df["series"] == -1) & (df["sort"] == 1) & (df["amount_t-2"] != 0), :]

# Iterate by asking for forgiveness, not permission
for i, row in sub_df.iterrows():
    try:
        index_match = df[
            (df["sort"] == 4)
            & (df["year"] == (row["year"] - 1))
            & (df["amount_t-1"] == (row["amount_t-2"]))
            & (df["cola"] == (row["cola"]))
            & (df_int["colb"] == (row["colb"]))
        ].index[0]
    except IndexError:
        continue
    else:
        df.at[i, "series"] = df.at[index_match, "series"]
        df.at[i, "colc"] = "done"
        df.at[i, "cold"] = ""
```

Body:
I need help :) I've got a python script in which a snippet that repeats df.iterrows() a couple of times takes a good half hour to run. I've seen a lot of examples using lambda functions but this is where apparently I meet my limitations. It's too complex for me to figure out I guess.

Current code (simplified snippet):

for index, row in df.iterrows():
    if row["series"] == -1 and row["sort"] == 1 and row["amount_t-2"] != 0:
        index_match = df[
            (df["sort"] == 4)
            & (df["year"] == (row["year"] - 1))
            & (df["amount_t-1"] == (row["amount_t-2"]))
            & (df["cola"] == (row["cola"]))
            & (df["colb"] == (row["colb"]))
        ].index.tolist()
        if len(index_match) == 1:
            df.loc[index, "series"] = df.loc[index_match[0], "series"]
            df.loc[index, "colc"] = "done"
            df.loc[index, "cold"] = ""

This snippet is repeated a number of times for different configurations/values. What's done here is looping through the entire dataset, creating a time series by setting the 'series' column to the same (index) number if certain conditions are met (i.e. if the values are linked)

Little background: the dataset consists of budgetary tables in which each row represents the state of a budget article for a certain budget phase/time (sort field: 1=budget, 2=first supplement, 3=second supplement, 4=actuals). In order to be able to trace a certain budget article through time, I want to link all relevant rows through a common value for the field 'series'.

When searching for a row to link to the current row, I filter the df by: 'previous phase' (sort-1 or in this case 4 if sort=1), 'year of previous phase' (same year for sort=2,3,4, previous if sort=1), matching value/amounts and matching article name etc.

So far, I've been meddling with something like the following code, but cannot get it to work. Am I at least close?

df['series'] = df.apply(lambda x: df.query("sort == 4 and year == @x['year']-1 and `amount_t-1` == @x['amount_t-2'] and cola == @x['cola'] and colb == @x['colb']").index[0] if x['series'] == -1 and x['sort'] == 1 and x['amount_t-2'] != 0, axis=1)

Thanks in advance,

Chris

Edit: Sample data

Before script starts, database contains:

year sort cola series
2020   1  I.1   1
2020   2  I.1   1
2020   3  I.1   1
2020   4  I.1   1
2021   1  I.2   1 (cola, being article name, is renamed to I.2 for this year)
2021   2  I.2   1
2021   3  I.2   1
2022   1  I.2   1 (note that 2021.4 is not present yet but 2022.1 is)

During script execution (before this snippet!) some rows are added:

2021   4  I.1  -1 (each row is added with a series id of -1 as default)
2021   4  I.2  -1 (this is the row we're looking for in series 1)
2021   4  I.3  -1 (all other rows I.1, I.3, I.* and II.* thru XX.* also get a series number, just not number 1...)

So, superficially (and for many cases also in reality), it seems like the series number corresponds with col.a (article name/number). However, article name/numbers may change over time or articles may be split or merged leading to a break in the series. Thus, I cannot simply use the article number as a guide.

Instead, I compare the amount_t in the current row to the amount_t-1 in the candidate row for previous in the series as a double check.

In the example above, the script should yield:

year sort cola series
2020   1  I.1   1
2020   2  I.1   1
2020   3  I.1   1
2020   4  I.1   1
2021   1  I.2   1
2021   2  I.2   1
2021   3  I.2   1
2021   4  I.1   2
2021   4  I.2   1 <-- this one right here :)
2021   4  I.3   3
2022   1  I.2   1

Hope this clarifies.


问:
Increasing a value with the multiple of 2 other values in MongoDB
I want to increase a value 'a' by 'b' * 0.1
How would I do this in MongoDB? I know about '$inc' and '$mul' but I don't know how to combine them.

My try:

collection.update_many({}, {'$inc': {'a': {'$mul': {'b', 0.1}}}})

答:
Figured it out you can use the aggregation pipeline to do it like this

```<code>collection.update_many({}, [{"$set": {"a": {"$add": [{"$multiply": ["$b", 0.1]}, "$a"]}}}])
</code>```

This may not be the best way to do it tho

Body:
Figured it out you can use the aggregation pipeline to do it like this

collection.update_many({}, [{"$set": {"a": {"$add": [{"$multiply": ["$b", 0.1]}, "$a"]}}}])

This may not be the best way to do it tho


问:
How to resize images proportionally / keeping the aspect ratio?
I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.

Can someone point me to some code, or explain the logic?

答:
You can determine width height if you want a particular aspect ratio to do so,
Let you have a picture of 3264×2448
Pictures aspect ratio is => 2448 ÷ 3264 =0.75
Now just check number which gives 0.75 on division.
Like: for
16:9 => 9÷16 =0.5625 (wrong it is not 0.75)
Now 4:3 =>3÷4=0.75 (we get it )
So the original aspect ratio is 4:3
now to resize the image just do
Width=3264 ÷/× 4
Height=2448 ÷/× 3
÷ for reducing
× for increasing
Hope you can understand and code yourself this is very effective because we just need to do very basic arithmetic just division or multiplication so simple.
Let me know if i am wrong.</p>


问:
How do you parse a poorly formatted HTML file?
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

```<code><html>
...
  <tr><td>Table column that is missing a td
      <td> Another table column</td></tr>
  <tr><td>$data_item_1$</td>
...
</html>
</code>```

Template B:

```<code><html>
...
  <ul><li>Yet another poorly formatted page <li>$data_item_1$</td></tr>
...
</html>
</code>```

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

答:
Use HTML5 parser like html5lib.

Unlike HTML Tidy, this will give you error handling very close to what browsers do.

OwnerDisplayName: ivo

ContentLicense: CC BY-SA 2.5

Body:
I have to parse a series of web pages in order to import data into an application. Each type of web page provides the same kind of data. The problem is that the HTML of each page is different, so the location of the data varies. Another problem is that the HTML code is poorly formatted, making it impossible to use a XML-like parser.

So far, the best strategy I can think of, is to define a template for each kind of page, like:

Template A:

...

Table column that is missing a td
       Another table column

$data_item_1$
...

Template B:

...

Yet another poorly formatted page
$data_item_1$

...

This way I would only need one single parser for all the pages, that would compare each page with its template and retrieving the $data_item_1$, $data_item_2$, etc.  Still, it is going to be a lot of work.  Can you think of any simpler solution? Any library that can help?

Thanks

LastEditorDisplayName: Eddie

OwnerDisplayName: porneL


问:
Android studio shows can not find Declaration to go to in flutter project
while working on a flutter project, Android studio behaving strangely for some of the dart files is shows Cannot find declaration to go to  even for BuildContext.  ( Project runs without any errors )

issue snapshot:

while some of the dart files in the same project are able to go to the declarations and find the references.

I have already tried the following methods:

Invalidate cache and restart

deleted .idea folder

updated flutter plugin

None of the above methods worked for me, Is there any way to resolve this error? any suggestions or solutions would be very helpful.

答: I was able to resolve this issue just by deleting the @override and writing it again..


问:
Konva stage does not trigger on click using synthetic MouseEvent
i'm using MouseEvent to click on Konva stage. The user does not click on the Konva's canvas, directly, instead,  the user clicks on something else and that click is translated to Konva canvas based on some calculations.

I have a 3D platform written in Babylonjs that uses Konva's canvas as the dynamic texture.
The texture is then applied to the mesh. When there is a click on the mesh, it will tell me which area (x,y) of the texture was clicked. Now I will have to programmatically trigger a click on the texture (Konva's canvas) so that Konva's shape gets selected and they can drag it around the texture and this will be updated real-time on the mesh (3d).

The problem is that my custom mouse event is not recognized by

```<code>stage.on('click'.
</code>```

Please check the below example.

https://jsbin.com/sayiwajega/1/edit?html,js,console,output

Working solution using fabricjs.

https://www.babylonjs-playground.com/#9U086#238

I know that there is an

```<code>this.stage.fire('click', { posX, posY });
</code>```

But the limitation here is that you cant pass an actual click or a drag event. as a result, you cant just transfer the action from the 3d Canvas to Konva's canvas.

答:
Konva doesn't listen to click event on the canvas to trigger its own click event.

Instead, it is listening to

mousedown / touchstart / pointerdown

mousemove / touchmove / pointermove

mouseup / touchend / pointerup

So to replicate most of Konva events you need to proxy these events into container.

stage.on('click',  (evt) => {
  console.log('you clicked on the circle!');
});

customMouseEvent = () =>  {
  const cb = document.getElementById('container').getElementsByTagName('canvas')[0];
  let evt = new MouseEvent("mousedown", {
    bubbles: true,
    cancelable: true,
    view: window
  });
  cb.dispatchEvent(evt);
  evt = new MouseEvent("mouseup", {
    bubbles: true,
    cancelable: true,
    view: window
  });
  cb.dispatchEvent(evt);
}
```

Body:
i'm using MouseEvent to click on Konva stage. The user does not click on the Konva's canvas, directly, instead,  the user clicks on something else and that click is translated to Konva canvas based on some calculations.

I have a 3D platform written in Babylonjs that uses Konva's canvas as the dynamic texture.
The texture is then applied to the mesh. When there is a click on the mesh, it will tell me which area (x,y) of the texture was clicked. Now I will have to programmatically trigger a click on the texture (Konva's canvas) so that Konva's shape gets selected and they can drag it around the texture and this will be updated real-time on the mesh (3d).

The problem is that my custom mouse event is not recognized by

stage.on('click'.

Please check the below example.

https://jsbin.com/sayiwajega/1/edit?html,js,console,output

Working solution using fabricjs.

https://www.babylonjs-playground.com/#9U086#238

I know that there is an

this.stage.fire('click', { posX, posY });

But the limitation here is that you cant pass an actual click or a drag event. as a result, you cant just transfer the action from the 3d Canvas to Konva's canvas.


问:
Trying to use a for loop to try and match user input to a premade array. Getting a warning for unreachable code and the program won't recognize match
I must get the user to enter a zip code and then the program searches a premade array to either confirm or deny their zip code.

It works fine when the zip codes don't match but it doesn't recognize it when it does.

Also, the line where I am getting the 'unreachable code' warning is in my loop controls:

```<code>for (int i = 0; i < zips.Length; i++)
</code>```

The rest of the code looks like this:

    string[] zips = { "I won't bother you with all the zip codes manually entered here" };
    System.Console.WriteLine("Enter your zip code > ";
    string userZip = System.Console.ReadLine();

    for (int i = 0; i < zips.Length; i++)
     {
        if (userZip == zips[i])
           System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else
           System.Console.WriteLine("Sorry - no delivery to " + userZip);
        break;
    }
```

答:
Here's one working solution (includes some sample made up ZIP codes).

```<code>using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var zips = new [] {"12345", "23456", "34567"};

        System.Console.WriteLine("Enter your zip code > ");
        string userZip = System.Console.ReadLine();

        var match = zips.FirstOrDefault(z => z == userZip);

        if(match!=null)  System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else  System.Console.WriteLine("Sorry - no delivery to " + userZip);
    }
}
</code>```

Explanation: instead of manually writing a for loop, I used a System.Linq function FirstOrDefault() to look through the list of zip codes instead. Internally it uses a loop but its just a simpler way of writing the logic required (IMO). It will either return the first match or null if none.

And you can run and try it right here: https://dotnetfiddle.net/yHDfEk

Sample input/output (no match):

```<code>Enter your zip code >
12344
Sorry - no delivery to 12344
</code>```

Sample input/output (match):

```<code>Enter your zip code >
23456
Delivery to 23456 ok.
</code>```

An example of where this is easier is that it deals with loop termination for you. (As noted in a comment by @Flydog57) you have the break statement in the wrong place which causes your program to misbehave. That extra logic is handled implicitly in the example I gave. Instead, you would want something like this:

```<code>var found = false;

for (int i = 0; i < zips.Length; i++)
 {
    if (userZip == zips[i])
    {
       found = true;
       System.Console.WriteLine("Delivery to " + userZip + " ok.");
       break;
    }
}

if(!found) System.Console.WriteLine("Sorry - no delivery to " + userZip);
</code>```

Note that if you wanted to use a manual loop, I would recommend foreach instead of for in most situations where you have a simple array, list, or similar data structure to loop through. foreach is just easier to get right.

```<code>var found = false;

foreach(var zip in zips)
{
    if (userZip == zip)
    {
       found = true;
       System.Console.WriteLine("Delivery to " + userZip + " ok.");
       break;
    }
}

if(!found) System.Console.WriteLine("Sorry - no delivery to " + userZip);
</code>```

Body:
I must get the user to enter a zip code and then the program searches a premade array to either confirm or deny their zip code.

It works fine when the zip codes don't match but it doesn't recognize it when it does.

Also, the line where I am getting the 'unreachable code' warning is in my loop controls:

for (int i = 0; i < zips.Length; i++)

The rest of the code looks like this:

    string[] zips = { "I won't bother you with all the zip codes manually entered here" };
    System.Console.WriteLine("Enter your zip code > ";
    string userZip = System.Console.ReadLine();

    for (int i = 0; i < zips.Length; i++)
     {
        if (userZip == zips[i])
           System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else
           System.Console.WriteLine("Sorry - no delivery to " + userZip);
        break;
    }

Body:
Here's one working solution (includes some sample made up ZIP codes).

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var zips = new [] {"12345", "23456", "34567"};

        System.Console.WriteLine("Enter your zip code > ");
        string userZip = System.Console.ReadLine();

        var match = zips.FirstOrDefault(z => z == userZip);

        if(match!=null)  System.Console.WriteLine("Delivery to " + userZip + " ok.");
        else  System.Console.WriteLine("Sorry - no delivery to " + userZip);
    }
}

Explanation: instead of manually writing a for loop, I used a System.Linq function FirstOrDefault() to look through the list of zip codes instead. Internally it uses a loop but its just a simpler way of writing the logic required (IMO). It will either return the first match or null if none.

And you can run and try it right here: https://dotnetfiddle.net/yHDfEk

Sample input/output (no match):

Enter your zip code >
12344
Sorry - no delivery to 12344

Sample input/output (match):

Enter your zip code >
23456
Delivery to 23456 ok.

An example of where this is easier is that it deals with loop termination for you. (As noted in a comment by @Flydog57) you have the break statement in the wrong place which causes your program to misbehave. That extra logic is handled implicitly in the example I gave. Instead, you would want something like this:

var found = false;

for (int i = 0; i < zips.Length; i++)
 {
    if (userZip == zips[i])
    {
       found = true;
       System.Console.WriteLine("Delivery to " + userZip + " ok.");
       break;
    }
}

if(!found) System.Console.WriteLine("Sorry - no delivery to " + userZip);

Note that if you wanted to use a manual loop, I would recommend foreach instead of for in most situations where you have a simple array, list, or similar data structure to loop through. foreach is just easier to get right.

var found = false;

foreach(var zip in zips)
{
    if (userZip == zip)
    {
       found = true;
       System.Console.WriteLine("Delivery to " + userZip + " ok.");
       break;
    }
}

if(!found) System.Console.WriteLine("Sorry - no delivery to " + userZip);


问:
Beautifulsoup doesn't get all mailto href
I am trying to find all emails on a website with the following code:

```<code>import requests
from bs4 import BeautifulSoup

website = 'http://abborup.dk/sidsteny/lejligheder-til-salg/'
response = requests.get(website)
soup = BeautifulSoup(response.content, 'html.parser')
Email_list = []
for email in soup.select('a[href^=mailto]'):
    data = email['href']
    data = data.split('?')[0]
    data = data.replace('mailto:', '')
    Email_list.append(data)
</code>```

The problem is that i do not get all of the mailto emails from the site, any ideas what i'm doing wrong?

答:
It looks like not all items are actually mailto's directly in the raw page source but generated by JavaScript.

You might be better off just regex'ing, something like:

```<code>import requests
import re

r = requests.get('http://abborup.dk/sidsteny/lejligheder-til-salg/')
emails = [
    '{}@{}'.format(*el)
    for el in re.findall('var username = "(.*?)"; var hostname = "(.*?)"', r.text)
]
</code>```

I wouldn't hold out much hope in the robustness or elegance of this approach but seems to work for your example.

Body:
I am trying to find all emails on a website with the following code:

import requests
from bs4 import BeautifulSoup

website = 'http://abborup.dk/sidsteny/lejligheder-til-salg/'
response = requests.get(website)
soup = BeautifulSoup(response.content, 'html.parser')
Email_list = []
for email in soup.select('a[href^=mailto]'):
    data = email['href']
    data = data.split('?')[0]
    data = data.replace('mailto:', '')
    Email_list.append(data)

The problem is that i do not get all of the mailto emails from the site, any ideas what i'm doing wrong?

Body:
It looks like not all items are actually mailto's directly in the raw page source but generated by JavaScript.

You might be better off just regex'ing, something like:

import requests
import re

r = requests.get('http://abborup.dk/sidsteny/lejligheder-til-salg/')
emails = [
    '{}@{}'.format(*el)
    for el in re.findall('var username = "(.*?)"; var hostname = "(.*?)"', r.text)
]

I wouldn't hold out much hope in the robustness or elegance of this approach but seems to work for your example.


问:
Generate Random numbers in array, add them together and store the answers in array
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

```<code>randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]
</code>```

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

```<code>public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}
</code>```

答:
So, answers will have 10 items, just like userAnswers.

You can therefore do, first:

```<code>answers = new int[10]
</code>```

Then you want answers[0] = num[0] + num[1]. The easiest way would be to go through num two at a time and add the values to answers. So:

```<code>int ai = 0
for(int i=0; i<20; i+=2)
    answers[ai++] = num[i] + num[i+1]
</code>```

Of course, you don't need to keep a reference to ai (answer index). You could do instead:

```<code>for(int i=0; i<20; i+=2)
    answers[i/2] = num[i] + num[i+1]
</code>```

Body:
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}

Body:
So, answers will have 10 items, just like userAnswers.

You can therefore do, first:

answers = new int[10]

Then you want answers[0] = num[0] + num[1]. The easiest way would be to go through num two at a time and add the values to answers. So:

int ai = 0
for(int i=0; i<20; i+=2)
    answers[ai++] = num[i] + num[i+1]

Of course, you don't need to keep a reference to ai (answer index). You could do instead:

for(int i=0; i<20; i+=2)
    answers[i/2] = num[i] + num[i+1]


问:
Searching via useTextEditingController of RIverpod not working
I have a textfield with controller supplied via useTextEditingController. The controller text is supposed to be a value passed to a function in a provider controller to search corresponding products and display same. However, no search results are being returned. I have confirmed via a print() statement that the value read and supposedly passed is what the user entered into the textfield. I am at my wits end as to why the results (proList) are not being returned to the callBack for display. Here are the relevant code snippets.

Please note that I took care of case sensitivity by converting search text to lowercase before query to ensure that doesn't affect the query.  Thanks for your help or pointers.

search_screen.dart

```<code>class SearchScreen extends HookConsumerWidget {
  static const routeName = '/searchScreen';
  SearchScreen({Key? key}) : super(key: key);

  late List<Product> _searchList = [];
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    List<Product> prodSearchList =
        ref.watch(productControllerProvider.notifier).products;

    final _searchTextController = useTextEditingController();
    final FocusNode _node = FocusNode();
    final _isSearchFieldEmpty = useState<bool>(true);
    bool isSearchFieldEmpty() {
      return _searchTextController.text.isEmpty;
    }

    useEffect(() {
      _searchTextController.addListener(() {
        _isSearchFieldEmpty.value = isSearchFieldEmpty();
      });
    }, [_searchTextController]);

    return Scaffold(
      bottomSheet: TextField(
        autofocus: true,
        controller: _searchTextController,
        focusNode: _node,
        decoration: kTextInputDecoration.copyWith(
          hintText: 'Item name here ...',
          filled: true,
          fillColor: Theme.of(context).cardColor,
          prefixIcon: const Icon(Icons.search),
          suffixIcon: IconButton(
            onPressed: _searchTextController.text.isEmpty
                ? null
                : () {
                    _searchTextController.clear();
                  },
            icon: Icon(Icons.close,
                color: _searchTextController.text.isNotEmpty
                    ? Colors.red
                    : Colors.grey),
          ),
        ),
        onChanged: (val) {
          _searchList =
              ref.watch(productControllerProvider.notifier).getBySearch(val);
        },
      ),
      body: _searchTextController.text.isNotEmpty && _searchList.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  SizedBox(
                    height: 50,
                  ),
                  Icon(
                    Icons.search,
                    size: 50,
                  ),
                  SizedBox(
                    height: 60,
                  ),
                  Text(
                    'Sorry no results found.',
                    style: TextStyle(fontSize: 20),
                  ),
                ],
              ),
            )
          : Padding(
              padding: const EdgeInsets.all(8.0),
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 10,
                  childAspectRatio: 2 / 3,
                  mainAxisSpacing: 10,
                ),
                itemCount: prodSearchList.length,
                itemBuilder: (context, i) {
                  if (_searchTextController.text.isNotEmpty) {
                    return FeedsProduct(
                      id: _searchList[i].id,
                      description: _searchList[i].description,
                      imageUrl: _searchList[i].imageUrl,
                      isFavorite: _searchList[i].isFavorite,
                      price: _searchList[i].price,
                      quantity: _searchList[i].quantity,
                    );
                  } else {
                    return FeedsProduct(
                      id: prodSearchList[i].id,
                      description: prodSearchList[i].description,
                      imageUrl: prodSearchList[i].imageUrl,
                      isFavorite: prodSearchList[i].isFavorite,
                      price: prodSearchList[i].price,
                      quantity: prodSearchList[i].quantity,
                    );
                  }
                },
              ),
            ),
    );
  }
}
</code>```

product_controller.dart:

```<code>final productControllerProvider = ChangeNotifierProvider<ProductListController>(
  (ref) => ProductListController(),
);

class ProductListController extends ChangeNotifier {
  // ProductListController([List<Product>? state]) : super();

  List<Product> get products => _products;

  List<Product> getByCatName(String catName) {
    List<Product> catList = _products
        .where(
            (e) => e.productCategoryName.toLowerCase() == catName.toLowerCase())
        .toList();
    return catList;
  }

  List<Product> getByBrandName(String brandName) {
    List<Product> brandList = _products
        .where((e) => e.brand.toLowerCase() == brandName.toLowerCase())
        .toList();
    return brandList;
  }

  List<Product> get popularProducts {
    return _products.where((e) => e.isPopular).toList();
  }

  Product getById(String prodId) {
    return _products.firstWhere((e) => e.id == prodId);
  }

  List<Product> getBySearch(String query) {
    List<Product> prodSearchResult = _products
        .where(
          (e) => e.title.toLowerCase() == query.toLowerCase(),
        )
        .toList();
notifyListeners();
    return prodSearchResult;
  }
</code>```

答:
Try to create _searchList as a HookState instead of a late in your class.

```<code> final _searchList = useState<List<Product>>([]);

 onChanged: (val) {
   _searchList.value = ref.watch(productControllerProvider.notifier).getBySearch(val);
 },
</code>```

Also you have your search method wrong, you don't actually have an Apple product, you have an Apple MacBookAir ... so your equal e.title.toLowerCase() == query.toLowerCase() will never be true, if you really want to search ignoring case and containing words you need to use RegExp

```<code>List<Product> getBySearch(String query) {
  final RegExp regex = RegExp(query, caseSensitive: false);
  List<Product> prodSearchResult = _products
    .where((e) => e.title.contains(regex))
    .toList();
  notifyListeners();
  return prodSearchResult;
}
</code>```

Body:
I have a textfield with controller supplied via useTextEditingController. The controller text is supposed to be a value passed to a function in a provider controller to search corresponding products and display same. However, no search results are being returned. I have confirmed via a print() statement that the value read and supposedly passed is what the user entered into the textfield. I am at my wits end as to why the results (proList) are not being returned to the callBack for display. Here are the relevant code snippets.

Please note that I took care of case sensitivity by converting search text to lowercase before query to ensure that doesn't affect the query.  Thanks for your help or pointers.

search_screen.dart

class SearchScreen extends HookConsumerWidget {
  static const routeName = '/searchScreen';
  SearchScreen({Key? key}) : super(key: key);

  late List<Product> _searchList = [];
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    List<Product> prodSearchList =
        ref.watch(productControllerProvider.notifier).products;

    final _searchTextController = useTextEditingController();
    final FocusNode _node = FocusNode();
    final _isSearchFieldEmpty = useState<bool>(true);
    bool isSearchFieldEmpty() {
      return _searchTextController.text.isEmpty;
    }

    useEffect(() {
      _searchTextController.addListener(() {
        _isSearchFieldEmpty.value = isSearchFieldEmpty();
      });
    }, [_searchTextController]);

    return Scaffold(
      bottomSheet: TextField(
        autofocus: true,
        controller: _searchTextController,
        focusNode: _node,
        decoration: kTextInputDecoration.copyWith(
          hintText: 'Item name here ...',
          filled: true,
          fillColor: Theme.of(context).cardColor,
          prefixIcon: const Icon(Icons.search),
          suffixIcon: IconButton(
            onPressed: _searchTextController.text.isEmpty
                ? null
                : () {
                    _searchTextController.clear();
                  },
            icon: Icon(Icons.close,
                color: _searchTextController.text.isNotEmpty
                    ? Colors.red
                    : Colors.grey),
          ),
        ),
        onChanged: (val) {
          _searchList =
              ref.watch(productControllerProvider.notifier).getBySearch(val);
        },
      ),
      body: _searchTextController.text.isNotEmpty && _searchList.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  SizedBox(
                    height: 50,
                  ),
                  Icon(
                    Icons.search,
                    size: 50,
                  ),
                  SizedBox(
                    height: 60,
                  ),
                  Text(
                    'Sorry no results found.',
                    style: TextStyle(fontSize: 20),
                  ),
                ],
              ),
            )
          : Padding(
              padding: const EdgeInsets.all(8.0),
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 10,
                  childAspectRatio: 2 / 3,
                  mainAxisSpacing: 10,
                ),
                itemCount: prodSearchList.length,
                itemBuilder: (context, i) {
                  if (_searchTextController.text.isNotEmpty) {
                    return FeedsProduct(
                      id: _searchList[i].id,
                      description: _searchList[i].description,
                      imageUrl: _searchList[i].imageUrl,
                      isFavorite: _searchList[i].isFavorite,
                      price: _searchList[i].price,
                      quantity: _searchList[i].quantity,
                    );
                  } else {
                    return FeedsProduct(
                      id: prodSearchList[i].id,
                      description: prodSearchList[i].description,
                      imageUrl: prodSearchList[i].imageUrl,
                      isFavorite: prodSearchList[i].isFavorite,
                      price: prodSearchList[i].price,
                      quantity: prodSearchList[i].quantity,
                    );
                  }
                },
              ),
            ),
    );
  }
}

product_controller.dart:

final productControllerProvider = ChangeNotifierProvider<ProductListController>(
  (ref) => ProductListController(),
);

class ProductListController extends ChangeNotifier {
  // ProductListController([List<Product>? state]) : super();

  List<Product> get products => _products;

  List<Product> getByCatName(String catName) {
    List<Product> catList = _products
        .where(
            (e) => e.productCategoryName.toLowerCase() == catName.toLowerCase())
        .toList();
    return catList;
  }

  List<Product> getByBrandName(String brandName) {
    List<Product> brandList = _products
        .where((e) => e.brand.toLowerCase() == brandName.toLowerCase())
        .toList();
    return brandList;
  }

  List<Product> get popularProducts {
    return _products.where((e) => e.isPopular).toList();
  }

  Product getById(String prodId) {
    return _products.firstWhere((e) => e.id == prodId);
  }

  List<Product> getBySearch(String query) {
    List<Product> prodSearchResult = _products
        .where(
          (e) => e.title.toLowerCase() == query.toLowerCase(),
        )
        .toList();
notifyListeners();
    return prodSearchResult;
  }

Body:
Try to create _searchList as a HookState instead of a late in your class.

 final _searchList = useState<List<Product>>([]);

 onChanged: (val) {
   _searchList.value = ref.watch(productControllerProvider.notifier).getBySearch(val);
 },

Also you have your search method wrong, you don't actually have an Apple product, you have an Apple MacBookAir ... so your equal e.title.toLowerCase() == query.toLowerCase() will never be true, if you really want to search ignoring case and containing words you need to use RegExp

List<Product> getBySearch(String query) {
  final RegExp regex = RegExp(query, caseSensitive: false);
  List<Product> prodSearchResult = _products
    .where((e) => e.title.contains(regex))
    .toList();
  notifyListeners();
  return prodSearchResult;
}


问:
Is this more efficient way of using vectors in C++
I want to ask a question about vectors in C++. I am learning about vectors at the moment, so I want to ask about it.

Is this code more efficient

```<code>vector<int> numbers;
numbers.reserve(10);
for (int i = 0; i < 10; i++){
   numbers.push_back(i + 1);
}
</code>```

than this

```<code>vector<int> numbers;
for (int i = 0; i < 10; i++){
   numbers.push_back(i + 1);
}
</code>```

?

答:
Yes. Although for '10' you will not notice a difference.

reserve will immediately reserve memory on the heap for the amount of elements you specify.

Without reserve, vector will start with a "reasonable" value. Whenever it needs more space to put elements in, it will reallocate and reassign all elements. This takes time, so not having to do this is faster.

But: don't go adding reserve to all your code.

It clutters your code.

You can get it wrong, like, reserving 10, but requiring 11.

My advice would be to use reserve, only after you have determined that reallocation causes performance issues.

Body:
I want to ask a question about vectors in C++. I am learning about vectors at the moment, so I want to ask about it.

Is this code more efficient

vector<int> numbers;
numbers.reserve(10);
for (int i = 0; i < 10; i++){
   numbers.push_back(i + 1);
}

than this

vector<int> numbers;
for (int i = 0; i < 10; i++){
   numbers.push_back(i + 1);
}

?


问:
Is there a python module that provides a test for equivalent Unicode characters?
There are multiple Unicode characters that are visually similar, such as:

```<code>":" and "꞉"     U+A789
"?" and "？"    U+FF1F
"*" and "⁎"     U+204E
"'", "`", "‘", "’", and "ʻ"
</code>```

There are also characters with and without diacritical marks, such as:

```<code>"c" and "ç"     U+00E7
"E" and "É"     U+00C9
"I" and "İ"     U+00ED
"i" and "ı"     U+0131
</code>```

I'd like to compare text from various sources, with effectively the same words comparing as equal, such as:

```<code>"naive" and "naïve"
"facade" and "façade"
"Hawai'i" and "Hawaiʻi"
"don't" and "don’t"
"letter 'A'" and "letter ‘A’" and "letter `A'"
"letter "B"" and "letter "“B”"
</code>```

Is there a module that provides tests of equivalence between such characters?

```<code>import unicode
if x != y and not unicode.same_character(x, y):
</code>```

答:
I recommend reading about normalization forms.
https://towardsdatascience.com/difference-between-nfd-nfc-nfkd-and-nfkc-explained-with-python-code-e2631f96ae6c

Also, this will help you with diacritical marks.
What is the best way to remove accents (normalize) in a Python unicode string?

Probably this code does what you want. It is written in a form of an app. You choose between 2 comparison functions. You can decide which is yours.

```<code>import unicodedata
import unidecode

if input("Ignore diacritical?\t") in ("y","yes"):
    norm_func= lambda s: unidecode.unidecode(unicodedata.normalize("NFKD",s))
else:
    norm_func= lambda s: unicodedata.normalize("NFKD", s)

same_characted= lambda c1,c2: norm_func(c1)==norm_func(c2)

#Test for Greek question mark.
print(same_characted("\x3b", "\u037E"))
print(same_characted(";",";"))
#Test for diacritical
print(same_characted("a", "ą"))
#Test for somethink else
print(same_characted("a", "b"))
</code>```

Body:
There are multiple Unicode characters that are visually similar, such as:

":" and "꞉"     U+A789
"?" and "？"    U+FF1F
"*" and "⁎"     U+204E
"'", "`", "‘", "’", and "ʻ"

There are also characters with and without diacritical marks, such as:

"c" and "ç"     U+00E7
"E" and "É"     U+00C9
"I" and "İ"     U+00ED
"i" and "ı"     U+0131

I'd like to compare text from various sources, with effectively the same words comparing as equal, such as:

"naive" and "naïve"
"facade" and "façade"
"Hawai'i" and "Hawaiʻi"
"don't" and "don’t"
"letter 'A'" and "letter ‘A’" and "letter `A'"
"letter "B"" and "letter "“B”"

Is there a module that provides tests of equivalence between such characters?

import unicode
if x != y and not unicode.same_character(x, y):

Body:
I recommend reading about normalization forms.
https://towardsdatascience.com/difference-between-nfd-nfc-nfkd-and-nfkc-explained-with-python-code-e2631f96ae6c

Also, this will help you with diacritical marks.
What is the best way to remove accents (normalize) in a Python unicode string?

Probably this code does what you want. It is written in a form of an app. You choose between 2 comparison functions. You can decide which is yours.

import unicodedata
import unidecode

if input("Ignore diacritical?\t") in ("y","yes"):
    norm_func= lambda s: unidecode.unidecode(unicodedata.normalize("NFKD",s))
else:
    norm_func= lambda s: unicodedata.normalize("NFKD", s)

same_characted= lambda c1,c2: norm_func(c1)==norm_func(c2)

#Test for Greek question mark.
print(same_characted("\x3b", "\u037E"))
print(same_characted(";",";"))
#Test for diacritical
print(same_characted("a", "ą"))
#Test for somethink else
print(same_characted("a", "b"))


问:
Apache Syncope connected with LDAP doesn't update user
I'm working with Apache Syncope 2.1.10 and I succesfully connect with LDAP server for user and group creation but when I try to update a field I get de following error in the update propagation task:

[LDAP: error code 68 - Entry Already Exists]

In the Mapping Rules I have the next ConnObjectLink:

'cn='+cn+',ou=myCompany, DC=COM,DC=local'

答: I think, it's not relevant about ConnObjectLink. it may be related to push task.if you create a push task, syncope ask you Matching and Unmatching rules. you should choose uptade for matching rule and allow update. I found this document. May be that documents can help you.</p>


问:
How do I unload a library after completing a task?
After completing a task I need to unload a library because it is disturbing other variables and functions.</p>

答: Probably by using $this->libname = null; ? Just a guess. But your problem shouldn't occur in the first place, so I suggest you check your code.</p>


问:
how to flush the ZipOutputStream periodically in java
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

```<code>try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}
</code>```

```<code>public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}
</code>```

答:
You want to use chunked encoding to send a file that large otherwise the servlet container will try and figure out the size of the data you are trying to send before sending it so it can set the Content-Length header.  Since you are compressing files you don't know the size of the data you're sending.  Chunked-Encoding allows you to send pieces of the response in smaller chunks.  Don't set the content length of the stream.  You might try using curl or something to see the HTTP headers in the response your getting from the server.  If it isn't chunked then you'll want to figure that out.  You'll want to research how to force the servlet container to send chunked encoding.  You might have to add this to the response header to make the servlet container send it chunked.

```<code>response.setHeader("Transfer-Encoding", "chunked");
</code>```

The other option would be to compress the file into a temporary file with File.createTemp(), and then send the contents of that.  If you compress to a temp file first then you can know how big the file is and set the content length for the servlet.

Body:
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}

public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}

Body:
You want to use chunked encoding to send a file that large otherwise the servlet container will try and figure out the size of the data you are trying to send before sending it so it can set the Content-Length header.  Since you are compressing files you don't know the size of the data you're sending.  Chunked-Encoding allows you to send pieces of the response in smaller chunks.  Don't set the content length of the stream.  You might try using curl or something to see the HTTP headers in the response your getting from the server.  If it isn't chunked then you'll want to figure that out.  You'll want to research how to force the servlet container to send chunked encoding.  You might have to add this to the response header to make the servlet container send it chunked.

response.setHeader("Transfer-Encoding", "chunked");

The other option would be to compress the file into a temporary file with File.createTemp(), and then send the contents of that.  If you compress to a temp file first then you can know how big the file is and set the content length for the servlet.


答:
Yes. Or at least it won't be slower. If you reserve some space for a vector, it won't have to move every time it reaches its capacity. Though if you didn't know, you can just provide size in vector's constructor like that:

vector<int> numbers(10);
for (int i = 0; i < 10; i++)
    numbers[i] = i + 1;
```
<p>and it's even better than reserving memory (it's not slower and can help in some cases).
Also, a nice way of doing this might be using stl's function iota (<code>#include <numeric></code>):</p>
<pre class="lang-cpp prettyprint-override"><code>vector<int> numbers(10);
iota(numbers.begin(), numbers.end(), 1);
</code>```

Title: Is this more efficient way of using vectors in C++

Body:
Yes. Or at least it won't be slower. If you reserve some space for a vector, it won't have to move every time it reaches its capacity. Though if you didn't know, you can just provide size in vector's constructor like that:

vector<int> numbers(10);
for (int i = 0; i < 10; i++)
    numbers[i] = i + 1;

and it's even better than reserving memory (it's not slower and can help in some cases).
Also, a nice way of doing this might be using stl's function iota (#include <numeric>):

vector<int> numbers(10);
iota(numbers.begin(), numbers.end(), 1);


问:
@WebMvcTest needs @Import(SecurityConfig.class) to enable SpringSecurity
First of all, its important to specify that the app is already deployed and our spring security configuration works. If an unauthenticated user tries to access to any endpoint of the API it returns 401 Unauthorized.

Following, this sample example, I want to test a Controller with @WebMvcTest and spring security

@WebMvcTest(EmployeeController.class)
@Import(SecurityConfig.class)
class EmployeeControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    protected MockMvc mvc;

    @MockBean
    private EmployeeService service;

    @BeforeEach
    public void setUp() {
        this.mvc = MockMvcBuilders
                .webAppContextSetup(ctx)
                .apply(springSecurity())
                .build();
    }

    @Test
    void unauthorized_role_should_return_401() {

       mvc.perform(get("/employees/1").accept(MediaType.APPLICATION_JSON)
            .with(SecurityMockMvcRequestPostProcessors.user("manager").roles("UNKNOWN")))
            .andExpect(status().isUnauthorized())
    }
}
```

This code works, but I don't understand why I need to import the SecurityConfig class to the test class. Indeed, if I remove the @Import, mockMvc returns 200. But, every sample project that I found over Github simply use @WebMvcTest even if the project has a SecurityConfig class

答:
There is no need to configure extra thing in order to enable spring security when using @WebMvcTest as @WebMvcTest will enable it automatically.

But if you customise the spring-security by creating your own beans , you still have to define these customised beans for the tests for the customisation to work. @Import is one of the way to define these beans. By consolidating their configuration into a SecurityConfig , it can keep your test cases DRY because if a test case need to test with the security stuff , it just need to import this SecurityConfig rather repeatedly do the same configuration for each test.

So it is rather a code design decision which is an application specific and hence it is normal that not every project will have the same kind of setup.

Body:
First of all, its important to specify that the app is already deployed and our spring security configuration works. If an unauthenticated user tries to access to any endpoint of the API it returns 401 Unauthorized.

Following, this sample example, I want to test a Controller with @WebMvcTest and spring security

@WebMvcTest(EmployeeController.class)
@Import(SecurityConfig.class)
class EmployeeControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    protected MockMvc mvc;

    @MockBean
    private EmployeeService service;

    @BeforeEach
    public void setUp() {
        this.mvc = MockMvcBuilders
                .webAppContextSetup(ctx)
                .apply(springSecurity())
                .build();
    }

    @Test
    void unauthorized_role_should_return_401() {

       mvc.perform(get("/employees/1").accept(MediaType.APPLICATION_JSON)
            .with(SecurityMockMvcRequestPostProcessors.user("manager").roles("UNKNOWN")))
            .andExpect(status().isUnauthorized())
    }
}

This code works, but I don't understand why I need to import the SecurityConfig class to the test class. Indeed, if I remove the @Import, mockMvc returns 200. But, every sample project that I found over Github simply use @WebMvcTest even if the project has a SecurityConfig class


问:
How to install Solana on Windows?
I ran:

curl https://release.solana.com/v1.8.3/solana-install-init-x86_64-pc-windows-msvc.exe --output C:\solana-install-tmp\solana-install-init.exe --create-dirs

In my Windows command prompt and it showed up like this:

It seemed like it installed - so then I did solana --version and this is what happened:

'solana' is not recognized as an internal or external command, operable program or batch file.

I ran solana --version in Powershell, Git Bash, VS Code Terminal, and Command Prompt and it gives the same output.

How do I install Solana?

Thank you!

答: you need to make sure you are running as admin I ran into the same issue</p>

Title: How to install Solana on Windows?


问:
Buttons with alternate style not responding to ngIf
Context: I have a dialog that is shown in many places and I need two type of dialog buttons

default: color="accent", ENTER presses this button, click as usual

regular: no color specified, click as usual

And for that I decided to create a DialogButtonComponent

<ng-container *ngIf="isDefault else regularButton">
    <button mat-button mat-dialog-close class="action" color="accent" #btnFocus [autofocus]="btnFocus.focus()"
        (click)="clickHandler()" (keyup.enter)="clickHandler()">
        DEF-{{text}}
    </button>
</ng-container>
<ng-template #regularButton>
    <button mat-button mat-dialog-close class="action nonDefault" (click)="clickHandler()">
        {{text}}
    </button>
</ng-template>
```
<pre class="lang-js prettyprint-override"><code>import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'wss-dialog-button',
  templateUrl: './dialog-button.component.html',
  styleUrls: ['./dialog-button.component.scss']
})
export class DialogButtonComponent implements OnInit {
  @Input() text: string = '';
  @Input() isDefault: boolean = false;
  @Output() click: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit(): void {
    console.log(this.isDefault);
  }

  public clickHandler() {
    this.click.emit(true);
  }

}
</code>```

When I try to use this in a dialog I have a weird behavior, both buttons are being shown as default

How can that be when the condition is the opposite

on 1st button isDefault="{{!data.confirmIsDefault}}"

on 2nd button isDefault="{{data.confirmIsDefault}}"

<mat-dialog-actions class="buttons">
    <ng-container *ngIf="!data.saveFunction; else showSaveAndContinue">
        <wss-dialog-button isDefault="{{!data.confirmIsDefault}}" text="1+{{data.cancel}}" (click)="onCancelClick()">
        </wss-dialog-button>
    </ng-container>
    <wss-dialog-button isDefault="{{data.confirmIsDefault}}" text="2+{{data.closeOrConfirm}}" (click)="cancelOrClose()">
    </wss-dialog-button>
    <ng-template #showSaveAndContinue>
        <wss-dialog-button isDefault="{{!data.confirmIsDefault}}" text="3+{{data.saveAndContinue}}"
            (click)="onSaveAndContinueClick()">
        </wss-dialog-button>
    </ng-template>
</mat-dialog-actions>
```

答:
There is a certain magic in this website, as soon as you post a question you find the solution

What I needed was to pass the input parameters with square brackets

before isDefault="{{!data.confirmIsDefault}}"

now [isDefault]="!data.confirmIsDefault"

<mat-dialog-actions class="buttons">
    <ng-container *ngIf="!data.saveFunction; else showSaveAndContinue">
        <wss-dialog-button [isDefault]="!data.confirmIsDefault" [text]="data.cancel" (click)="onCancelClick()">
        </wss-dialog-button>
    </ng-container>
    <wss-dialog-button [isDefault]="data.confirmIsDefault" [text]="data.closeOrConfirm" (click)="cancelOrClose()">
    </wss-dialog-button>
    <ng-template #showSaveAndContinue>
        <wss-dialog-button [isDefault]="!data.confirmIsDefault" [text]="data.saveAndContinue"
            (click)="onSaveAndContinueClick()">
        </wss-dialog-button>
    </ng-template>
</mat-dialog-actions>
```

Body:
Context: I have a dialog that is shown in many places and I need two type of dialog buttons

default: color="accent", ENTER presses this button, click as usual

regular: no color specified, click as usual

And for that I decided to create a DialogButtonComponent

<ng-container *ngIf="isDefault else regularButton">
    <button mat-button mat-dialog-close class="action" color="accent" #btnFocus [autofocus]="btnFocus.focus()"
        (click)="clickHandler()" (keyup.enter)="clickHandler()">
        DEF-{{text}}
    </button>
</ng-container>
<ng-template #regularButton>
    <button mat-button mat-dialog-close class="action nonDefault" (click)="clickHandler()">
        {{text}}
    </button>
</ng-template>

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'wss-dialog-button',
  templateUrl: './dialog-button.component.html',
  styleUrls: ['./dialog-button.component.scss']
})
export class DialogButtonComponent implements OnInit {
  @Input() text: string = '';
  @Input() isDefault: boolean = false;
  @Output() click: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit(): void {
    console.log(this.isDefault);
  }

  public clickHandler() {
    this.click.emit(true);
  }

}

When I try to use this in a dialog I have a weird behavior, both buttons are being shown as default

How can that be when the condition is the opposite

on 1st button isDefault="{{!data.confirmIsDefault}}"

on 2nd button isDefault="{{data.confirmIsDefault}}"

<mat-dialog-actions class="buttons">
    <ng-container *ngIf="!data.saveFunction; else showSaveAndContinue">
        <wss-dialog-button isDefault="{{!data.confirmIsDefault}}" text="1+{{data.cancel}}" (click)="onCancelClick()">
        </wss-dialog-button>
    </ng-container>
    <wss-dialog-button isDefault="{{data.confirmIsDefault}}" text="2+{{data.closeOrConfirm}}" (click)="cancelOrClose()">
    </wss-dialog-button>
    <ng-template #showSaveAndContinue>
        <wss-dialog-button isDefault="{{!data.confirmIsDefault}}" text="3+{{data.saveAndContinue}}"
            (click)="onSaveAndContinueClick()">
        </wss-dialog-button>
    </ng-template>
</mat-dialog-actions>


问:
Why would people use `$a = $b = 2;` in PHP?
Why would people use this format? Whats different between this and $a=2; $b=2;?

答: Its simply the shorter way to set both variables to 2.</p>


问:
HTML div goes on next line even though width is 33%
Please help me understand this. Here is my HTML (body)

```<code><body>
    <main class="container">
        <div class="row">
            <div class="col">Sparky</div>
            <div class="col">Vegeta</div>
            <div class="col">Flufferpants</div>
        </div>
    </main>
</body>
</code>```

Here is my CSS

```<code>* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
}
.col {
    display: inline-block;
    width: 33%;
    height: 200px;
}
</code>```

I am trying to have the 3 cols be on a single row, evenly spaced apart. I know this is easily done through flexbox, but I wanted to try using the width property manually.

Even when I set each of the col to be width 33%, it still rolls onto the next line. What's going on here?

https://jsfiddle.net/zd29ewb6/

Thanks

答:
use display flex on the row</p>
```<code>* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
    display: flex;
}
.col {
    width: 33%;
    height: 200px;
}
</code>```

Body:
Please help me understand this. Here is my HTML (body)

Sparky

Vegeta

Flufferpants

Here is my CSS

* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
}
.col {
    display: inline-block;
    width: 33%;
    height: 200px;
}

I am trying to have the 3 cols be on a single row, evenly spaced apart. I know this is easily done through flexbox, but I wanted to try using the width property manually.

Even when I set each of the col to be width 33%, it still rolls onto the next line. What's going on here?

https://jsfiddle.net/zd29ewb6/

Thanks

Body:
use display flex on the row

* {
    font-size: 25px;
    /* box-sizing: border-box; */
}
body {
    background-color: gray;
}
.container {
    max-width: 600px;
    margin: 0 auto;
    background-color: lightgoldenrodyellow;
}
.row {
    background-color: rgb(119, 103, 134);
    width: 100%;
    display: flex;
}
.col {
    width: 33%;
    height: 200px;
}


问:
Referencing Multiple Non-Terminals in Production with Same Name in Yacc
Let's assume I have the production:

```<code>Expression                             // These are my semantic actions
  : Expression PLUS_TOKEN Expression ( create_node(Expression, Expression) )
  | SimpleExpression                 ( SimpleExpression ) (* Returns a node of type expression *)
</code>```

Notice how I can't tell which Expression is which in my top most production's semantic action. How do I refer to the left and right Expression? What if I have three or more 'Expression's appear in the same production?

答:
Reference: http://www.smlnj.org/doc/ML-Yacc/mlyacc002.html

According to ML-Yacc documentation we refer to non-terminals with the following notation:

```<code>{non-terminal}{n+1}
</code>```

such that n is the number of occurrences of the non-terminal to the left of the symbol. If n equals one then we can just use the non-terminal name.

Hence, the above example would look like this:

```<code>Expression                             // These are my semantic actions
  : Expression PLUS_TOKEN Expression ( create_node(Expression1, Expression2) )
  | SimpleExpression                 ( SimpleExpression ) (* Returns a node of type expression *)
</code>```

Body:
Let's assume I have the production:

Expression                             // These are my semantic actions
  : Expression PLUS_TOKEN Expression ( create_node(Expression, Expression) )
  | SimpleExpression                 ( SimpleExpression ) (* Returns a node of type expression *)

Notice how I can't tell which Expression is which in my top most production's semantic action. How do I refer to the left and right Expression? What if I have three or more 'Expression's appear in the same production?

Body:
Reference: http://www.smlnj.org/doc/ML-Yacc/mlyacc002.html

According to ML-Yacc documentation we refer to non-terminals with the following notation:

{non-terminal}{n+1}

such that n is the number of occurrences of the non-terminal to the left of the symbol. If n equals one then we can just use the non-terminal name.

Hence, the above example would look like this:

Expression                             // These are my semantic actions
  : Expression PLUS_TOKEN Expression ( create_node(Expression1, Expression2) )
  | SimpleExpression                 ( SimpleExpression ) (* Returns a node of type expression *)


问:
The non-abstract class 'InternalSelectableMathState' is missing implementations for these members
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:

TextSelectionDelegate.copySelection

TextSelectionDelegate.cutSelection

TextSelectionDelegate.pasteText

TextSelectionDelegate.selectAll
Try to either

provide an implementation,

inherit an implementation from a superclass or mixin,

mark the class as abstract, or

provide a 'noSuchMethod' implementation.

class InternalSelectableMathState extends State
^^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here.
void copySelection(SelectionChangedCause cause);
^^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here.
void cutSelection(SelectionChangedCause cause);
^^^^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here.
Future pasteText(SelectionChangedCause cause);
^^^^^^^^^
/C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here.
void selectAll(SelectionChangedCause cause);
^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_datetime_picker-1.5.1/lib/flutter_datetime_picker.dart:311:32: Warning: Operand of null-aware operation '??' has type 'Color' which excludes null.

'Color' is from 'dart:ui'.
color: theme.backgroundColor ?? Colors.white,
^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/button.dart:200:14: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'.
child: AnimatedScale(
^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/switch.dart:167:20: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'.
child: AnimatedScale(
^^^^^^^^^^^^^

FAILURE: Build failed with an exception.

Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 2m 25s
Exception: Gradle task assembleDebug failed with exit code 1

答:
You need to upgrade your dependencies to fix this issue, so run:

flutter pub upgrade