问:
Why do we use "for" attribute inside label tag?
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor```
</div>
</div>
</p>
<p>Code2</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label></code>```

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?

答:
To be able to use the label with the check box.
E.g., when rendered, click the label and it will toggle the check box ticked state.

Edit: Further to this, it allows putting the label anywhere on the page.

Body:
I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand

Code1

<input id="indoor" type="radio" name="indoor-outdoor">
Indoor

Code2

<input id="loving" type="checkbox" name="personality"> Loving

<input type="checkbox" name="personality"> Loving

I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?


来源: stackexchange

问:
Android ConnectivityManager can't find permission ACCESS_NETWORK_STATE
I'm trying to read some data from a SpringBoot API request. I've added permission to the AndroidManifest.xml:

< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

My code that tries to access network state:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

```<code>        Network nw = connectivityManager.getActiveNetwork();
        if (nw == null){
            return false;
        }

        NetworkCapabilities actNw = connectivityManager.getNetworkCapabilities(nw);

        return actNw != null & (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
    } else {
        NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
        return nwInfo != null && nwInfo.isConnected();
    }
</code>```

And the problems that make my app doesn't work:

Android problems

答:
You have to declare the permission in your AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

Android requires access to certain components and functionality to be declared in the manifest. Some you only need to declare in order to use, such as INTERNET and ACCESS_NETWORK_STATE, others require various additional steps dependent on their protection level.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to read some data from a SpringBoot API request. I've added permission to the AndroidManifest.xml:

< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

My code that tries to access network state:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

        Network nw = connectivityManager.getActiveNetwork();
        if (nw == null){
            return false;
        }

        NetworkCapabilities actNw = connectivityManager.getNetworkCapabilities(nw);

        return actNw != null & (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
    } else {
        NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
        return nwInfo != null && nwInfo.isConnected();
    }

And the problems that make my app doesn't work:

Android problems

Body:
You have to declare the permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Android requires access to certain components and functionality to be declared in the manifest. Some you only need to declare in order to use, such as INTERNET and ACCESS_NETWORK_STATE, others require various additional steps dependent on their protection level.


问:
C# - using ColorDialog across forms
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

```<code>private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}
</code>```

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

```<code>if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;
</code>```

答: Pass the Color on via the Constructor not a string. If this is not possibly for whatever reason, you could create a ColorConfigClass that holds the required Color and you can set it when used.</p>

ContentLicense: CC BY-SA 3.0

Title: C# - using ColorDialog across forms

Body:
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;


问:
how to convert df.info() into data frame. df.info()
how to convert df.info() into  data_frame.

I want to be able to merge this dataframe with other dataframe.

```<code>df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 458 entries, 0 to 457
Data columns (total 9 columns):
Name        457 non-null object
Team        457 non-null object
Number      457 non-null float64
Position    457 non-null object
Age         457 non-null float64
Height      457 non-null object
Weight      457 non-null float64
College     373 non-null object
Salary      446 non-null float64
dtypes: float64(4), object(5)
memory usage: 32.3+ KB
</code>```

答:
Building off of the previous answer. The solution below will place the string collected from the buffer directly into a pandas DataFrame without having to save a temp file to disk

```<code>import io
buf = io.StringIO()
df.info(buf=buf)
s = buf.getvalue()
lines = [line.split() for line in s.splitlines()[3:-2]]
pd.DataFrame(lines)
</code>```

Explaination:

s.splitlines() - creates a list from the string where a new line character is found

indexing [3:-2] - removes the first three lines and last two so that it will fit nicely into columns for the data frame

Body:
how to convert df.info() into  data_frame.

I want to be able to merge this dataframe with other dataframe.

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 458 entries, 0 to 457
Data columns (total 9 columns):
Name        457 non-null object
Team        457 non-null object
Number      457 non-null float64
Position    457 non-null object
Age         457 non-null float64
Height      457 non-null object
Weight      457 non-null float64
College     373 non-null object
Salary      446 non-null float64
dtypes: float64(4), object(5)
memory usage: 32.3+ KB

Body:
Building off of the previous answer. The solution below will place the string collected from the buffer directly into a pandas DataFrame without having to save a temp file to disk

import io
buf = io.StringIO()
df.info(buf=buf)
s = buf.getvalue()
lines = [line.split() for line in s.splitlines()[3:-2]]
pd.DataFrame(lines)

Explaination:

s.splitlines() - creates a list from the string where a new line character is found

indexing [3:-2] - removes the first three lines and last two so that it will fit nicely into columns for the data frame


问:
Select all values from a column til last value
In column A I have several values. As values are added or removed, in excel vba I want to extract all values from column A down to the last value

How can i create this?

```<code>Werte = Sheets("Messauswertung").Range("A1:A100").Value
</code>```

This is not a the optimal way

Thanks!

答:
On way is

```<code>dim lastRow as Long
With Sheets("Messauswertung")
   lastRow = .Cells(rows.Count, 1).End(xlUp).Row 'last used row
   Werte = .Range("A1:A" & lastRow).Value
End With
</code>```

By the way, each sheet has a .Name but also a .CodeName (Sheet1).

I find it much better to (eventually change the CodeName and) use that one.

Easier to read, to write, and protected from name changes by users.

Body:
In column A I have several values. As values are added or removed, in excel vba I want to extract all values from column A down to the last value

How can i create this?

Werte = Sheets("Messauswertung").Range("A1:A100").Value

This is not a the optimal way

Thanks!

Body:
On way is

dim lastRow as Long
With Sheets("Messauswertung")
   lastRow = .Cells(rows.Count, 1).End(xlUp).Row 'last used row
   Werte = .Range("A1:A" & lastRow).Value
End With

By the way, each sheet has a .Name but also a .CodeName (Sheet1).

I find it much better to (eventually change the CodeName and) use that one.

Easier to read, to write, and protected from name changes by users.


问:
The requested module 'graphql' is expected to be of type CommonJS
I'm running my service with:

"start": "NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --es-module-specifier-resolution=node --no-warnings dist/server-new/server.js"

package.json - notice it's type module

```<code>{
    "name": "some-name",
    "license": "UNLICENSED",
    "version": "0.0.0",
    "description": "",
    "type": "module",
    "engines": {
        "node": "14.x",
        "npm": "6.14.x"
    },
...
}
</code>```

tsconfig.json

```<code>{
    "extends": "../../tsconfig",
    "compilerOptions": {
        "noEmit": false,
        "rootDir": "."           /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
        "outDir": "../../dist"  /* Redirect output structure to the directory. */
    },
    "module": "ESNext",
    "include": ["./*.ts", "package.json"],
    "resolveJsonModule": true
}
</code>```

server.ts - imports api.js as an ES6 module

```<code>import cluster from 'cluster';
import os from 'os';
import App from './api.js';

...
    App.listen(port, () => {
        console.log(`express is listening on port ${port}`);
    });
</code>```

api.ts - is able to import express but having problem importing GraphQL common JS modules

```<code>import compression from 'compression';
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { buildSchema } from 'graphql';
import CompanyController from './Controllers/CompanyController';

const App = express()
    .use(compression())
    ....
    );
export default App;
</code>```

Error during the start script:
SyntaxError: The requested module 'graphql' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.

referring to import { buildSchema } from 'graphql';

So I tried this:

import * as graphQL from 'graphql';
const { buildSchema } = graphQL;
```
<p>but then I get the TS error here...maybe I need to resolve this now but not sure how:</p>
<p><code>TypeError: buildSchema is not a function</code></p>
<p><strong>Also Tried:</strong></p>
```// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildSchema } = require('graphql');
```

Error: ReferenceError: require is not defined

So I'm not sure how in the world I'll import these two items here into api.ts.

GraphQL docs

答:
Got this while running ESM modules targeting ES2022 on Windows and Node 14.

Updating to Node 16 fixed the issue.

Body:
I'm running my service with:

"start": "NODE_ENV=production node --optimize_for_size --trace-warnings --experimental-json-modules --es-module-specifier-resolution=node --no-warnings dist/server-new/server.js"

package.json - notice it's type module

{
    "name": "some-name",
    "license": "UNLICENSED",
    "version": "0.0.0",
    "description": "",
    "type": "module",
    "engines": {
        "node": "14.x",
        "npm": "6.14.x"
    },
...
}

tsconfig.json

{
    "extends": "../../tsconfig",
    "compilerOptions": {
        "noEmit": false,
        "rootDir": "."           /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
        "outDir": "../../dist"  /* Redirect output structure to the directory. */
    },
    "module": "ESNext",
    "include": ["./*.ts", "package.json"],
    "resolveJsonModule": true
}

server.ts - imports api.js as an ES6 module

import cluster from 'cluster';
import os from 'os';
import App from './api.js';

...
    App.listen(port, () => {
        console.log(`express is listening on port ${port}`);
    });

api.ts - is able to import express but having problem importing GraphQL common JS modules

import compression from 'compression';
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { buildSchema } from 'graphql';
import CompanyController from './Controllers/CompanyController';

const App = express()
    .use(compression())
    ....
    );
export default App;

Error during the start script:
SyntaxError: The requested module 'graphql' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.

referring to import { buildSchema } from 'graphql';

So I tried this:

import * as graphQL from 'graphql';
const { buildSchema } = graphQL;

but then I get the TS error here...maybe I need to resolve this now but not sure how:

TypeError: buildSchema is not a function

Also Tried:

// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildSchema } = require('graphql');

Error: ReferenceError: require is not defined

So I'm not sure how in the world I'll import these two items here into api.ts.

GraphQL docs


问:
SQL: Compare 2 rows in the same table and output result when conditions are met
I am newbie to SQL, Apologies if this is a repeated type of question, tried searching for answers in the forum but couldn't find any answers.
I have created a temp table as below:

```<code>Drop TABLE if EXISTS #temp
Create table #temp(ID int, Country VARCHAR(40), ItemCount int, DeliveryDate Date, Itemtype VARCHAR(40) )
insert #temp(id,Country,itemCount,DeliveryDate,Itemtype)
Select
             3012111,'Dublin',     100, '01-01-2022', 'Head Gears'
union select 2012111,'Dublin',     200, '01-05-2022', 'Head Gears'
union select 2012112,'Australia',  300, '01-03-2022', 'Knee Pad'
union select 2012110,'Australia',  100, '01-04-2022', 'Head Gears'
union select 2012113,'Singapore',  150, '01-05-2022', 'Head Gears'
union select 2012114,'Singapore',  200, '01-07-2022', 'FootWear'
union select 2012116,'Brazil',     500, '01-08-2022', 'Head Gears'
union select 2012115,'Brazil',     300, '01-06-2022', 'Head Gears'
union select 2012117,'Indonesia',  150, '01-10-2022', 'Foot Wear'
</code>```

I am trying to write a query to output results from the temp table only when the following conditions are met:

Grouped by "Country,  compare the Itemcount and delivery date

Return output only if the delivery date of the lowest itemcount for a given
country by itemtype "Head Gears" is before the largest itemcount. If
there is only one delivery for a given country by Itemtype "Head
Gears", don't return anything as an output.

Tried this code but couldn't finish it to get the desired output:

```<code>Select X.Country, min(id) Id, X.ItemCount
from (
select Country, max(itemCount) itemCount
from #temp
group by Country
) X
inner join #temp T
on X.Country = T.Country
and X.itemCount = T.ItemCount
group by X.Country, X.itemCount
</code>```

This is the output I need: https://i.stack.imgur.com/3mHWD.png

Thanks for the help!

答:
I have assumed you are using SQL Server.
Also, If I have understood your question then I think that your image for the output you need is not correct. I think that for the data you provided your result needs to be Dublin 100 and not Dublin 200 ?

```<code>with t1 as (
select a.*
from #temp a
where a.country in (select b.country
                    from #temp b
                    group by b.country
                    having min(b.ItemCount) = a.ItemCount)),
t2 as (select a.*
from #temp a
where a.country in (select b.country
                    from #temp b
                    group by b.country
                    having max(b.ItemCount) = a.ItemCount))
select t1.country, t1.id, t1.ItemCount, t1.DeliveryDate, t1.Itemtype
from t1
left join t2 on t1.country = t2.country
where t1.DeliveryDate < t2.DeliveryDate
and t1.Itemtype = 'Head Gears'
and t1.Itemtype = t2.Itemtype;
</code>```

I believe this can be written better but I hope this helps...

Here is the fiddle you where you can see the code in action: clickhere

Body:
I am newbie to SQL, Apologies if this is a repeated type of question, tried searching for answers in the forum but couldn't find any answers.
I have created a temp table as below:

Drop TABLE if EXISTS #temp
Create table #temp(ID int, Country VARCHAR(40), ItemCount int, DeliveryDate Date, Itemtype VARCHAR(40) )
insert #temp(id,Country,itemCount,DeliveryDate,Itemtype)
Select
             3012111,'Dublin',     100, '01-01-2022', 'Head Gears'
union select 2012111,'Dublin',     200, '01-05-2022', 'Head Gears'
union select 2012112,'Australia',  300, '01-03-2022', 'Knee Pad'
union select 2012110,'Australia',  100, '01-04-2022', 'Head Gears'
union select 2012113,'Singapore',  150, '01-05-2022', 'Head Gears'
union select 2012114,'Singapore',  200, '01-07-2022', 'FootWear'
union select 2012116,'Brazil',     500, '01-08-2022', 'Head Gears'
union select 2012115,'Brazil',     300, '01-06-2022', 'Head Gears'
union select 2012117,'Indonesia',  150, '01-10-2022', 'Foot Wear'

I am trying to write a query to output results from the temp table only when the following conditions are met:

Grouped by "Country,  compare the Itemcount and delivery date

Return output only if the delivery date of the lowest itemcount for a given
country by itemtype "Head Gears" is before the largest itemcount. If
there is only one delivery for a given country by Itemtype "Head
Gears", don't return anything as an output.

Tried this code but couldn't finish it to get the desired output:

Select X.Country, min(id) Id, X.ItemCount
from (
select Country, max(itemCount) itemCount
from #temp
group by Country
) X
inner join #temp T
on X.Country = T.Country
and X.itemCount = T.ItemCount
group by X.Country, X.itemCount

This is the output I need: https://i.stack.imgur.com/3mHWD.png

Thanks for the help!

Body:
I have assumed you are using SQL Server.
Also, If I have understood your question then I think that your image for the output you need is not correct. I think that for the data you provided your result needs to be Dublin 100 and not Dublin 200 ?

with t1 as (
select a.*
from #temp a
where a.country in (select b.country
                    from #temp b
                    group by b.country
                    having min(b.ItemCount) = a.ItemCount)),
t2 as (select a.*
from #temp a
where a.country in (select b.country
                    from #temp b
                    group by b.country
                    having max(b.ItemCount) = a.ItemCount))
select t1.country, t1.id, t1.ItemCount, t1.DeliveryDate, t1.Itemtype
from t1
left join t2 on t1.country = t2.country
where t1.DeliveryDate < t2.DeliveryDate
and t1.Itemtype = 'Head Gears'
and t1.Itemtype = t2.Itemtype;

I believe this can be written better but I hope this helps...

Here is the fiddle you where you can see the code in action: clickhere


问:
Transmit Audio Via Micro:bit Radio In MicroBlocks
I am using a BBC Micro:bit version 2 and have a program set up on an editor called Micro:blocks. The code is supposed to take input from the first micro:bit's microphone and play it out of the other one's speaker. But when I try it, all I get is an annoying buzzing noise coming out the other end.
I can play it correctly out of the first micro:bit only (not using radio) and it sounds fine. I can't figure out why the second micro:bit makes a buzzing noise.

With the program without radio, I messed around with how long before it played the noise, and none of the tests resulted in a buzzing noise, so I know it's probably not a timing or delay issue.

Anyways, here is my code.

Transmitting code:

```<code>when [button a] pressed
  set radio group to (7)
  set radio channel to (7)
  set radio transmit power to (7)
  digital pin write (on) to (28)
  forever
     analog pin write (microphone + 500) to (0)
     radio transmit number (microphone + 500)

when [button b] pressed
   stop other processes
   radio transmit number (0)
   analog pin write (0) to (0)
</code>```

receiving code:

```<code>when program started
   forever
      if (new radio message)
         analog pin write (0) to (radio last received number)
</code>```

答:
This is an interesting project!

Your program looks correct but the radio system may not be fast enough to send each sound sample as a separate message. As a result, you are just hearing a series of clicks, resulting in the buzzing noise.

You could check that the sound data is being sent and received by sending a second or two of sound and graphing the incoming samples on the receiving side. It will be slow, but you should see something that looks like a smooth audio waveform.

Assuming speed is the issue, you could try sending several samples in each packet by encoding them into a string. But even that may not be fast enough to create a smooth audio stream, especially since the encode/decode process will take time.

A different approach would be for the receiver to collect a second or two of sound samples in a list, then play them back in a burst. That would not provide continuous audio but might allow transmitting a sentence at a time.

Here is a record/playback project you might use as a starting point for experimentation.

Note that you can download this image and drop the .png file into the MicroBlocks IDE. MicroBlocks will read the project back from the image itself :)

Body:
I am using a BBC Micro:bit version 2 and have a program set up on an editor called Micro:blocks. The code is supposed to take input from the first micro:bit's microphone and play it out of the other one's speaker. But when I try it, all I get is an annoying buzzing noise coming out the other end.
I can play it correctly out of the first micro:bit only (not using radio) and it sounds fine. I can't figure out why the second micro:bit makes a buzzing noise.

With the program without radio, I messed around with how long before it played the noise, and none of the tests resulted in a buzzing noise, so I know it's probably not a timing or delay issue.

Anyways, here is my code.

Transmitting code:

when [button a] pressed
  set radio group to (7)
  set radio channel to (7)
  set radio transmit power to (7)
  digital pin write (on) to (28)
  forever
     analog pin write (microphone + 500) to (0)
     radio transmit number (microphone + 500)

when [button b] pressed
   stop other processes
   radio transmit number (0)
   analog pin write (0) to (0)

receiving code:

when program started
   forever
      if (new radio message)
         analog pin write (0) to (radio last received number)


问:
Vue 3 The template root requires exactly one element. eslint-plugin-vue
After scaffolding a Vue 3 project I noticed an error in my App.vue.

```<code>A functional component that renders the matched component for the given path. Components rendered in can also contain its own , which will render components for nested paths.

API Reference

[vue/no-multiple-template-root]
The template root requires exactly one element.eslint-plugin-vue
</code>```

I tried putting

```<code>"vue/no-multiple-template-root": 0
</code>```

in my .eslintrc.js

But the error remains. How can I get rid of the error? Since in Vue 3 you don't have to have exactly one element in a template.

```<code>module.exports = {
    root: true,
    env: {
        node: true
    },
    extends: [
        "plugin:vue/vue3-essential",
        "eslint:recommended",
        "@vue/typescript/recommended",
        "@vue/prettier",
        "@vue/prettier/@typescript-eslint"
    ],
    parserOptions: {
        ecmaVersion: 2020
    },
    rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
        "vue/no-multiple-template-root": 0
    }
};
</code>```

答: I think, the best solution for that is to wrap all elements in the template into one div element. It works perfectly for me.</p>

Body:
After scaffolding a Vue 3 project I noticed an error in my App.vue.

A functional component that renders the matched component for the given path. Components rendered in can also contain its own , which will render components for nested paths.

API Reference

[vue/no-multiple-template-root]
The template root requires exactly one element.eslint-plugin-vue

I tried putting

"vue/no-multiple-template-root": 0

in my .eslintrc.js

But the error remains. How can I get rid of the error? Since in Vue 3 you don't have to have exactly one element in a template.

module.exports = {
    root: true,
    env: {
        node: true
    },
    extends: [
        "plugin:vue/vue3-essential",
        "eslint:recommended",
        "@vue/typescript/recommended",
        "@vue/prettier",
        "@vue/prettier/@typescript-eslint"
    ],
    parserOptions: {
        ecmaVersion: 2020
    },
    rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
        "vue/no-multiple-template-root": 0
    }
};


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
I think the "premature optimization is root of all evil" has to be understood literally - it does not say when is premature, and does not say you should optimize only at the end. Just not too early. Also, the "use the right algorithm, O(n^2) vs O(N)" is a bit dangerous if taken literally - because for many problems, the N is actually small, etc...

I think it depends a lot of the type of software you are doing: some software are such as every part is very independent, and can be optimized separately. But that's not always the case. For many (most ?) applications, speed just does not matter at all, the brute force but obviously correct way is the best one. But for projects where speed matters, it often has to be taken into account early - maybe that's another possible interpretation of Knuth's saying: many applications don't need to be optimized at all, just know which ones need and plan ahead.

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: David Cournapeau


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
An array is an IEnumerable<T>, using Covariance an IEnumerable<object>. That means any array is an IEnumerable<object>.

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
IEnumerable<object> collection = (IEnumerable<object>)obj;

foreach (object item in collection)
{
    Console.WriteLine(item.ToString());
}
</code>```

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`

Body:
An array is an IEnumerable<T>, using Covariance an IEnumerable<object>. That means any array is an IEnumerable<object>.

int[] array = new int[] { 0, 1, 2 };
object obj=array;
IEnumerable<object> collection = (IEnumerable<object>)obj;

foreach (object item in collection)
{
    Console.WriteLine(item.ToString());
}


问:
Lodash, method to return value from json array
I have to find inside a json array some value of a given key, and return the value of another key of the found object.

I have made this function:

```<code>const findValueByKey = ({
  jsonArray,
  keyToSearch,
  valueToSearch,
  keyOfTheValueToReturn,
  defaultMessage
}) => {
  const foundObject = jsonArray.find((obj) => obj[keyToSearch] === valueToSearch);
  if (foundObject) return foundObject[keyOfTheValueToReturn];
  return defaultMessage || 'not found';
};
</code>```

But my question is if there's something similar with Lodash, I don't want to reinventing the wheel.

I know that I can find an object given some criteria, like:

```<code>_.find(jsonArray, (object) => object[keyToSearch] === valueToSearch);
</code>```

But then I should extract the key that I need, etc.

答:
You can get the desired result using _.find along with _.get. _.find() will accept an object like { key: value } as the search criterion. Then we can use _.get() to return the desired property. If the key does not exist or the object cannot be found, we'll return defaultMessage.

The sample data comes from jsonplaceholder/users

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan@yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner@kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger@annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach@jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger@billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood@rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott@dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg@karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey (arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
    const obj = _.find(arr, { [keyToSearch]: valueToSearch });
    return _.get(obj, keyOfTheValueToReturn, defaultMessage);
}

console.log('Search by username:', findValueByKey(data, 'username', 'Samantha', 'name', 'Not found'))
console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))

console.log('Default result:', findValueByKey(data, 'keydoesntexist', 'valuedoesntexist', 'name', 'Not found'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

And just for completeness, a vanilla JavaScript solution, using Array.find() along with the in operator

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan@yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner@kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger@annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach@jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger@billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood@rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott@dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg@karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey(arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
    const obj = arr.find(el => (el || {}) [keyToSearch] === valueToSearch);
    return (keyOfTheValueToReturn in (obj || {})) ? obj[keyOfTheValueToReturn] : defaultMessage;
}

console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))```

Body:
I have to find inside a json array some value of a given key, and return the value of another key of the found object.

I have made this function:

const findValueByKey = ({
  jsonArray,
  keyToSearch,
  valueToSearch,
  keyOfTheValueToReturn,
  defaultMessage
}) => {
  const foundObject = jsonArray.find((obj) => obj[keyToSearch] === valueToSearch);
  if (foundObject) return foundObject[keyOfTheValueToReturn];
  return defaultMessage || 'not found';
};

But my question is if there's something similar with Lodash, I don't want to reinventing the wheel.

I know that I can find an object given some criteria, like:

_.find(jsonArray, (object) => object[keyToSearch] === valueToSearch);

But then I should extract the key that I need, etc.

Body:
You can get the desired result using _.find along with _.get. _.find() will accept an object like { key: value } as the search criterion. Then we can use _.get() to return the desired property. If the key does not exist or the object cannot be found, we'll return defaultMessage.

The sample data comes from jsonplaceholder/users

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan@yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner@kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger@annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach@jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger@billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood@rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott@dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg@karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey (arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
    const obj = _.find(arr, { [keyToSearch]: valueToSearch });
    return _.get(obj, keyOfTheValueToReturn, defaultMessage);
}

console.log('Search by username:', findValueByKey(data, 'username', 'Samantha', 'name', 'Not found'))
console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))

console.log('Default result:', findValueByKey(data, 'keydoesntexist', 'valuedoesntexist', 'name', 'Not found'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

And just for completeness, a vanilla JavaScript solution, using Array.find() along with the in operator

let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan@yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner@kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger@annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach@jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger@billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood@rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott@dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg@karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];

function findValueByKey(arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
    const obj = arr.find(el => (el || {}) [keyToSearch] === valueToSearch);
    return (keyOfTheValueToReturn in (obj || {})) ? obj[keyOfTheValueToReturn] : defaultMessage;
}

console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))


问:
Format the text after 4 characters (ABCD-EFGH-IJKL) but allow editing
I am trying to format and allow edit formated string in input with jquery, but I cannot achieve editing formated string correctly. Actually when user make mistake when typing code into input and want to correct it, it jump user to the end of the chain, because it forced formate it when user delete a char. How can i edit it, to let user correct his mistake but still format the chain?

What user type: 8F489T4R8T5O7S8E

What user see:  8F48-9T4R-8T5O-7S8E

But when user want to correct O to 0, it make result like this 8F48-9T4R-8T57-S8E0, because it will forced reformat the string immediately and put the 0 to the end of the chain.

    $("input[name=login-access-token]").keyup(function(event){
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input type="text" name="login-access-token" placeholder="Code" /></code>```

答:
Added new if condition.</p>
```<code>    $("input[name=login-access-token]").keyup(function(event){
     if (event.keyCode != 8 && event.keyCode != 46) { //New conditions added
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });
        }
    });
</code>```

Body:
I am trying to format and allow edit formated string in input with jquery, but I cannot achieve editing formated string correctly. Actually when user make mistake when typing code into input and want to correct it, it jump user to the end of the chain, because it forced formate it when user delete a char. How can i edit it, to let user correct his mistake but still format the chain?

What user type: 8F489T4R8T5O7S8E

What user see:  8F48-9T4R-8T5O-7S8E

But when user want to correct O to 0, it make result like this 8F48-9T4R-8T57-S8E0, because it will forced reformat the string immediately and put the 0 to the end of the chain.

    $("input[name=login-access-token]").keyup(function(event){
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });

    });

<input type="text" name="login-access-token" placeholder="Code" />

Body:
Added new if condition.

    $("input[name=login-access-token]").keyup(function(event){
     if (event.keyCode != 8 && event.keyCode != 46) { //New conditions added
        var input = $(this).val();
        input = input.replace(/[\W\s\._\-]+/g, '');
        var split = 4;
        var chunk = [];

        for (var i = 0, len = input.length; i < len; i += split) {
            split = 4;
            chunk.push( input.substr( i, split ) );
        }
        $(this).val(function() {
            var out = chunk.join("-").toUpperCase();

            if(out.length == 4 && event.keyCode != 8){
                    out += "-";
            }

            if(out.length == 9 && event.keyCode != 8 ){
                    out += "-";
            }

            return out;
        });
        }
    });


问:
The problem occurs after the flutter sdk is updated. How can I fix it?
```<code>Launching lib/main.dart on Android SDK built for arm64 in debug mode...
e: /Users/madol.eeee/.gradle/caches/transforms-3/0fbf638dbdf70ad1725fe71b315a2ef4/transformed/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2066b23b9b64ad3895a698a6d1fc8c5f/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2a1bbf32034612557ecc12fcd06b65de/transformed/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/38348b600f1be8b91fdb7c7730bf1eb5/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/5a29260d2a646236c4d0b2d60a4d47d8/transformed/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/74bfffd4e61971b016e3f927bbbd7521/transformed/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/7cde7f72a0842ac95e9281eb78688076/transformed/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/e84741d2b04d8859553c8e0a19bf4026/transformed/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* 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 8s
┌─ Flutter Fix ────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                       │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then │
│ update /Users/madol.eeee/project/traveling/flutter_traveling/android/build.gradle:           │
│ ext.kotlin_version = '<latest-version>'                                                      │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

i updated flutter sdk version 2.8.1 to 2.10.1 and get error after updated

i don't know why this hapening,  how can i fix that?

sorry and thank you

答:
You have to also update your kotlin version,
go in file android/build.gradle and change ext.kotlin_version line (should be the second line) to something like this  ext.kotlin_version = '1.4.32'

You might also to update your ide (android studios or vscode) and the plugins

Body:
Launching lib/main.dart on Android SDK built for arm64 in debug mode...
e: /Users/madol.eeee/.gradle/caches/transforms-3/0fbf638dbdf70ad1725fe71b315a2ef4/transformed/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2066b23b9b64ad3895a698a6d1fc8c5f/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/2a1bbf32034612557ecc12fcd06b65de/transformed/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/38348b600f1be8b91fdb7c7730bf1eb5/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/5a29260d2a646236c4d0b2d60a4d47d8/transformed/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/74bfffd4e61971b016e3f927bbbd7521/transformed/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/7cde7f72a0842ac95e9281eb78688076/transformed/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: /Users/madol.eeee/.gradle/caches/transforms-3/e84741d2b04d8859553c8e0a19bf4026/transformed/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* 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 8s
┌─ Flutter Fix ────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                       │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then │
│ update /Users/madol.eeee/project/traveling/flutter_traveling/android/build.gradle:           │
│ ext.kotlin_version = '<latest-version>'                                                      │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

i updated flutter sdk version 2.8.1 to 2.10.1 and get error after updated

i don't know why this hapening,  how can i fix that?

sorry and thank you


问:
Access [[scope]] of the function from api response
```<code>drop: (item, monitor) => addTaskToSprint(item.id, monitor, drop)
    length: 2
    name: "drop"
    arguments: (...)
    caller: (...)
    [[FunctionLocation]]: SprintCard.jsx:45
    [[Prototype]]: ƒ ()
    [[Scopes]]: Scopes[3]
        0: Closure (SprintCard)
           ItemType: "Task Card"
           addTaskToSprint: (id, monitor, dropTargetProps, task) => {…}
           drop: ƒ ()
</code>```

My api response looks like this,

I need to access [[Scopes]] so I can get the ItemType variable

drop is a function so accessing the scope like so (spec.drop.scopes) won't work

when I console.log(spec.drop) it shows the function declaration only

So is there any way to have access scopes?

答:
[[Scopes]] isn't a part of the object, it's a category devtools uses to show what environment record objects a function closes over. The drop function has access to ItemType, but other code doesn't get access to ItemType via drop unless drop provides that access in some way. More generally, code with access to a function doesn't necessarily have access to the things that function has access to (in fact, it often doesn't).

Here's a simpler example:

function counter() {
    let value = 0;
    const increment = () => ++value;
    return increment;
}

function example() {
    const increment = counter();
    console.log(increment()); // Shows "1"
    console.log(increment()); // Shows "2" -- that is, the `increment`
                              // function closes over `value` so it
                              // can use it to return an incrementing
                              // counter

    // There's no way for code here to directly access the `value` that
    // `increment` closes over.
}

example();```

The increment function has access to value, but the example function does not, even though it has access to increment.

Body:
drop: (item, monitor) => addTaskToSprint(item.id, monitor, drop)
    length: 2
    name: "drop"
    arguments: (...)
    caller: (...)
    [[FunctionLocation]]: SprintCard.jsx:45
    [[Prototype]]: ƒ ()
    [[Scopes]]: Scopes[3]
        0: Closure (SprintCard)
           ItemType: "Task Card"
           addTaskToSprint: (id, monitor, dropTargetProps, task) => {…}
           drop: ƒ ()

My api response looks like this,

I need to access [[Scopes]] so I can get the ItemType variable

drop is a function so accessing the scope like so (spec.drop.scopes) won't work

when I console.log(spec.drop) it shows the function declaration only

So is there any way to have access scopes?

Body:
[[Scopes]] isn't a part of the object, it's a category devtools uses to show what environment record objects a function closes over. The drop function has access to ItemType, but other code doesn't get access to ItemType via drop unless drop provides that access in some way. More generally, code with access to a function doesn't necessarily have access to the things that function has access to (in fact, it often doesn't).

Here's a simpler example:

function counter() {
    let value = 0;
    const increment = () => ++value;
    return increment;
}

function example() {
    const increment = counter();
    console.log(increment()); // Shows "1"
    console.log(increment()); // Shows "2" -- that is, the `increment`
                              // function closes over `value` so it
                              // can use it to return an incrementing
                              // counter

    // There's no way for code here to directly access the `value` that
    // `increment` closes over.
}

example();

The increment function has access to value, but the example function does not, even though it has access to increment.


问:
Extract multi value points using CDO into a single text file
I have come across the code

cdo -outputtab, date,value -remapnn,lon=X/lat=Y infile.nc > Outfile.txt

which very nicely extracts for a single point only. Is there any way I can extract time series data from netcdf file for multiple points using a single command line or by using some script and get the output in a single text file? Something like this -

lat-lon1, lat-lon2, lat-lon3

235, 256, 254

264, 246, 249

289, 278, 259

......

答:
I'm not sure why you tagged a cdo command equiry with python, are you looking for a bash command script solution or a python code?

If you want a simple bash script then you can do this using a loop over lat lon pairs to produce a set of text files and then combine then column-wise using this solution here.

Note 1: I drop the "date" otherwise you will have the date repeated for each entry - if you must have the date then pull out the first cdo remap command from the loop and do that one including "date".

Note 2: This will be space separated and not comma separated - I'm assuming that is not an issue

```<code># these are LON/LAT pairs:
for i in "10 3" "2 5" "3 7"; do
   a=( $i )
   lon=${a[0]}
   lat=${a[1]}
   cdo -outputtab,value -remapnn,lon=${lon}/lat=${lat} infile.nc > pt_lon${lon}_lat${lat}.txt
   # change column title from "value" to "lon-lat vals"
   sed -i -e "s/value/${lon}-${lat}/" pt_lon${lon}_lat${lat}.txt
done
# now combine the columns - set the e24 to the width that is appropriate
paste pt_*.txt  | pr -t -e24 > output.txt
</code>```

Body:
I'm not sure why you tagged a cdo command equiry with python, are you looking for a bash command script solution or a python code?

If you want a simple bash script then you can do this using a loop over lat lon pairs to produce a set of text files and then combine then column-wise using this solution here.

Note 1: I drop the "date" otherwise you will have the date repeated for each entry - if you must have the date then pull out the first cdo remap command from the loop and do that one including "date".

Note 2: This will be space separated and not comma separated - I'm assuming that is not an issue

# these are LON/LAT pairs:
for i in "10 3" "2 5" "3 7"; do
   a=( $i )
   lon=${a[0]}
   lat=${a[1]}
   cdo -outputtab,value -remapnn,lon=${lon}/lat=${lat} infile.nc > pt_lon${lon}_lat${lat}.txt
   # change column title from "value" to "lon-lat vals"
   sed -i -e "s/value/${lon}-${lat}/" pt_lon${lon}_lat${lat}.txt
done
# now combine the columns - set the e24 to the width that is appropriate
paste pt_*.txt  | pr -t -e24 > output.txt


问:
python method as argument
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

```<code>class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)
</code>```

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?

答: a.my_method returns not exactly the function you defined in the class A (you can get it via A.my_method) but an object called a 'bound method' which contains both the original function (or 'unbound method' in Python 2, IIRC) and the object from which it was retrieved (the self argument).

Title: python method as argument

Body:
So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out the following example:

class A:

    def __init__(self):
        self.value = 'a'

    def my_method(self)
        print self.value

class B:

   def __init__(self):
       self.values = 'b'

   def my_method(self, method):
       method()

a = A()
b = B()
b.my_method(a.my_method)

Now first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?


问:
How do we host multiple HTML files in a single S3 bucket to get separate URLs for each file?
I'm new to using AWS S3. I need to host my privacy policy HTML page and T&C HTML page in the S3 bucket as static web pages. I need separate URLs for those two files but I can not create separate S3 buckets for each file. So is there any way to full fill my requirement?

I need this kind of URLs after hosting the pages in the S3 bucket

```<code>http://<bucket-name>.s3-website-<AWS-region>.amazonaws.com/privacypolicy.html
http://<bucket-name>.s3-website-<AWS-region>.amazonaws.com/termsandcondition.html
</code>```

also, I can not create an index file for these HTML pages and after that link these HTML pages to that index file, because I need these URLs to link my mobile app. once the user clicks one of the links, the user should go to that page so that's why I need separate URL for these files.

答:
You dont have to create separate bucket

Just create 2 HTML files for example site1.html and site2.html.
Here are the steps to follow

upload site1.html and site2.html

enable website hosting and enter site1.html instead of index.html

turn off block public access setting

add bucket policy to access bucket publicly https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html

access website using website hosting URL link, this will lead to site1.html, if you want to access site2.html just append site2.html to root address

for example
here is my link for site1.html
http://stack-trial.s3-website.ap-south-1.amazonaws.com/

Note: you can also access the site1.html using this http://stack-trial.s3-website.ap-south-1.amazonaws.com/site1.html.

for site2.html
http://stack-trial.s3-website.ap-south-1.amazonaws.com/site2.html

Body:
I'm new to using AWS S3. I need to host my privacy policy HTML page and T&C HTML page in the S3 bucket as static web pages. I need separate URLs for those two files but I can not create separate S3 buckets for each file. So is there any way to full fill my requirement?

I need this kind of URLs after hosting the pages in the S3 bucket

http://<bucket-name>.s3-website-<AWS-region>.amazonaws.com/privacypolicy.html
http://<bucket-name>.s3-website-<AWS-region>.amazonaws.com/termsandcondition.html

also, I can not create an index file for these HTML pages and after that link these HTML pages to that index file, because I need these URLs to link my mobile app. once the user clicks one of the links, the user should go to that page so that's why I need separate URL for these files.


问:
Varying the number of neurons per hidden layer for dynamically created layers using GridSearchCV
I'm trying to update the number of neurons in each hidden layer for dynamically created layers. For example, the output as seen in the model.summary() shows each of the layers having either 5 or 10 Neurons, but not a 5 then 10 or 10 then 5 which is what I'd like.</p>
```<code>import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataset = 'https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv'
df_diabetes = pd.read_csv(dataset, names = names)
df_diabetes.head()
df_diabetes = df_diabetes[1:]
X = df_diabetes[['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age']]
y = df_diabetes['class']
### Normalize the input features so that they are on the same scale. This is so that the errors calculated for back-propagation are calculated from a similar scale of features. This would mean smaller initial errors compared to that from non-normalised feature data. Smaller scale of errors leads to faster convergence of the gradient descent when adjusting the weights using the chosen cost function.
scaler = MinMaxScaler(feature_range=[0, 1])
X_rescaled = scaler.fit_transform(X)
X = pd.DataFrame(data = X_rescaled, columns = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age'])
X.head(3)

X= X.to_numpy()
y = y.to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.75, random_state = 1, stratify =y, shuffle = True)

def createmodel(n_layers, neurons, activation_func, optimizer, loss_func):
    model = Sequential()

    for i in range(1, n_layers):
        if i == 1:
            model.add(Dense(neurons, input_dim=X_train.shape[1], activation=activation_func))
        else:
            model.add(Dense(neurons, activation=activation_func))

    # Finally, the output layer should have a single node in binary classification
    model.summary()
    model.add(Dense(1, activation=activation_func))
    model.compile(optimizer=optimizer, loss=loss_func, metrics=["accuracy"])  # note: metrics could also be 'mse'

    return model

##Wrap model into scikit-learn
model = KerasClassifier(build_fn=createmodel, verbose=False)

# activation_funcs = ['sigmoid', 'relu', 'tanh']
activation_funcs = ['relu']
# loss_funcs = ['binary_crossentropy','hinge']
loss_funcs = ['binary_crossentropy']
# optimizers = ['rmsprop', 'adam','sgd']
optimizers = ['adam']
param_grid = dict(n_layers=[2,3], neurons=[5,10],  activation_func = activation_funcs,
                  optimizer=optimizers, loss_func = loss_funcs, batch_size = [100], epochs = [20])
grid = GridSearchCV(estimator = model, param_grid = param_grid, verbose=2)
grid.fit(X,y)

print(grid.best_score_)
print(grid.best_params_)

pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']].to_csv('GridOptimization.csv')
</code>```

答:
You could try defining n_layers as a list of lists:

n_layers = [[5, 10], [10, 5], [5, 10, 10],[5, 5, 10]]
```
<p>where the length of each list represents the number of layers and their elements are the nodes for the layers. Here is a working example (just copy and paste it):</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataset = 'https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv'
df_diabetes = pd.read_csv(dataset, names = names)
df_diabetes.head()
df_diabetes = df_diabetes[1:]
X = df_diabetes[['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age']]
y = df_diabetes['class']
### Normalize the input features so that they are on the same scale. This is so that the errors calculated for back-propagation are calculated from a similar scale of features. This would mean smaller initial errors compared to that from non-normalised feature data. Smaller scale of errors leads to faster convergence of the gradient descent when adjusting the weights using the chosen cost function.
scaler = MinMaxScaler(feature_range=[0, 1])
X_rescaled = scaler.fit_transform(X)
X = pd.DataFrame(data = X_rescaled, columns = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age'])
X.head(3)

X= X.to_numpy()
y = y.to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.75, random_state = 1, stratify =y, shuffle = True)

def createmodel(n_layers, activation_func, optimizer, loss_func):
    model = Sequential()

    for i, neurons in enumerate(n_layers):
      if i == 0:
        model.add(Dense(neurons, input_dim=X_train.shape[1], activation=activation_func))
      else: model.add(Dense(neurons, activation=activation_func))

    # Finally, the output layer should have a single node in binary classification
    model.summary()
    model.add(Dense(1, activation=activation_func))
    model.compile(optimizer=optimizer, loss=loss_func, metrics=["accuracy"])  # note: metrics could also be 'mse'

    return model

model = KerasClassifier(build_fn=createmodel, verbose=False)

activation_funcs = ['relu']
loss_funcs = ['binary_crossentropy']
optimizers = ['adam']

n_layers = [[5, 10], [10, 5], [5, 10, 10],[5, 5, 10]] # The length of each list represents the number of layers and their elements are the nodes for the layers.
param_grid = dict(n_layers = n_layers,  activation_func = activation_funcs,
                  optimizer=optimizers, loss_func = loss_funcs, batch_size = [100], epochs = [20])
grid = GridSearchCV(estimator = model, param_grid = param_grid, verbose=2)
grid.fit(X,y)

print(grid.best_score_)
print(grid.best_params_)

pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']].to_csv('GridOptimization.csv')
</code>```

Body:
I'm trying to update the number of neurons in each hidden layer for dynamically created layers. For example, the output as seen in the model.summary() shows each of the layers having either 5 or 10 Neurons, but not a 5 then 10 or 10 then 5 which is what I'd like.

import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataset = 'https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv'
df_diabetes = pd.read_csv(dataset, names = names)
df_diabetes.head()
df_diabetes = df_diabetes[1:]
X = df_diabetes[['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age']]
y = df_diabetes['class']
### Normalize the input features so that they are on the same scale. This is so that the errors calculated for back-propagation are calculated from a similar scale of features. This would mean smaller initial errors compared to that from non-normalised feature data. Smaller scale of errors leads to faster convergence of the gradient descent when adjusting the weights using the chosen cost function.
scaler = MinMaxScaler(feature_range=[0, 1])
X_rescaled = scaler.fit_transform(X)
X = pd.DataFrame(data = X_rescaled, columns = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age'])
X.head(3)

X= X.to_numpy()
y = y.to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.75, random_state = 1, stratify =y, shuffle = True)

def createmodel(n_layers, neurons, activation_func, optimizer, loss_func):
    model = Sequential()

    for i in range(1, n_layers):
        if i == 1:
            model.add(Dense(neurons, input_dim=X_train.shape[1], activation=activation_func))
        else:
            model.add(Dense(neurons, activation=activation_func))

    # Finally, the output layer should have a single node in binary classification
    model.summary()
    model.add(Dense(1, activation=activation_func))
    model.compile(optimizer=optimizer, loss=loss_func, metrics=["accuracy"])  # note: metrics could also be 'mse'

    return model

##Wrap model into scikit-learn
model = KerasClassifier(build_fn=createmodel, verbose=False)

# activation_funcs = ['sigmoid', 'relu', 'tanh']
activation_funcs = ['relu']
# loss_funcs = ['binary_crossentropy','hinge']
loss_funcs = ['binary_crossentropy']
# optimizers = ['rmsprop', 'adam','sgd']
optimizers = ['adam']
param_grid = dict(n_layers=[2,3], neurons=[5,10],  activation_func = activation_funcs,
                  optimizer=optimizers, loss_func = loss_funcs, batch_size = [100], epochs = [20])
grid = GridSearchCV(estimator = model, param_grid = param_grid, verbose=2)
grid.fit(X,y)

print(grid.best_score_)
print(grid.best_params_)

pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']].to_csv('GridOptimization.csv')

Body:
You could try defining n_layers as a list of lists:

n_layers = [[5, 10], [10, 5], [5, 10, 10],[5, 5, 10]]

where the length of each list represents the number of layers and their elements are the nodes for the layers. Here is a working example (just copy and paste it):

import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataset = 'https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv'
df_diabetes = pd.read_csv(dataset, names = names)
df_diabetes.head()
df_diabetes = df_diabetes[1:]
X = df_diabetes[['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age']]
y = df_diabetes['class']
### Normalize the input features so that they are on the same scale. This is so that the errors calculated for back-propagation are calculated from a similar scale of features. This would mean smaller initial errors compared to that from non-normalised feature data. Smaller scale of errors leads to faster convergence of the gradient descent when adjusting the weights using the chosen cost function.
scaler = MinMaxScaler(feature_range=[0, 1])
X_rescaled = scaler.fit_transform(X)
X = pd.DataFrame(data = X_rescaled, columns = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age'])
X.head(3)

X= X.to_numpy()
y = y.to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.75, random_state = 1, stratify =y, shuffle = True)

def createmodel(n_layers, activation_func, optimizer, loss_func):
    model = Sequential()

    for i, neurons in enumerate(n_layers):
      if i == 0:
        model.add(Dense(neurons, input_dim=X_train.shape[1], activation=activation_func))
      else: model.add(Dense(neurons, activation=activation_func))

    # Finally, the output layer should have a single node in binary classification
    model.summary()
    model.add(Dense(1, activation=activation_func))
    model.compile(optimizer=optimizer, loss=loss_func, metrics=["accuracy"])  # note: metrics could also be 'mse'

    return model

model = KerasClassifier(build_fn=createmodel, verbose=False)

activation_funcs = ['relu']
loss_funcs = ['binary_crossentropy']
optimizers = ['adam']

n_layers = [[5, 10], [10, 5], [5, 10, 10],[5, 5, 10]] # The length of each list represents the number of layers and their elements are the nodes for the layers.
param_grid = dict(n_layers = n_layers,  activation_func = activation_funcs,
                  optimizer=optimizers, loss_func = loss_funcs, batch_size = [100], epochs = [20])
grid = GridSearchCV(estimator = model, param_grid = param_grid, verbose=2)
grid.fit(X,y)

print(grid.best_score_)
print(grid.best_params_)

pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']].to_csv('GridOptimization.csv')


问:
Javascript: HackerRank function within a function is not a function
This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

```<code>function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}
</code>```

So my first train of thought was to write the following inside myList():

```<code>let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};
</code>```

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?

答: For obj, inside myList() you could have run a closure, that is a self invoking function returning, in this case, an object with your k:v exports, but with private access to the context of the now expired anonymous caller. With "const add = function" etc statements you can define values for your exports, while the objList goes in the private context.

Body:
This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}

So my first train of thought was to write the following inside myList():

let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?


问:
How do I run an async background task during async pytest?
I want to test interactions between a server MyServer and client MyClient using pytest. The server is async, and has an async start() method. Here is my setup:

import pytest
from .server import MyServer
from .client import MyClient

PORT = 8765
HOST = "127.0.0.1"

async def run_server():
    await MyServer().start(host=HOST, port=PORT)

@pytest.fixture
def client():
    return MyClient(host=HOST, port=PORT)

@pytest.mark.asyncio
async def test_can_get_response(client):
    response = await client.call_server()
    assert response is not None
```
<p>I need the server to be booted up and run in the background when the tests run. There is a very simple solution here: before running pytest, just run a python file that calls <code>run_server()</code>, but it would be neater if I could boot up the server in this test file, so the server gets destroyed at the end.</p>
<p>My first instinct is to use threading:</p>
<pre class="lang-py prettyprint-override"><code>from threading import Thread

Thread(target=run_server).start()
</code>```

However, the tests get run before the thread has time to start:

```<code>Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<run_server() running at /path/to/file> wait_for=<_GatheringFuture pending cb=[<TaskWakeupMethWrapper object at 0x105fc90a0>()]>>
Task was destroyed but it is pending!
</code>```

Adding a time.sleep() so the server has time to boot doesn't make a difference, the tests run immediately.

I believe another alternative is to use a fixture, i.e. booting up the server for the course of each test. I attempted the following:

@pytest.fixture
async def run_server():
    await MyServer().start(host=HOST, port=PORT)

@pytest.fixture
def client():
    return MyClient(host=HOST, port=PORT)

@pytest.mark.asyncio
async def test_can_get_response(client, run_server):
    await run_server # Not run_server() because the fixture is already a coroutine
    response = await client.call_server()
    assert response is not None
```

This boots up the server as expected, but not in the background: MyServer().start() runs forever and blocks the tests from running.

How can I start my server in the background and run it over the course of the tests?

答:
Use Process instead of Thread. Here's an example (not full code, just to illustrate):

import pytest
from multiprocessing import Process

@pytest.mark.asyncio
async def test_http_file_upload():
    httpd = http_server.build_server(host, port)
    Process(target=httpd.serve_forever, args=(), daemon=True).start()
    await transfer_file(file, f"http://{host}:{port}{remote_path}")
    ...
```

Process will also terminate itself at the end of test.

Body:
I want to test interactions between a server MyServer and client MyClient using pytest. The server is async, and has an async start() method. Here is my setup:

import pytest
from .server import MyServer
from .client import MyClient

PORT = 8765
HOST = "127.0.0.1"

async def run_server():
    await MyServer().start(host=HOST, port=PORT)

@pytest.fixture
def client():
    return MyClient(host=HOST, port=PORT)

@pytest.mark.asyncio
async def test_can_get_response(client):
    response = await client.call_server()
    assert response is not None

I need the server to be booted up and run in the background when the tests run. There is a very simple solution here: before running pytest, just run a python file that calls run_server(), but it would be neater if I could boot up the server in this test file, so the server gets destroyed at the end.

My first instinct is to use threading:

from threading import Thread

Thread(target=run_server).start()

However, the tests get run before the thread has time to start:

Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<run_server() running at /path/to/file> wait_for=<_GatheringFuture pending cb=[<TaskWakeupMethWrapper object at 0x105fc90a0>()]>>
Task was destroyed but it is pending!

Adding a time.sleep() so the server has time to boot doesn't make a difference, the tests run immediately.

I believe another alternative is to use a fixture, i.e. booting up the server for the course of each test. I attempted the following:

@pytest.fixture
async def run_server():
    await MyServer().start(host=HOST, port=PORT)

@pytest.fixture
def client():
    return MyClient(host=HOST, port=PORT)

@pytest.mark.asyncio
async def test_can_get_response(client, run_server):
    await run_server # Not run_server() because the fixture is already a coroutine
    response = await client.call_server()
    assert response is not None

This boots up the server as expected, but not in the background: MyServer().start() runs forever and blocks the tests from running.

How can I start my server in the background and run it over the course of the tests?

Body:
Use Process instead of Thread. Here's an example (not full code, just to illustrate):

import pytest
from multiprocessing import Process

@pytest.mark.asyncio
async def test_http_file_upload():
    httpd = http_server.build_server(host, port)
    Process(target=httpd.serve_forever, args=(), daemon=True).start()
    await transfer_file(file, f"http://{host}:{port}{remote_path}")
    ...

Process will also terminate itself at the end of test.


问:
What is hint in the openGauss?
It seems that there are so many hints used in the openGauss, any one know the basic design idea of the hint in openGauss?</p>

答:
In order to get a better performance for a certain query, using hints is a method to adjust the query plan while the optimizer not choose a correct plan for one query.
For example, you can change the join order, or change the join return row number for a certain query to improve performance.
you can learn hints on this page
https://opengauss.org/en/docs/2.1.0/docs/Developerguide/hint-based-tuning.html</p>

Title: What is hint in the openGauss?


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
What about using source control like Mercurial? I don't know, maybe it isn't exactly what you want, but this is a tool that is designed to track changes between revisions. You can create a repository, commit the first file, then overwrite it with another one an commit the second one:

```<code>hg init some_repo
cd some_repo
cp ~/huge_file1.txt .
hg ci -Am "Committing first huge file."
cp ~/huge_file2.txt huge_file1.txt
hg ci -m "Committing second huge file."
</code>```

From here you can get a diff, telling you what lines differ. If you could somehow use that diff to determine what lines were the same, you would be all set.

That's just an idea, someone correct me if I'm wrong.

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

Body:
What about using source control like Mercurial? I don't know, maybe it isn't exactly what you want, but this is a tool that is designed to track changes between revisions. You can create a repository, commit the first file, then overwrite it with another one an commit the second one:

hg init some_repo
cd some_repo
cp ~/huge_file1.txt .
hg ci -Am "Committing first huge file."
cp ~/huge_file2.txt huge_file1.txt
hg ci -m "Committing second huge file."

From here you can get a diff, telling you what lines differ. If you could somehow use that diff to determine what lines were the same, you would be all set.

That's just an idea, someone correct me if I'm wrong.


问:
Threejs Raycast Intersects empty with scene.children. What am I doing wrong?
Post 1) I am trying to detect all objects viewable by the camera so I can reposition them to the starting position once they are out of view. I am aiming for an infinite waterfall effect that reuses the existing objects. I really don't why intersects is empty and it works if I raycast for individual objects while looping through scene.children but this will lead to very bad performance because it is in the animation loop.

Thanks for any help

Post 2) I have changed over to frustrum culling but frustum.containsPoint(scene.children[index]) always returns true even when objects are clearly out of camera view.

Again any help is appreciated

camera.updateMatrix();
  camera.updateMatrixWorld();

  var frustum = new THREE.Frustum();
  var projScreenMatrix = new THREE.Matrix4();
  projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);

  // frustum.setFromProjectionMatrix(camera.projectionMatrix);
  frustum.setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));

  for (let index = 0; index < scene.children.length; index++) {
    scene.children[index].updateMatrix(); // make sure plane's local matrix is updated
    scene.children[index].updateMatrixWorld();

    if (frustum.containsPoint(scene.children[index])) {
      //stuff happens...
      if (scene.children[index].name === "coin") {
        scene.children[index].rotation.x += 0.01;
        scene.children[index].position.y -= 0.1;
      }
      // console.log("mesh in view Frustrum");
    } else {
      console.log("mesh not in view Frustrum");
    }
  }```

答:
I am trying to detect all objects viewable by the camera

You don't need raycasting for this. Instead, setup an instance of Frustum based on the projection and view matrix of your camera via setFromProjectionMatrix(). In the next step, use intersectsObject() to detect whether a 3D object is inside the camera's view frustum (the viewable area of the 3D scene) or not.