问:
Flutter-desktop Frameless window support
just started with flutter and I am playing with macos desktop app. I wonder if flutter has support for frameless window.
For example in Electron.js we can define frameless window and our app window can have really custom shape. We can recreate our title bar according app needs and so on.

Example of frameless electron app:

I was trying to find any info about this feature but I was not success.

Is this feature planned, or can we do this now for example on macOS using Xcode?
I know that desktop support is in early stage so maybe it is very soon to ask.

答: You can use package bitsdojo_window</p>

Body: You can use package bitsdojo_window


来源: stackexchange

问:
Why does excel SUMIF function give wrong figure?

Taking sum of HP. But my formula is providing me wrong amount despite of criteria not being fulfilled!

答:
I think it's worth posting an explanation as to why your original formula does not work, as it highlights an interesting feature of the function SUMIF.

As stated in one of my commments, you are passing a range parameter to that function of CN_2021[[#All],[HP]:[Sum of ORDER_AMT]], which is a reference to the entire table (including headers). Hence, you are effectively searching for the entry from P14 in all three columns, not just the first.

However, you are also using a sum_range parameter of CN_2021[[#All],[Sum of ORDER_QTY]], which is only one column. One might think that the construction should flat out error, since your range and sum_range parameters are not of an equal dimension (the former comprises 3 columns, the latter only 1).

The reason it does not error is due to the fact that, in such cases, Excel redimensions the sum_range so as to be of an equal dimension to the range.

So, if we replace the Table references with their equivalent worksheet references (assuming that table begins in A3) for the sake of simplification, we have that

=SUMIF(CN_2021[[#All],[HP]:[Sum of ORDER_AMT]],P14,CN_2021[[#All],[Sum of ORDER_QTY]])

which is equivalent to

=SUMIF(A3:C19,P14,B3:B19)

should error, though the single-column range

B3:B19

is redimensioned to a three-column range in line with the range, i.e.

B3:D19

which means that you are effectively performing

=SUMIF(A3:C19,P14,B3:D19)

This could have potential consequences were column D also populated: for example, place a 3 in cell C14 and 1000 in cell D14. The formula will now pick up this extra 1000 in the sum.

Strangely, unlike SUMIF, SUMIFS does not appear to be so lenient with respect to this redimensioning:

=SUMIFS(B3:B19,A3:C19,P14)

errors.

ContentLicense: CC BY-SA 4.0


问:
cppcheck: error: unrecognized command line option: "--file-filter
I am developing C code on Ubuntu 20.04.

By running cppcheck -q --project=build/proj1/compile_commands.json --file-filter='src/base/Myfile.c'

I got the error

```<code>cppcheck: error: unrecognized command line option: "--file-filter=src/base/Myfile.c".
</code>```

答:
It looks like the version of cppcheck included in Ubuntu 20.04 is not the latest:

```<code>$ apt show cppcheck | grep Version
Version: 1.90-4build1
</code>```

cppcheck 1.90 was released in 2019. The --file-filter argument was introduced in commit fcd5cda97 in 2020:

```<code>$ git show fcd5cda97f10085c7def7fda6fc6199f624010ce
commit fcd5cda97f10085c7def7fda6fc6199f624010ce
Author: fuzzelhjb <chschmidt9@gmail.com>
Date:   Fri Jan 10 08:57:37 2020 +0100

    Check selected files from project (#2378)

diff --git a/cli/cmdlineparser.cpp b/cli/cmdlineparser.cpp
index 3fbc7f6c6..292327051 100644
--- a/cli/cmdlineparser.cpp
+++ b/cli/cmdlineparser.cpp
@@ -376,6 +376,10 @@ bool CmdLineParser::parseFromArgs(int argc, const char* const argv[])
                 mSettings->xml = true;
             }

+            // use a file filter
+            else if (std::strncmp(argv[i], "--file-filter=", 14) == 0)
+                mSettings->fileFilter = std::string(argv[i] + 14);
+
             // Only print something when there are errors
             else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0)
                 mSettings->quiet = true;
@@ -1035,6 +1039,9 @@ void CmdLineParser::printHelp()
               "    --exitcode-suppressions=<file>\n"
               "                         Used when certain messages should be displayed but\n"
               "                         should not cause a non-zero exitcode.\n"
+              "    --file-filter=<str>  Analyze only those files matching the given filter str\n"
+              "                         Example: --file-filter=*bar.cpp analyzes only files\n"
+              "                                  that end with bar.cpp.\n"
               "    --file-list=<file>   Specify the files to check in a text file. Add one\n"
               "                         filename per line. When file is '-,' the file list will\n"
               "                         be read from standard input.\n"
</code>```

The current release version of cppcheck appears to be 2.7.

Body:
I am developing C code on Ubuntu 20.04.

By running cppcheck -q --project=build/proj1/compile_commands.json --file-filter='src/base/Myfile.c'

I got the error

cppcheck: error: unrecognized command line option: "--file-filter=src/base/Myfile.c".

Body:
It looks like the version of cppcheck included in Ubuntu 20.04 is not the latest:

$ apt show cppcheck | grep Version
Version: 1.90-4build1

cppcheck 1.90 was released in 2019. The --file-filter argument was introduced in commit fcd5cda97 in 2020:

$ git show fcd5cda97f10085c7def7fda6fc6199f624010ce
commit fcd5cda97f10085c7def7fda6fc6199f624010ce
Author: fuzzelhjb <chschmidt9@gmail.com>
Date:   Fri Jan 10 08:57:37 2020 +0100

    Check selected files from project (#2378)

diff --git a/cli/cmdlineparser.cpp b/cli/cmdlineparser.cpp
index 3fbc7f6c6..292327051 100644
--- a/cli/cmdlineparser.cpp
+++ b/cli/cmdlineparser.cpp
@@ -376,6 +376,10 @@ bool CmdLineParser::parseFromArgs(int argc, const char* const argv[])
                 mSettings->xml = true;
             }

+            // use a file filter
+            else if (std::strncmp(argv[i], "--file-filter=", 14) == 0)
+                mSettings->fileFilter = std::string(argv[i] + 14);
+
             // Only print something when there are errors
             else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0)
                 mSettings->quiet = true;
@@ -1035,6 +1039,9 @@ void CmdLineParser::printHelp()
               "    --exitcode-suppressions=<file>\n"
               "                         Used when certain messages should be displayed but\n"
               "                         should not cause a non-zero exitcode.\n"
+              "    --file-filter=<str>  Analyze only those files matching the given filter str\n"
+              "                         Example: --file-filter=*bar.cpp analyzes only files\n"
+              "                                  that end with bar.cpp.\n"
               "    --file-list=<file>   Specify the files to check in a text file. Add one\n"
               "                         filename per line. When file is '-,' the file list will\n"
               "                         be read from standard input.\n"

The current release version of cppcheck appears to be 2.7.


问:
using styled components i got stuck while displaying a image. i don't know where things went wrong
here is my code I am trying to display an image on my document but it is not visible:
is something wrong with the styled component or I have placed something wrong somewhere

this code is from the lama dev  React e-commerce video I am practicing that eCommerce
https://youtu.be/c1xTDSIXit8

```<code>import { ArrowLeftOutlined, ArrowRightOutlined } from '@material-ui/icons'
import React from 'react'
import styled from "styled-components"
import dummy from '../img/girl.png'

const Container=styled.div`
    height:100vh;
    width:100%;
    display:flex;
    position:relative;
    `
const Arrow= styled.div`
    width:50px;
    height:50px;
    background-color:#fff7f7;
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    position:absolute;
    top:0;
    bottom:0;
    left: ${props=>props.direction === 'left' && '15px'};
    right: ${props=>props.direction === 'right' && '15px'};
    margin:auto;
    cursor:pointer;
    opacity:0.5;
    `
const Wrapper=styled.div`
height:100%;
`
const Slide= styled.div`
width:100vw:
height:100vh;
display:flex;
align-items:center;
`
const ImgContainer= styled.div`
height:100%;
flex:1;
`
const Image= styled.div`
height:80%;
`
const InfoContainer= styled.div`
flex:1;
padding:50px;
`
const Title= styled.h1``
const Description= styled.p``
const Button= styled.button``

const Slider = () => {
  return (
    <Container>
        <Arrow direction='left'>
            <ArrowLeftOutlined/>
        </Arrow>
        <Wrapper>
            <Slide>
            <ImgContainer>
                <Image src={dummy}/>
            </ImgContainer>
            <InfoContainer>
                <Title>SUMMER SAL</Title>
                <Description>DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.</Description>
                <Button>SHOW NOW</Button>
            </InfoContainer>
            </Slide>
        </Wrapper>
        <Arrow direction='right'>
            <ArrowRightOutlined/>
        </Arrow>
    </Container>
  )
}

export default Slider
</code>```

there is no error in my code but I can't view the image

答:
Here, I can see in the code that the div component is used from styled components to display an image.

Simply replace the below code:

```<code>const Image= styled.div`
    height:80%;
`
</code>```

With the below code

```<code>const Image= styled.img`
    height:80%;
`
</code>```

Body:
here is my code I am trying to display an image on my document but it is not visible:
is something wrong with the styled component or I have placed something wrong somewhere

this code is from the lama dev  React e-commerce video I am practicing that eCommerce
https://youtu.be/c1xTDSIXit8

import { ArrowLeftOutlined, ArrowRightOutlined } from '@material-ui/icons'
import React from 'react'
import styled from "styled-components"
import dummy from '../img/girl.png'

const Container=styled.div`
    height:100vh;
    width:100%;
    display:flex;
    position:relative;
    `
const Arrow= styled.div`
    width:50px;
    height:50px;
    background-color:#fff7f7;
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    position:absolute;
    top:0;
    bottom:0;
    left: ${props=>props.direction === 'left' && '15px'};
    right: ${props=>props.direction === 'right' && '15px'};
    margin:auto;
    cursor:pointer;
    opacity:0.5;
    `
const Wrapper=styled.div`
height:100%;
`
const Slide= styled.div`
width:100vw:
height:100vh;
display:flex;
align-items:center;
`
const ImgContainer= styled.div`
height:100%;
flex:1;
`
const Image= styled.div`
height:80%;
`
const InfoContainer= styled.div`
flex:1;
padding:50px;
`
const Title= styled.h1``
const Description= styled.p``
const Button= styled.button``

const Slider = () => {
  return (
    <Container>
        <Arrow direction='left'>
            <ArrowLeftOutlined/>
        </Arrow>
        <Wrapper>
            <Slide>
            <ImgContainer>
                <Image src={dummy}/>
            </ImgContainer>
            <InfoContainer>
                <Title>SUMMER SAL</Title>
                <Description>DON'T COMPROMISE ON STYLE! GET FLAT 30% OFF FOR NEW ARRIVALS.</Description>
                <Button>SHOW NOW</Button>
            </InfoContainer>
            </Slide>
        </Wrapper>
        <Arrow direction='right'>
            <ArrowRightOutlined/>
        </Arrow>
    </Container>
  )
}

export default Slider

there is no error in my code but I can't view the image

Body:
Here, I can see in the code that the div component is used from styled components to display an image.

Simply replace the below code:

const Image= styled.div`
    height:80%;
`

With the below code

const Image= styled.img`
    height:80%;
`


问:
Should I store object literals inside the jQuery namespace or the global namespace?
In trying to clean up the jQuery $(document).ready function in some of my scripts.  Instead of having lots of functions inside that function I've been creating an object literal that has properties for the functionality I'm adding to the page like so:

```<code>var taskPage = {

    init: function() {

        this.validate();
        this.changeActivityType();
    },

    validate: function() {...
    },

    changeActivityType: function() {...
    }
};
</code>```

Should I put this object literal in the global namespace or should I put this object in the jQuery namespace somehow?

答:
Global namespace is a no no!

You can enclose it in a self-executing anonymous function.

```<code>(function($){
    var taskPage = {

        init: function() {

            this.validate();
            this.changeActivityType();
        },

        validate: function() {...
        },

        changeActivityType: function() {...
        }
    };

    $(document).ready();

})(jQuery);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In trying to clean up the jQuery $(document).ready function in some of my scripts.  Instead of having lots of functions inside that function I've been creating an object literal that has properties for the functionality I'm adding to the page like so:

var taskPage = {

    init: function() {

        this.validate();
        this.changeActivityType();
    },

    validate: function() {...
    },

    changeActivityType: function() {...
    }
};

Should I put this object literal in the global namespace or should I put this object in the jQuery namespace somehow?

Body:
Global namespace is a no no!

You can enclose it in a self-executing anonymous function.

(function($){
    var taskPage = {

        init: function() {

            this.validate();
            this.changeActivityType();
        },

        validate: function() {...
        },

        changeActivityType: function() {...
        }
    };

    $(document).ready();

})(jQuery);


问:
How to assign values to a Java 2d array?
Java beginner here. I have 2 string arrays A, B. for a new empty array C, I'd like to assign each value in A B to C. Code I've got as following:

```<code>String[] A = {"banana", "orange", "apple"};
String[] B = {"2", "3"};
String[][] C;

private String[][] mix() {
  for (int i = 0; i < this.A.length; i++) {
    for (int j = 0; j < this.B.length; j++) {
        C[i][j] = {A[i], B[j]};
    }
}
</code>```

The above code gives me error on C[i][j] = {A[i], B[j]};:

```<code>Array constants can only be used in initializers
</code>```

EDIT: my expected output would be

C = {{"banana", "2"}, {"orange", "2"}, {"apple", "2"}, {"banana", "3"}, {"orange", "3"}, {"apple", "3"}}

or any permutation like above with all 6 combinations.

答:
As pointed out in comments you need to use C[i] = ... to assign a 2D array to a 3D array, and you need to use new String[]{...} to correctly create a 2D array like so C[i] = new String[]{A[i], B[j]};.

You can only use C[i][j] = ...; if you assign a string like so C[i][j] = "apple";

Here is a working example with the format you are looking for. Note how we use the logic above, and how we have swapped around the B and A for loops to get the correct output:

```<code>String[] A = {"banana", "orange", "apple"};
String[] B = {"2", "3"};
String[][] C;

private String[][] mix() {
    //We need to initialize the array before we place items into it
    //We know the size because you want every fruit to show up for every number so we use "B.length"
    C = new String[B.length][];

    //Use B in the outer loop because so that 2 comes out first, then 3
    for (int i = 0; i < this.B.length; i++) {

        //Use A in the inner loop to get the pattern you want
        for (int j = 0; j < this.A.length; j++) {

            //Assign a new 2D child array to the 3D array "C"
            C[i] = new String[]{this.A[j], this.B[i]};
        }
    }
}
</code>```

Now if you loop through the C array it will produce exactly your result:

```<code>{{"banana", "2"}, {"orange", "2"}, {"apple", "2"}, {"banana", "3"}, {"orange", "3"}, {"apple", "3"}}
</code>```

Body:
Java beginner here. I have 2 string arrays A, B. for a new empty array C, I'd like to assign each value in A B to C. Code I've got as following:

String[] A = {"banana", "orange", "apple"};
String[] B = {"2", "3"};
String[][] C;

private String[][] mix() {
  for (int i = 0; i < this.A.length; i++) {
    for (int j = 0; j < this.B.length; j++) {
        C[i][j] = {A[i], B[j]};
    }
}

The above code gives me error on C[i][j] = {A[i], B[j]};:

Array constants can only be used in initializers

EDIT: my expected output would be

C = {{"banana", "2"}, {"orange", "2"}, {"apple", "2"}, {"banana", "3"}, {"orange", "3"}, {"apple", "3"}}

or any permutation like above with all 6 combinations.

Body:
As pointed out in comments you need to use C[i] = ... to assign a 2D array to a 3D array, and you need to use new String[]{...} to correctly create a 2D array like so C[i] = new String[]{A[i], B[j]};.

You can only use C[i][j] = ...; if you assign a string like so C[i][j] = "apple";

Here is a working example with the format you are looking for. Note how we use the logic above, and how we have swapped around the B and A for loops to get the correct output:

String[] A = {"banana", "orange", "apple"};
String[] B = {"2", "3"};
String[][] C;

private String[][] mix() {
    //We need to initialize the array before we place items into it
    //We know the size because you want every fruit to show up for every number so we use "B.length"
    C = new String[B.length][];

    //Use B in the outer loop because so that 2 comes out first, then 3
    for (int i = 0; i < this.B.length; i++) {

        //Use A in the inner loop to get the pattern you want
        for (int j = 0; j < this.A.length; j++) {

            //Assign a new 2D child array to the 3D array "C"
            C[i] = new String[]{this.A[j], this.B[i]};
        }
    }
}

Now if you loop through the C array it will produce exactly your result:

{{"banana", "2"}, {"orange", "2"}, {"apple", "2"}, {"banana", "3"}, {"orange", "3"}, {"apple", "3"}}


问:
How to serialize PersistentMap and return it
I have a simple map<string, string> and would like to add to it and return it serialized.
Here is my code

```<code>organizations: PersistentMap<string, string> = new PersistentMap<
    string,
    string
  >("oc");

getOrgList(): PersistentMap<string, string> {
    return this.organizations;
  }
</code>```

The contract call panics as below:

```<code>kind: {
    ExecutionError: 'Smart contract panicked: Cannot parse JSON, filename: "~lib/assemblyscript-json/decoder.ts" line: 144 col: 5'
  },
</code>```

Update:
When the map is empty, I get no errors.
I add items to the map using

```<code>this.organizations.set(orgCode, orgName);
</code>```

and I call it from the command line like that

```<code>near call cert.msaudi.testnet createOrgId '{\"orgCode\":\"AAA\",\"orgName\":\"AAAA\"}' --accountId=msaudi.testnet
</code>```

edit:full contract code

```<code>import { Context, PersistentMap } from "near-sdk-core";

@nearBindgen
export class Contract {
  public organizations: PersistentMap<string, string> = new PersistentMap<
    string,
    string
  >("oc"); //orgCode, orgName

  //check if organization name is there from the frontend to save processing time.
  @mutateState()
  createOrgId(orgCode: string, orgName: string): string {
    this.organizations.set(orgCode, orgName);
    return "Organization created with code:" + orgCode + " name: " + orgName;
  }

  getOrgList(): PersistentMap<string, string> {
    return this.organizations;
  }
}
</code>```

答:
If you want to return a regular map from the contract, you need to parse the map from PersistentMap<string,string> to a regular Map<string,string>. Not only that, but you need to keep track of the keys separately from the map if you want to return all values in addition to the keys. That's because the PersistentMap doesn't store the keys, and you cannot retrieve them (Here's a separate thread about it).

 keys: PersistentVector<string>; // Need to store the keys as well

 getOrgList(): Map<string, string> {
    const res: Map<string, string> = new Map<string, string>();
    for (let i = 0; i < this.keys.length; i++) {
      res.set(this.keys[i], this.organizations.getSome(this.keys[i]));
    }
    return res;
 }
```

Body:
I have a simple map<string, string> and would like to add to it and return it serialized.
Here is my code

organizations: PersistentMap<string, string> = new PersistentMap<
    string,
    string
  >("oc");

getOrgList(): PersistentMap<string, string> {
    return this.organizations;
  }

The contract call panics as below:

kind: {
    ExecutionError: 'Smart contract panicked: Cannot parse JSON, filename: "~lib/assemblyscript-json/decoder.ts" line: 144 col: 5'
  },

Update:
When the map is empty, I get no errors.
I add items to the map using

this.organizations.set(orgCode, orgName);

and I call it from the command line like that

near call cert.msaudi.testnet createOrgId '{\"orgCode\":\"AAA\",\"orgName\":\"AAAA\"}' --accountId=msaudi.testnet

edit:full contract code

import { Context, PersistentMap } from "near-sdk-core";

@nearBindgen
export class Contract {
  public organizations: PersistentMap<string, string> = new PersistentMap<
    string,
    string
  >("oc"); //orgCode, orgName

  //check if organization name is there from the frontend to save processing time.
  @mutateState()
  createOrgId(orgCode: string, orgName: string): string {
    this.organizations.set(orgCode, orgName);
    return "Organization created with code:" + orgCode + " name: " + orgName;
  }

  getOrgList(): PersistentMap<string, string> {
    return this.organizations;
  }
}


问:
Fastapi works with uvicorn but not when deployed
I've deployed an api with Fastapi that worked perfectly when using uvicorn to host it locally. Now when I deployed it with Deta, it shows "500 internal server error".

Is there something wrong with my main.py? In the Deta Visor it only says response is "Internal server error" and also "No errors".

My main.py:

#!/usr/bin/python3
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import sqlite3

from fastapi.params import Depends

app = FastAPI()

origins = [
    "*"
]

async def get_db():
    conn = sqlite3.connect("C:/Users/Administrator/Desktop/CryptoBotDB.sqlite", check_same_thread=False)
    try:
        yield conn
    finally:
        conn.close()

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root(db = Depends(get_db)):
    cur = db.cursor()

    cur.execute("SELECT money_start_total FROM Trades")
    trades = cur.fetchall()
    profit_lista = []
    for item in trades:
        profit_lista.append(round(int(item[0]), 0))

    profit_perc_lista = []
    cur.execute("SELECT profit_perc FROM Trades")
    profit_perc = cur.fetchall()
    for item in profit_perc:
        profit_perc_lista.append(str(round(int(item[0]), 0)) + "%")

    cur.execute("SELECT month FROM Trades")
    months = cur.fetchall()
    month_lista = []
    for item in months:
        month_lista.append(item[0][:2] + '/20' + item[0][2:])

    profit_dict = {"data": [{'data': profit_lista, 'labels': month_lista}]}
    data_lista = []

    for i in range((len(trades))):
        data_lista.append({"month": month_lista[i], "money": profit_perc_lista[i], "style": "color:red"})
    data_lista.reverse()

    cur.execute("SELECT money_end_total from Trades")
    money_now = cur.fetchall()[-1][-1]
    if money_now > 3001.0:
        total_profits = '+' + str(round((1 - (int(money_now) / 3001.0)) * 100, 2)) + '%'
    else:
        total_profits = '-' + str(round((1 - (int(money_now) / 3001.0)) * 100, 2)) + '%'
    total_profits_cash = str(round(money_now - 3001.0, 2)) + '€'

    total_profits_dict = {"profits_perc": total_profits, "profits_cash": total_profits_cash}

    cur.execute("SELECT profperc from cur_pos")
    cur_perc = cur.fetchone()
    cur.execute("SELECT profcash from cur_pos")
    cur_cash = cur.fetchone()

    cur_dictionary = {"cur_perc": cur_perc, "cur_cash": cur_cash}

    return profit_dict, data_lista, total_profits_dict, cur_dictionary

```

答:
It seems like you are trying to read a SQLite database that doesn't exist inside your Deta Micro. You are referencing a "C" Drive, which is only accessible to your code locally.

To solve this, make sure to include the database file with you code, next to the "main.py" file and deploy. Then you need to adjust your db code like this:

async def get_db():
    conn = sqlite3.connect("CryptoBotDB.sqlite", check_same_thread=False)
    try:
        yield conn
    finally:
        conn.close()
```

If you ever get stuck, feel free to reach out to us (the Deta team) on Discord/Slack/Intercom (links on our website) – we're pretty responsive.

Body:
It seems like you are trying to read a SQLite database that doesn't exist inside your Deta Micro. You are referencing a "C" Drive, which is only accessible to your code locally.

To solve this, make sure to include the database file with you code, next to the "main.py" file and deploy. Then you need to adjust your db code like this:

async def get_db():
    conn = sqlite3.connect("CryptoBotDB.sqlite", check_same_thread=False)
    try:
        yield conn
    finally:
        conn.close()

If you ever get stuck, feel free to reach out to us (the Deta team) on Discord/Slack/Intercom (links on our website) – we're pretty responsive.


问:
Customize Zoom in/out button in leaflet.js
I am trying to customize zoom control (+/-), so it should appear in the right side like Google maps (https://www.google.com/maps/)

I tried to add float:right; but it didn't work.

From the CSS file :

/* zoom control */

.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
  font: bold 18px 'Lucida Console', Monaco, monospace;
  text-indent: 1px;
  }
.leaflet-control-zoom-out {
  font-size: 20px;
  }

.leaflet-touch .leaflet-control-zoom-in {
  font-size: 22px;
  }
.leaflet-touch .leaflet-control-zoom-out {
  font-size: 24px;
  }
```

http://jsfiddle.net/hsy7v/1/

答: if your using leaflet in angular don't forget about ::ngdeep without this styles do not apply</p>

Body:
I am trying to customize zoom control (+/-), so it should appear in the right side like Google maps (https://www.google.com/maps/)

I tried to add float:right; but it didn't work.

From the CSS file :

/* zoom control */

.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
  font: bold 18px 'Lucida Console', Monaco, monospace;
  text-indent: 1px;
  }
.leaflet-control-zoom-out {
  font-size: 20px;
  }

.leaflet-touch .leaflet-control-zoom-in {
  font-size: 22px;
  }
.leaflet-touch .leaflet-control-zoom-out {
  font-size: 24px;
  }

http://jsfiddle.net/hsy7v/1/


问:
ContainsKey Thread Safe
In the following code:

```<code>public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}
</code>```

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB

答:
I believe its not thread safe,

I would suggest go thru below link, it shows implementation of the thread safe dictionary, or its better to develop your own synchronization.

http://lysaghtn.weebly.com/synchronised-dictionary.html

OwnerDisplayName: MBeckius

ContentLicense: CC BY-SA 2.5

Title: ContainsKey Thread Safe

Body:
In the following code:

public class StringCache
{
    private readonly object lockobj = new object();

    private readonly Dictionary<int, string> cache = new Dictionary<int, string>();

    public string GetMemberInfo(int key)
    {
        if (cache.ContainsKey(key))
            return cache[key];
        lock (lockobj)
        {
            if (!cache.ContainsKey(key))
                cache[key] = GetString(key);
        }
        return cache[key];
    }

    private static string GetString(int key)
    {
        return "Not Important";
    }
}

1) Is ContainsKey thread safe?  IOW, what happens if that method is executing when another thread is adding something to the dictionary?
2) For the first return cache[key], is there any chance that it could return a garbled value?

TIA,

MB


问:
Modeling many-to-one with constraints?
I'm attempting to create a database model for movie classifications, where each movie could have a single classification from each of one of multiple rating systems (e.g. BBFC, MPAA). This is the current design, with all implied PKs and FKs:

```<code>TABLE Movie
(
    MovieId INT -- PK
)

TABLE ClassificationSystem
(
    ClassificationSystemId TINYINT -- PK
)

TABLE Classification
(
    ClassificationId INT,          -- PK
    ClassificationSystemId TINYINT -- FK
)

TABLE MovieClassification
(
    MovieId INT,          -- composite PK, FK
    ClassificationId INT, -- composite PK, FK
    Advice NVARCHAR(250)  -- description of why the classification was given
)
</code>```

The problem is with the MovieClassification table whose constraints would allow multiple classifications from the same system, whereas it should ideally only permit either zero or one classifications from a given system.

Is there any reasonable way to restructure this so that a movie having exactly zero or one classifications from any given system is enforced by database constraints, given the following requirements?

Do not duplicate information that could be looked up (i.e. duplicating ClassificationSystemId in the MovieClassification table is not a good solution because this could get out of sync with the value in the Classification table)

Remain extensible to multiple classification systems (i.e. a new classification system does not require any changes to the table structure)?

Note also the Advice column - each mapping of a movie to a classification needs to have a textual description of why that classification was given to that movie. Any design would need to support this.

答:
Honestly, i'd just change the data model around a little bit.

```<code>create table #Movies (PK_moID int identity(1,1), moName varchar(50) primary key(PK_moID))
create table #ClassificationSystem (PK_csID int identity(1,1), csName varchar(50) primary key(PKcsID))
create table #Classification (PK_clID int identity(1,1), FK_csID int)
create table #MovieClassification (FK_moID int, FK_csID int, FK_clID int primary key (FK_moID, FK_csID))
</code>```

now, with your movie classification you have a composite pk of the movie and the system, so you can only get one rating of a movie per system (even if you add new systems).  you can also create a relationship from movie classification to the classificaiton table to enfore the data.

Title: Modeling many-to-one with constraints?

Body:
I'm attempting to create a database model for movie classifications, where each movie could have a single classification from each of one of multiple rating systems (e.g. BBFC, MPAA). This is the current design, with all implied PKs and FKs:

TABLE Movie
(
    MovieId INT -- PK
)

TABLE ClassificationSystem
(
    ClassificationSystemId TINYINT -- PK
)

TABLE Classification
(
    ClassificationId INT,          -- PK
    ClassificationSystemId TINYINT -- FK
)

TABLE MovieClassification
(
    MovieId INT,          -- composite PK, FK
    ClassificationId INT, -- composite PK, FK
    Advice NVARCHAR(250)  -- description of why the classification was given
)

The problem is with the MovieClassification table whose constraints would allow multiple classifications from the same system, whereas it should ideally only permit either zero or one classifications from a given system.

Is there any reasonable way to restructure this so that a movie having exactly zero or one classifications from any given system is enforced by database constraints, given the following requirements?

Do not duplicate information that could be looked up (i.e. duplicating ClassificationSystemId in the MovieClassification table is not a good solution because this could get out of sync with the value in the Classification table)

Remain extensible to multiple classification systems (i.e. a new classification system does not require any changes to the table structure)?

Note also the Advice column - each mapping of a movie to a classification needs to have a textual description of why that classification was given to that movie. Any design would need to support this.

Body:
Honestly, i'd just change the data model around a little bit.

create table #Movies (PK_moID int identity(1,1), moName varchar(50) primary key(PK_moID))
create table #ClassificationSystem (PK_csID int identity(1,1), csName varchar(50) primary key(PKcsID))
create table #Classification (PK_clID int identity(1,1), FK_csID int)
create table #MovieClassification (FK_moID int, FK_csID int, FK_clID int primary key (FK_moID, FK_csID))

now, with your movie classification you have a composite pk of the movie and the system, so you can only get one rating of a movie per system (even if you add new systems).  you can also create a relationship from movie classification to the classificaiton table to enfore the data.


问:
I/UrlLauncher(17669): component name for (url) is null
Why does it throw an error and give me the link is empty even though the link exists?
And when I use launch (url) alone, the link opens without any problems.

```<code> String StateUrl = 'View App' ;
 var url = 'https://www.youtube.com/watch?v=-k0IXjCHObw' ;
body: Column(
        children: [
          Text(StateUrl),
          Center(
            child: ElevatedButton.icon(
                onPressed: () async{
                  try {
                    await canLaunch(url) ?
                    await launch(url):
                    throw 'Error';
                  } catch(e){
                    setState(() {
                      StateUrl = e.toString() ;
                    });
                  }
                },
                icon: const Icon(FontAwesomeIcons.link),
                label:  const Text('View Url')
            ),
          ),
        ],
      ),
</code>```

Performing hot reload:

D/EGL_emulation(17669): app_time_stats: avg=17852.65ms min=658.78ms
max=35046.52ms count=2 I/UrlLauncher(17669): component name for
https://www.youtube.com/watch?v=-k0IXjCHObw is null
D/EGL_emulation(17669): app_time_stats: avg=8279.72ms min=8279.72ms
max=8279.72ms count=1

答:
If you come here looking for why your email link (mailto:email@example.com) doesn't work, then try this out.

Don't call canLaunch for mailto links - use it only for http and https!

Since I have both http(s) and mailto links in my app, I use the try-catch block.

Here is the full function:

class UrlHandler {
  /// Attempts to open the given [url] in in-app browser. Returns `true` after successful opening, `false` otherwise.
  static Future<bool> open(String url) async {
    try {
      await launch(
        url,
        enableJavaScript: true,
      );
      return true;
    } catch (e) {
      log(e.toString());
      return false;
    }
  }
}
```

Body:
Why does it throw an error and give me the link is empty even though the link exists?
And when I use launch (url) alone, the link opens without any problems.

 String StateUrl = 'View App' ;
 var url = 'https://www.youtube.com/watch?v=-k0IXjCHObw' ;
body: Column(
        children: [
          Text(StateUrl),
          Center(
            child: ElevatedButton.icon(
                onPressed: () async{
                  try {
                    await canLaunch(url) ?
                    await launch(url):
                    throw 'Error';
                  } catch(e){
                    setState(() {
                      StateUrl = e.toString() ;
                    });
                  }
                },
                icon: const Icon(FontAwesomeIcons.link),
                label:  const Text('View Url')
            ),
          ),
        ],
      ),

Performing hot reload:

D/EGL_emulation(17669): app_time_stats: avg=17852.65ms min=658.78ms
max=35046.52ms count=2 I/UrlLauncher(17669): component name for
https://www.youtube.com/watch?v=-k0IXjCHObw is null
D/EGL_emulation(17669): app_time_stats: avg=8279.72ms min=8279.72ms
max=8279.72ms count=1


问:
How do you flush a buffered log4j FileAppender?
In log4j, when using a FileAppender with BufferedIO=true and BufferSize=xxx properties (i.e. buffering is enabled), I want to be able to flush the log during normal shutdown procedure. Any ideas on how to do this?</p>

答:
The only solution that worked for me is waiting for a while:</p>
```<code>private void flushAppender(Appender appender) {
    // this flush seems to be useless
    ((AbstractOutputStreamAppender<?>) appender).getManager().flush();
    try {
        Thread.sleep(500); // wait for log4j to flush logs
    } catch (InterruptedException ignore) {
    }
}
</code>```

Body:
The only solution that worked for me is waiting for a while:

private void flushAppender(Appender appender) {
    // this flush seems to be useless
    ((AbstractOutputStreamAppender<?>) appender).getManager().flush();
    try {
        Thread.sleep(500); // wait for log4j to flush logs
    } catch (InterruptedException ignore) {
    }
}


问:
Category products don't match database
I have a script that deletes specific entries from [prefix]_category_product ( => removes products from a category) using SQL.

Though the changes are successfully made in the database and in the Prestashop admin interface, they don't show on the front-end. Some products which have been removed from a category still appear in it.

I don't think it's a caching issue because emptying the Prestashop cache and the browser cache doesn't work, and they don't disappear after a few days/weeks. If I add and remove the product from the category manually using the admin interface it works. What am I doing wrong?

答:
You are forgetting the ps_product and ps_product_shop tables,
where the id_category_default value is stored.</p>

Title: Category products don't match database


问:
Why the navbar dropdown in bootstrap 5 doesn't work
When I copy the code of the navbar dropdown from the documentation of bootstrap 5 the dropdown doesn't work, if I click on the dropdown the links ("action", "another action", "something else")  of this last one don't show up, what should I do?

here is the code :

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  Logo

      Link 1

      Link 2

              Dropdown link

        Link 1
        Link 2
        Link 3

Navbar With Dropdown

This example adds a dropdown menu in the navbar.

Navbar

    Navbar
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

          Home

          Link

                  Dropdown

Action

Another action

Something else here

```

答:
Change this:

 Dropdown link
```
<p>To this:</p>
<pre class="lang-CSS prettyprint-override"><code>Dropdown Link
</code>```

Also add this:

```<code><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</code>```

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  Logo

      Link 1

      Link 2

      Dropdown Link

        Link 1
        Link 2
        Link 3

Navbar With Dropdown

This example adds a dropdown menu in the navbar.

Navbar

    Navbar
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

          Home

          Link

                  Dropdown

Action

Another action

Something else here

```

Body:
Change this:

<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown"> Dropdown link </a>

To this:

<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Dropdown Link</a>

Also add this:

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<head>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
  <!-- Brand -->
  <a class="navbar-brand" href="#">Logo</a>

  <!-- Links -->
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Link 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link 2</a>
    </li>

    <!-- Dropdown -->
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Dropdown Link</a>
      <div class="dropdown-menu">
        <a class="dropdown-item" href="#">Link 1</a>
        <a class="dropdown-item" href="#">Link 2</a>
        <a class="dropdown-item" href="#">Link 3</a>
      </div>
    </li>
  </ul>
</nav>
<br>

<div class="container">
  <h3>Navbar With Dropdown</h3>
  <p>This example adds a dropdown menu in the navbar.</p>
</div>

<h1>Navbar</h1>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                  Dropdown
                </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
      </ul>
    </div>
  </div>
</nav>

<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>


问:
Axios post-request doesn't send complete object
I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:

```<code>const file = values.beleg1;
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async function () {
                    const result = reader.result.toString().split(',')[1];
                    await valuesObj.push({ name: 'base64Image', value: result });

                };
                reader.onerror = function (error) {
                    console.log('Error: ', error);
                };
</code>```

If I then log the object 'valuesObj' it does show that the base64-object is attached to the main-object.

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request

```<code>axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data: valuesObj,
            })
                .then((response: AxiosResponse) => {
                    setLoadingText('');
                    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
                    const objectUrl: string = window.URL.createObjectURL(blob);
                    window.open(objectUrl);
                })
                .catch((error) => {
                    console.log(error);
                });
</code>```

What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?

答:
Your Problem seems to be that your async axios request gets the value of your valuesObj, before onload actually adds your new record.

Sorry forgot a solution ^^

Either you put your axios request directly into the pipe...

```<code>reader.onload =
        (async function () {
            const result = reader.result.toString().split(',')[1]
            await valuesObj.push({ name: 'base64Image', value: result})
            return valuesObj
        })
        .then(
            data =>
            axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data,
            })
            .then((response: AxiosResponse) => {
                setLoadingText('')
                const blob: Blob = new Blob([response.data], { type: 'application/pdf' })
                const objectUrl: string = window.URL.createObjectURL(blob)
                window.open(objectUrl)
            })
            .catch(console.log))
        )

})
</code>```

or you create another async function which you can call from your onload or from another async fn, which awaits both async events.

Body:
I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:

const file = values.beleg1;
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async function () {
                    const result = reader.result.toString().split(',')[1];
                    await valuesObj.push({ name: 'base64Image', value: result });

                };
                reader.onerror = function (error) {
                    console.log('Error: ', error);
                };

If I then log the object 'valuesObj' it does show that the base64-object is attached to the main-object.

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request

axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data: valuesObj,
            })
                .then((response: AxiosResponse) => {
                    setLoadingText('');
                    const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
                    const objectUrl: string = window.URL.createObjectURL(blob);
                    window.open(objectUrl);
                })
                .catch((error) => {
                    console.log(error);
                });

What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?

Body:
Your Problem seems to be that your async axios request gets the value of your valuesObj, before onload actually adds your new record.

Sorry forgot a solution ^^

Either you put your axios request directly into the pipe...

reader.onload =
        (async function () {
            const result = reader.result.toString().split(',')[1]
            await valuesObj.push({ name: 'base64Image', value: result})
            return valuesObj
        })
        .then(
            data =>
            axios({
                url: 'http://localhost:8080/createPDF',
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                responseType: 'blob',
                data,
            })
            .then((response: AxiosResponse) => {
                setLoadingText('')
                const blob: Blob = new Blob([response.data], { type: 'application/pdf' })
                const objectUrl: string = window.URL.createObjectURL(blob)
                window.open(objectUrl)
            })
            .catch(console.log))
        )

})

or you create another async function which you can call from your onload or from another async fn, which awaits both async events.


问:
How to get all repos in Azure DevOps
I have number of projects in Azure DevOps. I want to able to iterate through all Repos in Azure DevOps and get the name of the Repo, Creator of Repo and Last Updated/commit.

And get a notification when some one created new Repo?

答:
Another option (easier with the Auth part) is to retrieve your Azure Repositories is through the AZ CLI using following commands:

Log into Azure

```<code>az login -t $tenant
</code>```

First configure default values for organization and project, this
will help you to not specify --project and --organization parameters
in every az devops/repos command:

```<code>az devops configure -d organization=$organizationUrl project=$project
</code>```

List repositories of your subscription and default project and organization

```<code>az repos list --subscription $subscription
</code>```

Title: How to get all repos in Azure DevOps

Body:
Another option (easier with the Auth part) is to retrieve your Azure Repositories is through the AZ CLI using following commands:

Log into Azure

az login -t $tenant

First configure default values for organization and project, this
will help you to not specify --project and --organization parameters
in every az devops/repos command:

az devops configure -d organization=$organizationUrl project=$project

List repositories of your subscription and default project and organization

az repos list --subscription $subscription


问:
Why does the sprite costume not change?
I'm just starting to play about in Scratch...

I seem to have a sprite of a cat with two 'costumes', which I guess are like frames.

I made this sequence:

...but when I click the green flag the cat moves to the right but the costumes don't switch.

If I make a simpler sequence:

...and manually change the costume in the drop-down then the costume does change.

What is the limitation here?

答:
This is by design. By default, loops have a built-in delay of about 1/30 second. (There are ways to eliminate that delay, but that is off-topic here.) This was done to help inexperienced programmers witness the effect of a loop; possibly also to make execution speed more consistent (regardless of client's CPU power).

In your case, that means costume2 will be visible for 1/30 second before switching back to costume1.
Costume1 on the other hand, is instantly followed up by costume2.
Consequently, you will only see costume2.

There are various ways to fix that.

Change your script to repeat 5 { move 10 steps; next costume; } This gives both costumes an implicit 1/30 second delay. If this is still too short, add a delay (wait ... seconds). Note: next costume wraps around, so assuming the sprite has 2 costumes, it will flip back and forth between costume1 and costume2.

Too jerky? Use glide ... secs to ... instead of 'move and wait'.

Or just take smaller steps; swap costume once every few steps.

Make two separate scripts running in parallel, one for the movement, the other for switching costumes. That makes it easier to specify a different delay for each.

Title: Why does the sprite costume not change?


问:
Type safety in Dart using Container
I found something strange in dart. If there is a list that contains instances of a base class (in this example Super), the list can be set with a list of inherited instances. It seems that this changes the list type at runtime.

Is this intended behavior or is this a bug in Dart?

```<code>abstract class Super {}

class A extends Super {}

class B extends Super {}

class Container {
List<Super> mylist = [];
Container(this.mylist);
}

void main() {
// 1. dont't works
final container = Container(<A>[A(), A()]);
// 2. works
final container = Container([A(), A()]);
print(container.mylist.runtimeType);

container.mylist.add(B());
print(container.mylist);
}
</code>```

If case 1 is used in the code above I get the following error:

```<code>JSArray<A>
Uncaught Error: TypeError: Instance of 'B': type 'B' is not a subtype of type 'A'
</code>```

The error is at the line where I try to add an instance of B:

```<code>container.mylist.add(B());
</code>```

答:
When you do:

final container = Container([A(), A()]);
```
<p>you explicitly create a <code>List<A></code> object.  Although <code>Container</code>'s constructor expects a <code>List<Super></code>, it accepts a <code>List<A></code> argument because Dart considers <code>Generic<Derived></code> to be a subtype of <code>Generic<Base></code> if <code>Derived</code> is a subtype of <code>Base</code>.  Your later attempt to do <code>container.mylist.add(B());</code> will fail because <code>container.mylist</code> is actually a <code>List<A></code> and therefore cannot legally store any <code>B</code> elements.</p>
<p>When you instead do:</p>
<pre class="lang-dart prettyprint-override"><code>final container = Container([A(), A()]);
</code>```

then, because the List literal is not given an explicit type, its type is inferred to be List<Super> from Container's expected construction parameter. container.mylist.add(B()); will succeed since container.mylist is actually a List<Super> and therefore can legally store B elements.

Title: Type safety in Dart using Container

Body:
I found something strange in dart. If there is a list that contains instances of a base class (in this example Super), the list can be set with a list of inherited instances. It seems that this changes the list type at runtime.

Is this intended behavior or is this a bug in Dart?

abstract class Super {}

class A extends Super {}

class B extends Super {}

class Container {
List<Super> mylist = [];
Container(this.mylist);
}

void main() {
// 1. dont't works
final container = Container([A(), A()]);
// 2. works
final container = Container([A(), A()]);
print(container.mylist.runtimeType);

container.mylist.add(B());
print(container.mylist);
}

If case 1 is used in the code above I get the following error:

JSArray
Uncaught Error: TypeError: Instance of 'B': type 'B' is not a subtype of type 'A'

The error is at the line where I try to add an instance of B:

container.mylist.add(B());

Body:
When you do:

final container = Container(<A>[A(), A()]);

you explicitly create a List<A> object.  Although Container's constructor expects a List<Super>, it accepts a List<A> argument because Dart considers Generic<Derived> to be a subtype of Generic<Base> if Derived is a subtype of Base.  Your later attempt to do container.mylist.add(B()); will fail because container.mylist is actually a List<A> and therefore cannot legally store any B elements.

When you instead do:

final container = Container([A(), A()]);

then, because the List literal is not given an explicit type, its type is inferred to be List<Super> from Container's expected construction parameter. container.mylist.add(B()); will succeed since container.mylist is actually a List<Super> and therefore can legally store B elements.


问:
superscript in Java String
Does Java String supports superscript in a String? If yes then how can I use it, I have searched the web and also the API but not able to figure out how I can use it for my purpose

Although this will be printed on the webpage, I cannot use the html tag here, any suggestions please

答:
This can be achieved using unicode characters as seen here:

```<code>   System.out.println("cm\u00b2");
   System.out.println("meter/second\u00b2");
   System.out.println("meter/second\u00b3");
</code>```

This results in the below output:

```<code>cm²
meter/second²
meter/second³
</code>```

More unicode characters can be found here - https://unicode-table.com/en/

Title: superscript in Java String

Body:
This can be achieved using unicode characters as seen here:

   System.out.println("cm\u00b2");
   System.out.println("meter/second\u00b2");
   System.out.println("meter/second\u00b3");

This results in the below output:

cm²
meter/second²
meter/second³

More unicode characters can be found here - https://unicode-table.com/en/


问:
Laravel (Lumen) connect to database on another server on same network
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();
```
<p>And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:</p>
<h3>Attempt 1</h3>
```DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] No route to host</p>
</blockquote>
<h3>Attempt 2</h3>
```DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'</p>
</blockquote>
<h3>Attempt 3</h3>
```DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.

答: Type the IPv4 local of the VM database. (You can try to ping one VM to each other to be sure that the connection is workign between the vms)</p>

Body:
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();

And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:

Attempt 1

DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] No route to host

Attempt 2

DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'

Attempt 3

DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.


问:
Pretrained Tensorflow model RGB -> RGBY channel extension
I am working on the protein analysis project. We receive the images* of proteins with 4 filters (Red, Green, Blue and Yellow). Every of those RGBY channels contains unique data as different cellular structures are visible with different filters.

The idea is to use a pre-trained network e.g. VGG19 and extend the number of channels from default 3 to 4. Something like this:

(My appologies, I am not allowed to add images directly before 10 reputation, please press the "Run code snippet" button to visualize):

```

Picture: VGG model with RGB extended to RGBY

The Y channel should be the copy of the existing pretrained channel. Then it is possible to make use of the pretrained weights.

Does anyone have an idea of how such extension of a pretrained network can be achieved?

*
Author of the collage - Allunia from Kaggle, "Protein Atlas - Exploration and Baseline" kernel.

答:
Beyond the RGBY case, the following snippet works generally by copying or removing the layer's weights and/or biases vectors dimensions as needed. Please refer to numpy documentation on what numpy.resize does: in the case of the original question it copies the B-channel weights onto the Y-channel (or more generally onto any higher dimensionality).

import numpy as np
import tensorflow as tf
...

model = ...  # your RGBY model is here
pretrained_model = tf.keras.models.load_model(...)  # pretrained RGB model

# the following assumes that the layers match with the two models and
# only the shapes of weights and/or biases are different
for pretrained_layer, layer in zip(pretrained_model.layers, model.layers):
    pretrained = pretrained_layer.get_weights()
    target = layer.get_weights()
    if len(pretrained) == 0:  # skip input, pooling and other no weights layers
        continue
    try:
        # set the pretrained weights as is whenever possible
        layer.set_weights(pretrained)
    except:
        # numpy.resize to the rescue whenever there is a shape mismatch
        for idx, (l1, l2) in enumerate(zip(pretrained, target)):
            target[idx] = np.resize(l1, l2.shape)

        layer.set_weights(target)
```

Body:
I am working on the protein analysis project. We receive the images* of proteins with 4 filters (Red, Green, Blue and Yellow). Every of those RGBY channels contains unique data as different cellular structures are visible with different filters.

The idea is to use a pre-trained network e.g. VGG19 and extend the number of channels from default 3 to 4. Something like this:

(My appologies, I am not allowed to add images directly before 10 reputation, please press the "Run code snippet" button to visualize):

Picture: VGG model with RGB extended to RGBY

The Y channel should be the copy of the existing pretrained channel. Then it is possible to make use of the pretrained weights.

Does anyone have an idea of how such extension of a pretrained network can be achieved?

*
Author of the collage - Allunia from Kaggle, "Protein Atlas - Exploration and Baseline" kernel.


问:
Writing to files in Bulk vs Chunks

Setup

With standard C code (= no platform specific code), I have written a program to do the following:

Get starting clock()

Open a file

write a ~250MB long string to it using one of the below listed modes

close the file.

Repeat 2...4 10000 times as fast as possible, rip storage unit

Get ending clock()

Do some time calculations and output

A) bulk mode: Write everything at once (= one call to fwrite)

B) chunk mode: Write string in chunks. One chunk is slightly more than 1MB. (= multiple calls to fwrite, about ~250).

Then, I let the program run on two different computers.

Expection

I expect A) being faster than B).

Results

Below was on my beefy PC with a Samsung 970 EVO M.2 SSD (CPU = AMD Ryzen 2700x: 8 cores / 16 threads). The output on this one is slightly wrong, it should've been Ns/file, not Ns/write)

Below was on my laptop. I don't really know what type of SSD is installed (and I don't bother too much to check it out). If it matters, or anyone wants to and knows how to research, the laptop is a Surface Book 3.

Conclusion

Beefy PC: B) is faster than A), against expectations.

Laptop: A) is faster than B), within expectations.

My best guess is that some sort of hidden parellization is at work. Either the CPU does smart things, the SSD does very smart things, or they work together to do incredibly smart things. But pinning and writing down anything further sounds too absurd for me to keep it staying here.

What explains the difference in my expectation and the results?

The benchmark

Check out https://github.com/rphii/Rlib, under examples/writecomp.c

More Text

I noticed this effect while working on my beefy PC with a string of length ~25MB. Since B) was a marginal, but consistent, ~4ms faster than A), I increased the string length and did a more thorough test.

答:
Since no one's gonna do it, I'll answer my question based on the comment I got.

clock does not measure the wall clock time but the CPU time. Please read this post.

Reads/writes are generally buffered.

Operating systems generally uses an in-memory cache (especially for HDD).

SSD reads can be faster in parallel (and often are for recent ones) while HDD are almost never faster in parallel. (this quite recent post provides some information about caching and buffering).

Title: Writing to files in Bulk vs Chunks


问:
How to copy a variable into a lambda from a list?
I am trying to generate a list of lambdas that I will later apply to an object, but when I try to do it via a comprehension or a loop over a list, the reference to the variable is kept, rather than the value itself. Let me illustrate.

Assume your object class is something like this:

class Object:
 def function(self, x):
  print(x)
```
<p>So when you create the object and invoke it you get something like this:</p>
<pre class="lang-py prettyprint-override"><code>o = Object()
o.function(0)
>>> 0
</code>```

Now, if I manually construct my list of lambdas it would look like this:

lambdas = [
 lambda x: x.function(0),
 lambda x: x.function(1),
 lambda x: x.function(2)
]
```
<p>Which I can then apply to my previously created object:</p>
<pre class="lang-py prettyprint-override"><code>for l in lambdas:
 l(o)
>>> 0
>>> 1
>>> 2
</code>```

However, when I generate the lambda list from another list, I only get the reference to the latest element of the list:

lambdas = [lambda x: x.function(i) for i in range(2)]
for l in lambdas:
 l(o)
>>> 2
>>> 2
>>> 2
```

On closer inspection I can see that each lambda has a different memory address, so they are NOT references to the same function.

So I can only assume that the lambda is keeping a reference to i which has a final value of 2 and therefore when invoked, it takes the value.

So my question is if its possible to set the value of the variable inside the lambda before invocation?

Note: The usa case for a list of lambdas is to pass to the agg function of a Pandas groupby on a DataFrame. I am not looking for a solution to the pandas problem, but curious about the general solution.

答:
What takes place is that in this expression, the "living" (nonlocal) i variable is
used inside each lambda created. And at the end of the for loop, its value is the last value taken - which will be used when the lambdas are actually called.

```<code>lambdas = [lambda x: x.function(i) for i in range(2)]
</code>```

The fix for that is to create an intermediary namespace which will "freeze" the nonlocal variable value at the time the lambda is created. This is usually done with another lambda:

```<code> lambdas = [(lambda i: (lambda x: x.function(i)))(i) for i in range(2)]
</code>```

So, bear with me - in the above expression, for each execution of the for i loop, a new, disposable lambda i is created and called imediatelly with the current value of the i used in the for. Inside it, this value is bound to a local i variable, that is unique to this disposable lambda i (in Python internal workings, it gets its own "cell"). This unique iis then used in the second, permanent, lambda x expression. Whenever that one is called, it will use the i value persisted in the outter lambda i call. The external lambda i then returns the lambda x expression as its result, but its nonlocal i is bound to the value used inside the lambda i, not the one used in the for i.

This is a common problem in Python, but can't be fixed because it is part of how the language works.

There is a shorter, and working, form to "freeze" the i from for i when each lambda i is created, that does not require an outer function scope: when a function is created, the values passed as default for its parameters are stored along with the function. Then, if one stores the current value of i as a default value, it won't change when the variable i itself does:

```<code>lambdas = [lambda x, i=i: x.function(i) for i in range(2)]
</code>```

Here, in the lambda x, i=i:  snippet, the value of i in the scope the lambda is created is stored as the default value for the parameter i, which works as a local (in contrast with a nonlocal) variable inside the lambda function itself.

Body:
I am trying to generate a list of lambdas that I will later apply to an object, but when I try to do it via a comprehension or a loop over a list, the reference to the variable is kept, rather than the value itself. Let me illustrate.

Assume your object class is something like this:

class Object:
 def function(self, x):
  print(x)

So when you create the object and invoke it you get something like this:

o = Object()
o.function(0)
>>> 0

Now, if I manually construct my list of lambdas it would look like this:

lambdas = [
 lambda x: x.function(0),
 lambda x: x.function(1),
 lambda x: x.function(2)
]

Which I can then apply to my previously created object:

for l in lambdas:
 l(o)
>>> 0
>>> 1
>>> 2

However, when I generate the lambda list from another list, I only get the reference to the latest element of the list:

lambdas = [lambda x: x.function(i) for i in range(2)]
for l in lambdas:
 l(o)
>>> 2
>>> 2
>>> 2

On closer inspection I can see that each lambda has a different memory address, so they are NOT references to the same function.

So I can only assume that the lambda is keeping a reference to i which has a final value of 2 and therefore when invoked, it takes the value.

So my question is if its possible to set the value of the variable inside the lambda before invocation?

Note: The usa case for a list of lambdas is to pass to the agg function of a Pandas groupby on a DataFrame. I am not looking for a solution to the pandas problem, but curious about the general solution.

Body:
What takes place is that in this expression, the "living" (nonlocal) i variable is
used inside each lambda created. And at the end of the for loop, its value is the last value taken - which will be used when the lambdas are actually called.

lambdas = [lambda x: x.function(i) for i in range(2)]

The fix for that is to create an intermediary namespace which will "freeze" the nonlocal variable value at the time the lambda is created. This is usually done with another lambda:

 lambdas = [(lambda i: (lambda x: x.function(i)))(i) for i in range(2)]

So, bear with me - in the above expression, for each execution of the for i loop, a new, disposable lambda i is created and called imediatelly with the current value of the i used in the for. Inside it, this value is bound to a local i variable, that is unique to this disposable lambda i (in Python internal workings, it gets its own "cell"). This unique iis then used in the second, permanent, lambda x expression. Whenever that one is called, it will use the i value persisted in the outter lambda i call. The external lambda i then returns the lambda x expression as its result, but its nonlocal i is bound to the value used inside the lambda i, not the one used in the for i.

This is a common problem in Python, but can't be fixed because it is part of how the language works.

There is a shorter, and working, form to "freeze" the i from for i when each lambda i is created, that does not require an outer function scope: when a function is created, the values passed as default for its parameters are stored along with the function. Then, if one stores the current value of i as a default value, it won't change when the variable i itself does:

lambdas = [lambda x, i=i: x.function(i) for i in range(2)]

Here, in the lambda x, i=i:  snippet, the value of i in the scope the lambda is created is stored as the default value for the parameter i, which works as a local (in contrast with a nonlocal) variable inside the lambda function itself.


问:
How to pass a custom hook as props and retain parent context?
I have a created a custom formatting hook like so:

```<code>const useFormatter = (value, short = false) => {
  if (isNaN(value ?? undefined) || !isFinite(value)) {
    return "";
  }
  if (aggregator === Aggregator.TOTAL) {
    const prefix = metric !== Metric.USAGE ? getCurrencySymbol(currency) : "";
    if (short) {
      return prefix + formatNumber(value, 2);
    } else {
      return prefix + formatDecimalNumber(value, 2, 0);
    }
  } else if (aggregator === Aggregator.TOTAL_OVER_TOTAL) {
    let suffix = "";
    let prefix = "";
    switch (metric) {
      case Metric.COST:
        // Cost/Usage
        prefix = "$";
        break;
      case Metric.SAVINGS:
        // Savings/Cost
        suffix = "%";
        value = (1 - 1 / (value + 1)) * 100;
        break;
      default:
    }

    const d = value % 1;
    let minFracDigits = 2;
    if (d < 9e-5) {
      minFracDigits = 6;
    } else if (d < 9e-4) {
      minFracDigits = 5;
    } else if (d < 9e-3) {
      minFracDigits = 4;
    } else if (d < 9e-2) {
      minFracDigits = 3;
    }
    return `${prefix}${formatDecimalNumber(value, minFracDigits, 0)}${suffix}`;
  } else {
    const suffix = "%";
    return formatDecimalNumber(value * 100, 2, 0) + suffix;
  }
};

export default useFormatter;
</code>```

All this is, is shared logic for formatting a number, then I import the hook into a parent component and use like so:

```<code>const formatter = React.useCallback(
    useFormatter(value, short = false),
      [aggregator, currency, metric]
    );
</code>```

It is then passed down to a child in the props where the value and short (optional) params are given to it, the reason for this setup is to maintain the parent context and then pass it down essentially as a callback. Unfortunately this code does not compile and I don't understand why, the error I am getting is:

```<code>./src/Components/Dashboard/test_comp.js
  Line 88:18:  'value' is not defined  no-undef
  Line 88:25:  'short' is not defined  no-undef
</code>```

Now in the child component it is being given these values, but clearly I am missing something here. Why does my code not compile?

答:
I think the main problem with this code is that you treat it as a custom hook while it is a plain function.

One would choose to write a custom hook, when the logic needs access to other hooks. You are not using any hooks inside your function, therefore make it a plain function and do not use the hook naming convention. Furthermore udalmik is right by saying that you are passing the result of the invocation rather than the function.

From the React docs:

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

Body:
I have a created a custom formatting hook like so:

const useFormatter = (value, short = false) => {
  if (isNaN(value ?? undefined) || !isFinite(value)) {
    return "";
  }
  if (aggregator === Aggregator.TOTAL) {
    const prefix = metric !== Metric.USAGE ? getCurrencySymbol(currency) : "";
    if (short) {
      return prefix + formatNumber(value, 2);
    } else {
      return prefix + formatDecimalNumber(value, 2, 0);
    }
  } else if (aggregator === Aggregator.TOTAL_OVER_TOTAL) {
    let suffix = "";
    let prefix = "";
    switch (metric) {
      case Metric.COST:
        // Cost/Usage
        prefix = "$";
        break;
      case Metric.SAVINGS:
        // Savings/Cost
        suffix = "%";
        value = (1 - 1 / (value + 1)) * 100;
        break;
      default:
    }

    const d = value % 1;
    let minFracDigits = 2;
    if (d < 9e-5) {
      minFracDigits = 6;
    } else if (d < 9e-4) {
      minFracDigits = 5;
    } else if (d < 9e-3) {
      minFracDigits = 4;
    } else if (d < 9e-2) {
      minFracDigits = 3;
    }
    return `${prefix}${formatDecimalNumber(value, minFracDigits, 0)}${suffix}`;
  } else {
    const suffix = "%";
    return formatDecimalNumber(value * 100, 2, 0) + suffix;
  }
};

export default useFormatter;

All this is, is shared logic for formatting a number, then I import the hook into a parent component and use like so:

const formatter = React.useCallback(
    useFormatter(value, short = false),
      [aggregator, currency, metric]
    );

It is then passed down to a child in the props where the value and short (optional) params are given to it, the reason for this setup is to maintain the parent context and then pass it down essentially as a callback. Unfortunately this code does not compile and I don't understand why, the error I am getting is:

./src/Components/Dashboard/test_comp.js
  Line 88:18:  'value' is not defined  no-undef
  Line 88:25:  'short' is not defined  no-undef

Now in the child component it is being given these values, but clearly I am missing something here. Why does my code not compile?


问:
Retrieve all records with LIMIT in mysql
I have the following MySQL query;

```<code>SELECT records FROM users
LIMIT 1
</code>```

One record will be retrieved. Suppose I want to retrieve all records but still use the keyword LIMIT. Can I do something like this?

```<code>SELECT records FROM users
LIMIT ALL
</code>```

答:
If you want to retrieve all data then just use

select * from tbl;

Body:
I have the following MySQL query;

SELECT records FROM users
LIMIT 1

One record will be retrieved. Suppose I want to retrieve all records but still use the keyword LIMIT. Can I do something like this?

SELECT records FROM users
LIMIT ALL


问:
Change color of inactive IconButton
I have following widgets implemented:

Which parameter of ThemeData I should change to change grey color of IconButton?

Widget code:

```<code>TextFormField(
                    controller: _loginPageViewModel.emailTEC,
                    validator: _loginPageViewModel.validator.validateEmail,
                    decoration: InputDecoration(
                      hintText: S.of(context).email,
                      suffixIcon: IconButton(
                        onPressed: _loginPageViewModel.emailTEC.clear,
                        icon: const Icon(Icons.clear),
                      ),
                    )
                )
</code>```

ThemeData code:

```<code>ThemeData(
      brightness: Brightness.light,
      //primaryColor: const Color(0xFFF8C537),
      scaffoldBackgroundColor: const Color(0xFFFFDDA1),
      appBarTheme: const AppBarTheme(
        color: Color(0xFFE53935),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
            primary: const Color(0xFFFFD151),
            onPrimary: Colors.black,
            elevation: 0.5
        ),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        hintStyle: TextStyle(color: Color(0xFFFFD151)),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFEDB230))
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFFFFD151)),
        ),
      ),
colorScheme: ThemeData().colorScheme.copyWith(primary: Color(0xFFEDB230)),
  );
</code>```

答:
While the IconButton is being used as suffixIcon, you can change its color from InputDecoration.

theme: Theme.of(context).copyWith(
  inputDecorationTheme: Theme.of(context).inputDecorationTheme.copyWith(
        iconColor: Colors.orange,
      ),
),
```

More about inputDecorationTheme.

Title: Change color of inactive IconButton

Body:
I have following widgets implemented:

Which parameter of ThemeData I should change to change grey color of IconButton?

Widget code:

TextFormField(
                    controller: _loginPageViewModel.emailTEC,
                    validator: _loginPageViewModel.validator.validateEmail,
                    decoration: InputDecoration(
                      hintText: S.of(context).email,
                      suffixIcon: IconButton(
                        onPressed: _loginPageViewModel.emailTEC.clear,
                        icon: const Icon(Icons.clear),
                      ),
                    )
                )

ThemeData code:

ThemeData(
      brightness: Brightness.light,
      //primaryColor: const Color(0xFFF8C537),
      scaffoldBackgroundColor: const Color(0xFFFFDDA1),
      appBarTheme: const AppBarTheme(
        color: Color(0xFFE53935),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
            primary: const Color(0xFFFFD151),
            onPrimary: Colors.black,
            elevation: 0.5
        ),
      ),
      inputDecorationTheme: const InputDecorationTheme(
        hintStyle: TextStyle(color: Color(0xFFFFD151)),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFEDB230))
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Color(0xFFFFD151)),
        ),
      ),
colorScheme: ThemeData().colorScheme.copyWith(primary: Color(0xFFEDB230)),
  );

Body:
While the IconButton is being used as suffixIcon, you can change its color from InputDecoration.

theme: Theme.of(context).copyWith(
  inputDecorationTheme: Theme.of(context).inputDecorationTheme.copyWith(
        iconColor: Colors.orange,
      ),
),

More about inputDecorationTheme.


问:
unique elements in a haskell list
okay, this is probably going to be in the prelude, but: is there a standard library function for finding the unique elements in a list? my (re)implementation, for clarification, is:</p>

```<code>has :: (Eq a) => [a] -> a -> Bool
has [] _ = False
has (x:xs) a
  | x == a    = True
  | otherwise = has xs a

unique :: (Eq a) => [a] -> [a]
unique [] = []
unique (x:xs)
  | has xs x  = unique xs
  | otherwise = x : unique xs
</code>```

答:
A library-based solution:

We can use that style of Haskell programming where all looping and recursion activities are pushed out of user code and into suitable library functions. Said library functions are often optimized in ways that are way beyond the skills of a Haskell beginner.

A way to decompose the problem into two passes goes like this:

produce a second list that is parallel to the input list, but with duplicate elements suitably marked

eliminate elements marked as duplicates from that second list

For the first step, duplicate elements don't need a value at all, so we can use [Maybe a] as the type of the second list. So we need a function of type:

```<code>pass1 :: Eq a => [a] -> [Maybe a]
</code>```

Function pass1 is an example of stateful list traversal where the state is the list (or set) of distinct elements seen so far. For this sort of problem, the library provides the mapAccumL :: (s -> a -> (s, b)) -> s -> [a] -> (s, [b]) function.

Here the mapAccumL function requires, besides the initial state and the input list, a step function argument, of type s -> a -> (s, Maybe a).

If the current element x is not a duplicate, the output of the step function is Just x and x gets added to the current state. If x is a duplicate, the output of the step function is Nothing, and the state is passed unchanged.

Testing under the ghci interpreter:

```<code>$ ghci
 GHCi, version 8.8.4: https://www.haskell.org/ghc/  :? for help
 λ>
 λ> stepFn s x = if (elem x s) then (s, Nothing) else (x:s, Just x)
 λ>
 λ> import Data.List(mapAccumL)
 λ>
 λ> pass1 xs = mapAccumL stepFn [] xs
 λ>
 λ> xs2 = snd $ pass1 "abacrba"
 λ> xs2
 [Just 'a', Just 'b', Nothing, Just 'c', Just 'r', Nothing, Nothing]
 λ>
</code>```

Writing a pass2 function is even easier. To filter out Nothing non-values, we could use:

```<code>import Data.Maybe( fromJust, isJust)
pass2 = (map fromJust) . (filter isJust)
</code>```

but why bother at all ? - as this is precisely what the catMaybes library function does.

```<code> λ>
 λ> import Data.Maybe(catMaybes)
 λ>
 λ> catMaybes xs2
 "abcr"
 λ>
</code>```

Putting it all together:

Overall, the source code can be written as:

```<code>import Data.Maybe(catMaybes)
import Data.List(mapAccumL)

uniques :: (Eq a) => [a] -> [a]
uniques = let  stepFn s x = if (elem x s) then (s, Nothing) else (x:s, Just x)
          in   catMaybes . snd . mapAccumL stepFn []
</code>```

This code is reasonably compatible with infinite lists, something occasionally referred to as being “laziness-friendly”:

```<code> λ>
 λ> take 5 $ uniques $ "abacrba" ++ (cycle "abcrf")
 "abcrf"
 λ>
</code>```

Efficiency note:
If we anticipate that it is possible to find many distinct elements in the input list and we can have an Ord a instance, the state can be implemented as a Set object rather than a plain list, this without having to alter the overall structure of the solution.

Title: unique elements in a haskell list

Body:
okay, this is probably going to be in the prelude, but: is there a standard library function for finding the unique elements in a list? my (re)implementation, for clarification, is:

has :: (Eq a) => [a] -> a -> Bool
has [] _ = False
has (x:xs) a
  | x == a    = True
  | otherwise = has xs a

unique :: (Eq a) => [a] -> [a]
unique [] = []
unique (x:xs)
  | has xs x  = unique xs
  | otherwise = x : unique xs

Body:
A library-based solution:

We can use that style of Haskell programming where all looping and recursion activities are pushed out of user code and into suitable library functions. Said library functions are often optimized in ways that are way beyond the skills of a Haskell beginner.

A way to decompose the problem into two passes goes like this:

produce a second list that is parallel to the input list, but with duplicate elements suitably marked

eliminate elements marked as duplicates from that second list

For the first step, duplicate elements don't need a value at all, so we can use [Maybe a] as the type of the second list. So we need a function of type:

pass1 :: Eq a => [a] -> [Maybe a]

Function pass1 is an example of stateful list traversal where the state is the list (or set) of distinct elements seen so far. For this sort of problem, the library provides the mapAccumL :: (s -> a -> (s, b)) -> s -> [a] -> (s, [b]) function.

Here the mapAccumL function requires, besides the initial state and the input list, a step function argument, of type s -> a -> (s, Maybe a).

If the current element x is not a duplicate, the output of the step function is Just x and x gets added to the current state. If x is a duplicate, the output of the step function is Nothing, and the state is passed unchanged.

Testing under the ghci interpreter:

$ ghci
 GHCi, version 8.8.4: https://www.haskell.org/ghc/  :? for help
 λ>
 λ> stepFn s x = if (elem x s) then (s, Nothing) else (x:s, Just x)
 λ>
 λ> import Data.List(mapAccumL)
 λ>
 λ> pass1 xs = mapAccumL stepFn [] xs
 λ>
 λ> xs2 = snd $ pass1 "abacrba"
 λ> xs2
 [Just 'a', Just 'b', Nothing, Just 'c', Just 'r', Nothing, Nothing]
 λ>

Writing a pass2 function is even easier. To filter out Nothing non-values, we could use:

import Data.Maybe( fromJust, isJust)
pass2 = (map fromJust) . (filter isJust)

but why bother at all ? - as this is precisely what the catMaybes library function does.

 λ>
 λ> import Data.Maybe(catMaybes)
 λ>
 λ> catMaybes xs2
 "abcr"
 λ>

Putting it all together:

Overall, the source code can be written as:

import Data.Maybe(catMaybes)
import Data.List(mapAccumL)

uniques :: (Eq a) => [a] -> [a]
uniques = let  stepFn s x = if (elem x s) then (s, Nothing) else (x:s, Just x)
          in   catMaybes . snd . mapAccumL stepFn []

This code is reasonably compatible with infinite lists, something occasionally referred to as being “laziness-friendly”:

 λ>
 λ> take 5 $ uniques $ "abacrba" ++ (cycle "abcrf")
 "abcrf"
 λ>

Efficiency note:
If we anticipate that it is possible to find many distinct elements in the input list and we can have an Ord a instance, the state can be implemented as a Set object rather than a plain list, this without having to alter the overall structure of the solution.


问:
Ignore field when inserting with Fluent Nhibernate
In my MySql database i have a field which is a timestamp. MySQL is inserting the time when the row is created and updates the time when a row is updated.

How do I tell NHibernate don't to insert anything in that field when inserting and updating. I still want to be able to read the property.

With my current mapping:

```<code>Map(x => x.CreateDate).Column("CreateDate");
</code>```

NHibernate tries to insert 0001-01-01 00:00:00, because the field is not nullable (And it should not be nullable)

I'm using Fluent Nhibernate.

答:
I believe you should be able to add ReadOnly() to get that effect.

```<code>Map(x => x.CreateDate).Column("CreateDate").ReadOnly();
</code>```

Body:
In my MySql database i have a field which is a timestamp. MySQL is inserting the time when the row is created and updates the time when a row is updated.

How do I tell NHibernate don't to insert anything in that field when inserting and updating. I still want to be able to read the property.

With my current mapping:

Map(x => x.CreateDate).Column("CreateDate");

NHibernate tries to insert 0001-01-01 00:00:00, because the field is not nullable (And it should not be nullable)

I'm using Fluent Nhibernate.

Body:
I believe you should be able to add ReadOnly() to get that effect.

Map(x => x.CreateDate).Column("CreateDate").ReadOnly();


问:
How do I create configuration for axios for default request headers in every http call?
https://github.com/MrFiniOrg/AxiosQuestion

I would like to have my project setup so that I do not have to specify the same request header in every http call.

I have searched this online but I have not been able to accomplish this in my project.

Would someone please assist me in resolving this issue I am having.
I am new to react and axios and I am not sure how to configure this.

My project seems to be doing this but it is sending the request 2 times.
One with the header and one without.

My axios call can be found in the app.js class component

答:
You can put it in a file (as explained here) and then import it in the top level

```<code>import { CssBaseline } from "@mui/material";
import "./App.css";
import ProfilePage from "./view/Profile/ProfilePage";
import "./service/axios-config"; //<---import it here

function App() {
  return (
    <div className="App">
      <CssBaseline />
      <ProfilePage />
    </div>
  );
}

export default App;
</code>```

instead of adding this code in the top level:

```<code>axios.defaults.baseURL = process.env.REACT_APP_BE_URL;
</code>```

Body:
You can put it in a file (as explained here) and then import it in the top level

import { CssBaseline } from "@mui/material";
import "./App.css";
import ProfilePage from "./view/Profile/ProfilePage";
import "./service/axios-config"; //<---import it here

function App() {
  return (
    <div className="App">
      <CssBaseline />
      <ProfilePage />
    </div>
  );
}

export default App;

instead of adding this code in the top level:

axios.defaults.baseURL = process.env.REACT_APP_BE_URL;


问:
Linking two code blocks together so that their output appears under the same category in the markdown
I've got a couple of charts that show two related data sets. I would like to have them appear in the same 'category' on the markdown, but under two separate 'subtitles' on the table of contents.

My YAML follows this pattern (though I have also used "toc:true" and "toc_float: true" previously):

```<code>---
title: "Update"
author: "Me"
date: "`r Sys.Date()`"
output:
  rmdformats::readthedown:
    fig_width: 12
    fig_height: 5
---
</code>```

The code I use to produce the charts in the markdown follows this format:

```<code># Time-series
##  Nominal

```{r chart1,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
Chart1
```
##  Real
```{r chart2,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
Chart2
```
</code>```

The 'category title' (Time-series) and 'subtitle' (Nominal) work as intended, and appear linked in the table of contents when the markdown is produced. The second 'subtitle' (Real) appears unlinked,  and while it seems to recognise that 'Real' is intended to be a subtitle in RStudio, when the markdown html is produced it neither recognizes as a subtitle nor does it link it to the 'category title' above. Does anyone how to achieve this?

答:
you are missing a blank line between chunk1 and ## Real

```<code>---
title: "Untitled"
author: "domingo"
date: "11 2 2022"
output:
  html_document:
    toc: TRUE
    toc_float: TRUE
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Time-series
##  Nominal

```{r chart1,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
plot(mtcars)
```

##  Real
```{r chart2,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
plot(mtcars)
```
</code>```

Body:
I've got a couple of charts that show two related data sets. I would like to have them appear in the same 'category' on the markdown, but under two separate 'subtitles' on the table of contents.

My YAML follows this pattern (though I have also used "toc:true" and "toc_float: true" previously):

---
title: "Update"
author: "Me"
date: "`r Sys.Date()`"
output:
  rmdformats::readthedown:
    fig_width: 12
    fig_height: 5
---

The code I use to produce the charts in the markdown follows this format:

# Time-series
##  Nominal

```{r chart1,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
Chart1
```
##  Real
```{r chart2,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
Chart2
```

The 'category title' (Time-series) and 'subtitle' (Nominal) work as intended, and appear linked in the table of contents when the markdown is produced. The second 'subtitle' (Real) appears unlinked,  and while it seems to recognise that 'Real' is intended to be a subtitle in RStudio, when the markdown html is produced it neither recognizes as a subtitle nor does it link it to the 'category title' above. Does anyone how to achieve this?

Body:
you are missing a blank line between chunk1 and ## Real

---
title: "Untitled"
author: "domingo"
date: "11 2 2022"
output:
  html_document:
    toc: TRUE
    toc_float: TRUE
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

# Time-series
##  Nominal

```{r chart1,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
plot(mtcars)
```

##  Real
```{r chart2,echo=FALSE, cache=FALSE, warning=FALSE, message=FALSE, fig.height=25,fig.width=10}
plot(mtcars)
```