问:
get out from git repository (VScode)
I'm using both remote connection in VSCode and GitHub. Usually, I would clone my project in "source control" using a URL.

Every time I close the connection, I would automatically "get out" from the git repository.

Today, I used "clone repository" in "explorer", then VSCode started showing 6000+ changes in "source control": they are the old files I stored in my remote folder(nothing about the URL I just cloned).

How can I get out from this status? (or get out from the git repository ?)

(All folders are showing "green U" except the one containing my cloned project)

答:
Check first if your "clone from Explorer" did not clone the repository in a wrong path, meaning one folder below or above the folder monitored by your Remote VSCode session.

VSCode would then display old files (from the old clone) as well as files from the cloned repository done in the wrong path.

The best remedy would be to open an SSH session and look for yourself (not through VSCode) in command-line, to see what is going on.

Ideally, you could simply remove any extra folder, and reclone everything, then open the cloned repo through Remote VSCode.

Title: get out from git repository (VScode)


来源: stackexchange

问:
Omitting metacharacters in python
I want to assing a path to a variable a:
a = "D:\misc\testsets\Real"

How can i omit the \t metacharacter without changing the folder name?

答:
Use raw strings:</p>
```<code>a = r"D:\misc\testsets\Real"
</code>```

ContentLicense: CC BY-SA 4.0

Title: Omitting metacharacters in python

Body:
Use raw strings:

a = r"D:\misc\testsets\Real"


答:
Try this:

r denotes raw string.

a = r"D:\misc\testsets\Real"
```

Title: Omitting metacharacters in python

Body:
I want to assing a path to a variable a:
a = "D:\misc\testsets\Real"

How can i omit the \t metacharacter without changing the folder name?


问:
How to Use jinja to render HTML without flask?
I need to render HTML page using jinja but without flask I read some other questions here but none had clear answer kindly let me know how can i achieve the same

```<code>File structre

1.py

HTML folder

1.html

templates
show persons.txt
</code>```

Here I need to render 1.html using 1.py - is it possble to do it in ofline mode

current 1.py

```<code>  from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('show persons.txt')

template = env.get_template('1.html ') #  how can i do the same with html here
output = template.render(persons=persons)
print(output)
</code>```

currently with this I am able to print output but if I need to get same data on a html file what can be done here  ?

Also if possible if also can we open the html page when run

updated code after Corralien comments is der a way to open this in browser directly

```<code>from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('1.html')

output = template.render(persons=persons)
print(output)
</code>```

Output

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Andrej -  34
Mark -  17
Thomas -  44
Lucy -  14
Robert -  23
Dragomir -  54

</body>
</html>
</code>```

答:
To open your html file into your browser, use webbrowser module (standard library)

```<code>import webbrowser
import tempfile

# Your code here
...
output = template.render(persons=persons)

with open('output.html', 'w') as fp:
    fp.write(output)
webbrowser.open_new('output.html')  # or .open_new_tab('output.html')
</code>```

Body:
I need to render HTML page using jinja but without flask I read some other questions here but none had clear answer kindly let me know how can i achieve the same

File structre

1.py

HTML folder

1.html

templates
show persons.txt

Here I need to render 1.html using 1.py - is it possble to do it in ofline mode

current 1.py

  from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('show persons.txt')

template = env.get_template('1.html ') #  how can i do the same with html here
output = template.render(persons=persons)
print(output)

currently with this I am able to print output but if I need to get same data on a html file what can be done here  ?

Also if possible if also can we open the html page when run

updated code after Corralien comments is der a way to open this in browser directly

from jinja2 import Environment, FileSystemLoader

persons = [
    {'name': 'Andrej', 'age': 34},
    {'name': 'Mark', 'age': 17},
    {'name': 'Thomas', 'age': 44},
    {'name': 'Lucy', 'age': 14},
    {'name': 'Robert', 'age': 23},
    {'name': 'Dragomir', 'age': 54}
]

file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)

template = env.get_template('1.html')

output = template.render(persons=persons)
print(output)

Output

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Andrej -  34
Mark -  17
Thomas -  44
Lucy -  14
Robert -  23
Dragomir -  54

Body:
To open your html file into your browser, use webbrowser module (standard library)

import webbrowser
import tempfile

# Your code here
...
output = template.render(persons=persons)

with open('output.html', 'w') as fp:
    fp.write(output)
webbrowser.open_new('output.html')  # or .open_new_tab('output.html')


问:
Searching for a matching items in between two sets with "complex in" condition
Lets say I have two sets:

```<code>set1 = set(("a", "b", 5), ("a", "c", 3))
set2 = set(("a", "b", 3), ("a", "b", 7))
</code>```

Each item has 3 values:

first index (first part of the key) e.g. "a"

second index (second part of the key) e.g. "b"

third index (timestamp last part of the key) e.g 5

I want to search for all of the elements of set 1, that have the corresponding item in set2, where the corresponding item is any item that has the same value at both the first and second index, but the value of the timestamp of the matching item from the set2 must be lower than the timestamp of the item from the set1.

From the example the matching item would be:

("a", "b", 5) ("a", "b", 3) timestamp of 3 < 5

✓ ("a", "b", 5) ("a", "b", 7)

("a", "c", 3) ("a", "b", 3) "c" != "b"

("a", "c", 3) ("a", "b", 7) "c" != "b"

Now the problem is I need to search for the items in set2 in n.log(n) time. That is why I am trying to keep the values in the set. If I was looking for the items without the timestamp:

```<code>set1 = set(("a", "b"), ("a", "c"))
set2 = set(("a", "b"), ("a", "b"))
</code>```

I could do:

```<code>for item from set1:
  if item in set2:
    print("Found matching item")
</code>```

But with the timestamp, I can't figure out how to implement this without two for loops.

答:
You can create a dictionary from set2 where the key is the first two parts of the tuple, and the value is a list of all the timestamps. Then you can find the matching key and test if the timestamp in set1 is lower than any of them.

```<code>d = {}
for item in set2:
    d.setdefault(item[0:2], []).append(item[2])

for item in set1:
    if any(item[2] > x for x in set2.get(item[0:2], [])):
        print("Found match")
</code>```

Body:
Lets say I have two sets:

set1 = set(("a", "b", 5), ("a", "c", 3))
set2 = set(("a", "b", 3), ("a", "b", 7))

Each item has 3 values:

first index (first part of the key) e.g. "a"

second index (second part of the key) e.g. "b"

third index (timestamp last part of the key) e.g 5

I want to search for all of the elements of set 1, that have the corresponding item in set2, where the corresponding item is any item that has the same value at both the first and second index, but the value of the timestamp of the matching item from the set2 must be lower than the timestamp of the item from the set1.

From the example the matching item would be:

("a", "b", 5) ("a", "b", 3) timestamp of 3 < 5

✓ ("a", "b", 5) ("a", "b", 7)

("a", "c", 3) ("a", "b", 3) "c" != "b"

("a", "c", 3) ("a", "b", 7) "c" != "b"

Now the problem is I need to search for the items in set2 in n.log(n) time. That is why I am trying to keep the values in the set. If I was looking for the items without the timestamp:

set1 = set(("a", "b"), ("a", "c"))
set2 = set(("a", "b"), ("a", "b"))

I could do:

for item from set1:
  if item in set2:
    print("Found matching item")

But with the timestamp, I can't figure out how to implement this without two for loops.

Body:
You can create a dictionary from set2 where the key is the first two parts of the tuple, and the value is a list of all the timestamps. Then you can find the matching key and test if the timestamp in set1 is lower than any of them.

d = {}
for item in set2:
    d.setdefault(item[0:2], []).append(item[2])

for item in set1:
    if any(item[2] > x for x in set2.get(item[0:2], [])):
        print("Found match")


问:
Sort number array using lodash/Javascript
I have a string array as below.

```<code>let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
</code>```

I want the expected output as below.

```<code>["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];
</code>```

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);```

答:
So, you need comparator for numbers and for signs.

Gerenal concept:

You can define sign priority like this:

const signPriority = {
  '+': 0,
  'n': 1, // n = no sign
  '-': 2,
}
```
<p>Where <code>key</code> is sign and <code>value</code> is sign weight we will use in comparator (<code>'n'</code> means "no sign").</p>
<p>Then we will split up array elements to number and sign, in comparator function and comparate them separetely:</p>
<pre class="lang-js prettyprint-override"><code>arr.sort((a, b) => {
    // If numbers are different ...
    if (parseInt(a) !== parseInt(b)) {
        // Just compare a numbers
        return parseInt(a) - parseInt(b);
    } else {
        // If sign matter ...
        // Extract sign from element or define as 'n' if no sign found
        const sign_a = ['+', '-'].includes(a.slice(-1)) ? a.slice(-1) : 'n';
        const sign_b = ['+', '-'].includes(b.slice(-1)) ? b.slice(-1) : 'n';
        // Compare signs using their weight
        return signPriority[sign_a] - signPriority[sign_b];
    }
})
</code>```

Full solution:

const signPriority = {
    '+': 0,
    'n': 1,
    '-': 2,
}

const arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

const sorted = arr.sort((a, b) => {
    if (parseInt(a) !== parseInt(b)) {
        return parseInt(a) - parseInt(b);
    } else {
        const sign_a = ['+', '-'].includes(a.slice(-1)) ? a.slice(-1) : 'n';
        const sign_b = ['+', '-'].includes(b.slice(-1)) ? b.slice(-1) : 'n';
        return signPriority[sign_a] - signPriority[sign_b];
    }
})

console.log(sorted);```

Body:
I have a string array as below.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

I want the expected output as below.

["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);

Body:
So, you need comparator for numbers and for signs.

Gerenal concept:

You can define sign priority like this:

const signPriority = {
  '+': 0,
  'n': 1, // n = no sign
  '-': 2,
}

Where key is sign and value is sign weight we will use in comparator ('n' means "no sign").

Then we will split up array elements to number and sign, in comparator function and comparate them separetely:

arr.sort((a, b) => {
    // If numbers are different ...
    if (parseInt(a) !== parseInt(b)) {
        // Just compare a numbers
        return parseInt(a) - parseInt(b);
    } else {
        // If sign matter ...
        // Extract sign from element or define as 'n' if no sign found
        const sign_a = ['+', '-'].includes(a.slice(-1)) ? a.slice(-1) : 'n';
        const sign_b = ['+', '-'].includes(b.slice(-1)) ? b.slice(-1) : 'n';
        // Compare signs using their weight
        return signPriority[sign_a] - signPriority[sign_b];
    }
})

Full solution:

const signPriority = {
    '+': 0,
    'n': 1,
    '-': 2,
}

const arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

const sorted = arr.sort((a, b) => {
    if (parseInt(a) !== parseInt(b)) {
        return parseInt(a) - parseInt(b);
    } else {
        const sign_a = ['+', '-'].includes(a.slice(-1)) ? a.slice(-1) : 'n';
        const sign_b = ['+', '-'].includes(b.slice(-1)) ? b.slice(-1) : 'n';
        return signPriority[sign_a] - signPriority[sign_b];
    }
})

console.log(sorted);


问:
How to combine two tables into one using my sql statement
i'm new in Database, i want to get a result from both sql table.
Here is the example

Table 1

Item Code
Price

A001
5 Dollar

A002
6 Dollar

Table 2 - Item Code Information

Item Code
Item Description

A001
Fish

A002
Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code
Item Description
Price

A001
Fish
5 Dollar

A002
Chicken
6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

答:
```<code>SELECT T1.ItemCode, T2.ItemDescription, T1.Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode;
</code>```

Here T1 is an alias for Table 1 and T2 is alias for Table2.

Body:
SELECT T1.ItemCode, T2.ItemDescription, T1.Price
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.ItemCode = T2.ItemCode;

Here T1 is an alias for Table 1 and T2 is alias for Table2.


问:
Truncation error SQL server 2005 Delete/Insert
So I am trying to do a bulk insert with SSIS and continually get:

"Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "String or binary data would be truncated."

Even though I already have a data conversion for every column into the exact same type as the table that the rows are getting inserted into. I used a view and the data looks like it supposed to just before the DB insert step. Still get the error.

Next I went into sql server management studio and setup an insert query into that damned table and still get the same truncation error. I then did a set ANSI_WARNINGS  OFF and the insert works data looks good in the table. Now when I try to delete this row I get the Truncation error.

My question besides any basic input to the situation is how can I turn off the ANSI_WARNINGS within SSIS so that the bulk load can go though?

答: Are there triggers on the table you're inserting into? Then the error may come from an action that the trigger takes.</p>

OwnerDisplayName: Andrew Jahn

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John Saunders


问:
Can anyone help me in defining a url without hook_menu and link it to a function in drupal?
In drupal I want to define a URL without hook_menu(), so that I can link the URL to a function that will be return a JSON (I want to call it from JavaScript code).

```<code>function(){
  $arr = array('a'=>'one', ..........);

  return json_encode($arr);
}
</code>```

Let me know how I can define a URL without hook_menu(), and link it to a function.

答:
Agreed. You can not. In drupal there are a few ways that a url is exposed.

A physical file exists, and therefore you can access it directly (tho
this would be outside of drupal most likely)

Via hook_menu

Via views page callbacks

Via url alias

... and a couple other modules which handle urls...

The reason this is so is because the urls that you are likely referring to don't really exist. The real path of path/json is actually index.php?q=path/json to the apache server

If you want to have a url just output JSON code.. finish the page with a call to:
drupal_json(..)  [http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_json/6]

ContentLicense: CC BY-SA 3.0

Body:
In drupal I want to define a URL without hook_menu(), so that I can link the URL to a function that will be return a JSON (I want to call it from JavaScript code).

function(){
  $arr = array('a'=>'one', ..........);

  return json_encode($arr);
}

Let me know how I can define a URL without hook_menu(), and link it to a function.


问:
Expo MediaLibrary.getAssetsAsync({album:album}) is not returning album - React Native
I am using Expo MediaLibrary to get videos from a specific folder and I am facing this problem.

MediaLibrary.getAssetsAsync() shows there are no media inside an album. while there are media inside the folder.

Code:

```<code>  let album = await MediaLibrary.getAlbumAsync("GrabTube")
  console.log(album )
  let assets = await MediaLibrary.getAssetsAsync({album:album })
  console.log(assets)
</code>```

response:

```<code>Object {
  "assetCount": 1,
  "id": "876214992",
  "title": "GrabTube",
}
Object {
  "assets": Array [],
  "endCursor": "0",
  "hasNextPage": false,
  "totalCount": 0,
}
</code>```

In the first console.log, it shows there is one item/asset inside the folder. But as shown inside the second console.log it shows the folder is empty.

Is there any fix for this?

答:
For some reason it's necessary to define the mediaType even when you have already defined the album...

to me the solution was change from :

```<code>let assets = await MediaLibrary.getAssetsAsync({album:album })
</code>```

to:

```<code>let assets = await MediaLibrary.getAssetsAsync({album:album, mediaType:'audio' })
</code>```

Body:
I am using Expo MediaLibrary to get videos from a specific folder and I am facing this problem.

MediaLibrary.getAssetsAsync() shows there are no media inside an album. while there are media inside the folder.

Code:

  let album = await MediaLibrary.getAlbumAsync("GrabTube")
  console.log(album )
  let assets = await MediaLibrary.getAssetsAsync({album:album })
  console.log(assets)

response:

Object {
  "assetCount": 1,
  "id": "876214992",
  "title": "GrabTube",
}
Object {
  "assets": Array [],
  "endCursor": "0",
  "hasNextPage": false,
  "totalCount": 0,
}

In the first console.log, it shows there is one item/asset inside the folder. But as shown inside the second console.log it shows the folder is empty.

Is there any fix for this?

Body:
For some reason it's necessary to define the mediaType even when you have already defined the album...

to me the solution was change from :

let assets = await MediaLibrary.getAssetsAsync({album:album })

to:

let assets = await MediaLibrary.getAssetsAsync({album:album, mediaType:'audio' })


问:
One stage vs two stage object detection
I was going through YOLOv4 paper which often uses the term one & two stage object detection. I was unable to understand what's the difference between the two types of object detectors. I am assuming

One stage does both region detection + object classification using one network only

two stage does the above operations using 2 different networks

Is this assumption correct?

答:
One-stage detectors:

Object classification and bounding-box regression are done directly without using pre-generated region proposals (candidate object bounding-boxes).

Two-stage detectors:

Generation of region proposals, e.g. by selective search as in R-CNN and Fast R-CNN, or by a Region Proposal Network (RPN) as in Faster R-CNN.

Object classification for each region proposal. Additionally other things can be done such as bounding-box regression for refining the region proposals, binary-mask prediction etc.

Two-stage detectors usually reach better accuracy but are slower than one-stage detectors.

(image taken from "On the Performance of One-Stage and Two-Stage Object Detectors in Autonomous Vehicles Using Camera Data")

Title: One stage vs two stage object detection


问:
Throw Custom Exception From ANTLR4 Grammar File
I have a grammar file which parse a specific file type. Now I need a simple thing.
I have a parser rule, and when the parser rule doesn't satisfy with the input token I need to throw my own custom exception.
That is, when my input file is giving me an extraneous error because the parser is expecting something and the i/p file doesn't has that. I want to throw an exception in this scenario.
Is this possible ?
If yes, How ?
If no, any work around ?

I'm beginner in this skill.

```<code>grammar Test

exampleParserRule : [a-z]+ ;

</code>```

My input file contains 12345. Now I need to throw a custom exception

答:
You can do this in your grammar:

```<code>grammar Test

@header {
package $your.$package;

import $your.$package.$yourExceptionClass;
}

exampleParserRule : [a-z]+ ;
catch [RecognitionException re] {
    reportError(re);
    recover(input,re);
    retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
    String msg = getErrorMessage(re, this.getTokenNames());
    throw new $yourExceptionClass(msg, re);
}
</code>```

It's up to you if you really want to reportError(logs to console) , recover etc. - but these are the defaults so it may be good to use these.
Also, you may want to generate a more human readable error message (use getErrorMessage.

If you do more complex work follow @mike-cargal`s advice.

Body:
I have a grammar file which parse a specific file type. Now I need a simple thing.
I have a parser rule, and when the parser rule doesn't satisfy with the input token I need to throw my own custom exception.
That is, when my input file is giving me an extraneous error because the parser is expecting something and the i/p file doesn't has that. I want to throw an exception in this scenario.
Is this possible ?
If yes, How ?
If no, any work around ?

I'm beginner in this skill.

grammar Test

exampleParserRule : [a-z]+ ;

My input file contains 12345. Now I need to throw a custom exception

Body:
You can do this in your grammar:

grammar Test

@header {
package $your.$package;

import $your.$package.$yourExceptionClass;
}

exampleParserRule : [a-z]+ ;
catch [RecognitionException re] {
    reportError(re);
    recover(input,re);
    retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
    String msg = getErrorMessage(re, this.getTokenNames());
    throw new $yourExceptionClass(msg, re);
}

It's up to you if you really want to reportError(logs to console) , recover etc. - but these are the defaults so it may be good to use these.
Also, you may want to generate a more human readable error message (use getErrorMessage.

If you do more complex work follow @mike-cargal`s advice.


问:
Converting from longitude\latitude to Cartesian coordinates
I have some earth-centered coordinate points given as latitude and longitude (WGS-84).

How can i convert them to Cartesian coordinates (x,y,z) with the origin at the center of the earth?

答:
```<code>Coordinate[] coordinates = new Coordinate[3];
coordinates[0] = new Coordinate(102, 26);
coordinates[1] = new Coordinate(103, 25.12);
coordinates[2] = new Coordinate(104, 16.11);
CoordinateSequence coordinateSequence = new CoordinateArraySequence(coordinates);

Geometry geo = new LineString(coordinateSequence, geometryFactory);

CoordinateReferenceSystem wgs84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem cartesinaCrs = DefaultGeocentricCRS.CARTESIAN;

MathTransform mathTransform = CRS.findMathTransform(wgs84, cartesinaCrs, true);

Geometry geo1 = JTS.transform(geo, mathTransform);
</code>```


问:
Menu with Text only not showing in Toolbar
I have to show back icon, Logo and text (Next) in Toolbar. Next is right aligned. I tried placing text via menu. I have set logo and back button to toolbar.

```<code>toolbar.setLogo(R.mipmap.logo);
toolbar.setNavigationIcon(R.mipmap.back);
</code>```

Also, I have inflated following menu in onCreateOptionsMenu

Menu inflated:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<item
    android:id="@+id/action_next"
    android:title="@string/next"
    app:showAsAction="always" />
</code>```

Text Menu is not visible at all. if I put icon in menu item, it gets displayed.
I have used android.support.v7.widget.Toolbar.

Edited:

I solved it. In case  someone else gets struck with such issue.

Please add

```<code><item name="android:actionMenuTextColor">@color/blue</item>
</code>```

in styles. Menu itemw as getting selected on click but was not visible, means it was showing white text color on white toolbar. Setting menuText color solved my problem.

答:
If you are getting an empty action with no text but blank space in it,
it might happen if you have created your own tool bar in the layout and have also used the Action bar in your theme's parent.
If you are creating your own toolbar then use parent="Theme.MaterialComponents.DayNight.NoActionBar" in your themes, both normal and night themes.

Body:
I have to show back icon, Logo and text (Next) in Toolbar. Next is right aligned. I tried placing text via menu. I have set logo and back button to toolbar.

toolbar.setLogo(R.mipmap.logo);
toolbar.setNavigationIcon(R.mipmap.back);

Also, I have inflated following menu in onCreateOptionsMenu

Menu inflated:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<item
    android:id="@+id/action_next"
    android:title="@string/next"
    app:showAsAction="always" />

Text Menu is not visible at all. if I put icon in menu item, it gets displayed.
I have used android.support.v7.widget.Toolbar.

Edited:

I solved it. In case  someone else gets struck with such issue.

Please add

<item name="android:actionMenuTextColor">@color/blue</item>

in styles. Menu itemw as getting selected on click but was not visible, means it was showing white text color on white toolbar. Setting menuText color solved my problem.


问:
How to install and enable php extension for tidy html on a beanstalk with amazon linux 2? (php ver. 7.4)
How to install php extension for tidy html on a beanstalk with amazon linux 2?

I have tried the following

```<code>commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"
</code>```

All of the commands run correctly but I get the following error at runtime of php scripts:

Class 'tidy' not found

答:
In the end I forgot to enable the php module·

Here the full beanstalk config file, so I wrote and added the command.

Note 1. this install the module for php 7.4

Note 2. for command 2-epel we have been forced to use the option "ignoreErrors": true, cause otherwise the deploy procedure will fail cause remi results already installed.

```<code>files:
  "/usr/local/bin/enable-tidy-php-module.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/bash

      cd /etc/php.d/
      ln -s /etc/opt/remi/php74/php.d/20-tidy.ini 20-tidy.ini
      cd /usr/lib64/php/modules/
      ln -s /opt/remi/php74/root/usr/lib64/php/modules/tidy.so tidy.so
      cd /usr/lib64/php-zts/modules/
      ln -s /opt/remi/php74/root/usr/lib64/php/modules/tidy.so tidy.so
      exit 0

commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
    ignoreErrors: true
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"
  5-enable-tidy-php:
    command: "/usr/local/bin/enable-tidy-php-module.sh"
</code>```

Body:
How to install php extension for tidy html on a beanstalk with amazon linux 2?

I have tried the following

commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"

All of the commands run correctly but I get the following error at runtime of php scripts:

Class 'tidy' not found

Body:
In the end I forgot to enable the php module·

Here the full beanstalk config file, so I wrote and added the command.

Note 1. this install the module for php 7.4

Note 2. for command 2-epel we have been forced to use the option "ignoreErrors": true, cause otherwise the deploy procedure will fail cause remi results already installed.

files:
  "/usr/local/bin/enable-tidy-php-module.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/bash

      cd /etc/php.d/
      ln -s /etc/opt/remi/php74/php.d/20-tidy.ini 20-tidy.ini
      cd /usr/lib64/php/modules/
      ln -s /opt/remi/php74/root/usr/lib64/php/modules/tidy.so tidy.so
      cd /usr/lib64/php-zts/modules/
      ln -s /opt/remi/php74/root/usr/lib64/php/modules/tidy.so tidy.so
      exit 0

commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
    ignoreErrors: true
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"
  5-enable-tidy-php:
    command: "/usr/local/bin/enable-tidy-php-module.sh"


问:
Hashtables Python put method showing IndexError
Below is my SimpleHashTable class.

The put(self, key) method should determines where the key is placed in the hashtable when a collision occurs (i.e., calculates the next available index position). Linear probing will be used for collision resolution. I am to do the the following steps:
Invoke the get_hash_index(key) to get the original index position.
Use a while loop to get the next available position.
Store the key into the hashtable according to the available index position.

```<code>class SimpleHashTable:
    def __init__(self, size=7):
        self.size = size
        self.slots = [None] * self.size

    def __str__(self):
        return "{}".format(self.slots)

    def get_hash_index(self, key):
        self.key = key
        self.hkey = key % self.size
        return self.hkey

    def new_hash_code(self, index):
        count = 0
        while count < self.size:
            if self.slots[index] == None:
                return index
            index += 1
            count += 1
        return None

    def put(self, key): #issue here
        code = self.get_hash_index(key)
        if self.slots[code] != None:
            code = self.new_hash_code(code)
        self.slots[code] = key

    def __len__(self):
        count = 0
        for item in self.slots:
            if item != None:
                count += 1
        return count
</code>```

Test:

```<code>my_hash_table = SimpleHashTable(13)
my_hash_table.put(12)
my_hash_table.put(24)
my_hash_table.put(36)
my_hash_table.put(48)
my_hash_table.put(31)
my_hash_table.put(77)
my_hash_table.put(43)
</code>```

Output getting:

```<code>***Error***
Traceback (most recent call last):
  File "__tester__.python3", line 87, in <module>
    my_hash_table.put(77)
  File "__tester__.python3", line 26, in put
    code = self.new_hash_code(code)
  File "__tester__.python3", line 17, in new_hash_code
    if self.slots[index] == None:
IndexError: list index out of range
</code>```

答:
The error is in the new_hash_code method. Your current code starts from the current value of index, but increments it without testing it against self.size. You should simply reset it to 0 when reaching the top:

```<code>def new_hash_code(self, index):
    count = 0
    while count < self.size:
        if index == self.size:   # prevent out of range error...
            index = 0
        if self.slots[index] == None:
            return index
        index += 1
        count += 1
    return None
</code>```

Body:
Below is my SimpleHashTable class.

The put(self, key) method should determines where the key is placed in the hashtable when a collision occurs (i.e., calculates the next available index position). Linear probing will be used for collision resolution. I am to do the the following steps:
Invoke the get_hash_index(key) to get the original index position.
Use a while loop to get the next available position.
Store the key into the hashtable according to the available index position.

class SimpleHashTable:
    def __init__(self, size=7):
        self.size = size
        self.slots = [None] * self.size

    def __str__(self):
        return "{}".format(self.slots)

    def get_hash_index(self, key):
        self.key = key
        self.hkey = key % self.size
        return self.hkey

    def new_hash_code(self, index):
        count = 0
        while count < self.size:
            if self.slots[index] == None:
                return index
            index += 1
            count += 1
        return None

    def put(self, key): #issue here
        code = self.get_hash_index(key)
        if self.slots[code] != None:
            code = self.new_hash_code(code)
        self.slots[code] = key

    def __len__(self):
        count = 0
        for item in self.slots:
            if item != None:
                count += 1
        return count

Test:

my_hash_table = SimpleHashTable(13)
my_hash_table.put(12)
my_hash_table.put(24)
my_hash_table.put(36)
my_hash_table.put(48)
my_hash_table.put(31)
my_hash_table.put(77)
my_hash_table.put(43)

Output getting:

***Error***
Traceback (most recent call last):
  File "__tester__.python3", line 87, in <module>
    my_hash_table.put(77)
  File "__tester__.python3", line 26, in put
    code = self.new_hash_code(code)
  File "__tester__.python3", line 17, in new_hash_code
    if self.slots[index] == None:
IndexError: list index out of range

Body:
The error is in the new_hash_code method. Your current code starts from the current value of index, but increments it without testing it against self.size. You should simply reset it to 0 when reaching the top:

def new_hash_code(self, index):
    count = 0
    while count < self.size:
        if index == self.size:   # prevent out of range error...
            index = 0
        if self.slots[index] == None:
            return index
        index += 1
        count += 1
    return None


问:
pip install generates WARNINGS : 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at ...>
I have spent a lot of time searching if someone did already have the same issue but I did not find anything.

For some time, I have warnings each time I want to install a package with pip. The installation works at the end but it takes much more time. The warning consists in a repetition of 5 times the same WARNING :

```<code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b71c50>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b6c690>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b6cb90>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105bb6f10>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105bb67d0>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
</code>```

After these warnings, everything seems to work well, but I would like to remove them to speed up the installations.

If you need more information, please don't hesitate to ask, I am not sure where I should dig to solve that so I don't know what kind of information would be needed.

Thank you very much for your help !

答:
I experienced the same issue. In my case it caused that I copied pip.conf file from different machine.
When I deleted this file and set all variables directly through 'pip config' command the Warnings disappeared.
Hope it helped</p>

Body:
I have spent a lot of time searching if someone did already have the same issue but I did not find anything.

For some time, I have warnings each time I want to install a package with pip. The installation works at the end but it takes much more time. The warning consists in a repetition of 5 times the same WARNING :

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b71c50>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b6c690>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105b6cb90>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105bb6f10>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPConnection object at 0x105bb67d0>: Failed to establish a new connection: [Errno 61] Connection refused')': /simple/mako/

After these warnings, everything seems to work well, but I would like to remove them to speed up the installations.

If you need more information, please don't hesitate to ask, I am not sure where I should dig to solve that so I don't know what kind of information would be needed.

Thank you very much for your help !


问:
Initialize static array for use it in other static variable of other class
```<code>class Assignation {
  private $VVal_1 = 1;
  private $VNam_1 = "One";
  //....Multiple Items
  private $VVal_2000 = 2000; //For Example
  private $VNam_2000 = "Two Thousands"; //For Example
  private static $Hash = array(); //How to initialize???

  private static function Assigning(){
  //This function for to assign the array elements (initialize)
    global $Hash;
    $this->Hash = array(); //to empty Hash variable and not add more data than it should.
    $this->Hash[$this->VVal_1] = $this->VNam_1;
    //....Multiple Items
    $this->Hash[$this->VVal_2000] = $this->VNam_2000;
  }

  public static function GetVal($Nam) {
    $this->Assigning();  //or use self::Assigning(); //I want to avoid this call
    if (array_search($Nam, $this->Hash))
      return array_search($Nam, $this->Hash);
    return -1;//error
  }

  public static function GetNam($Val) {
    $this->Assigning();  //or use self::Assigning(); //I want to avoid this call
    if (array_key_exists($Val, $this->Hash))
      return $this->Hash[$Val];
    return "Error";
  }
}

Class Testing {
  static $OtherVal = Assignation::GetVal("BLABLA"); //for example
  static $OtherNam = Assignation::GetNam(20); //for example
  //Other functions...
}
</code>```

Hi, you can see my script or code php...
I need to initialize the Hash array, this have static word because I need to use it in other static function. And this "other function" need to use it for other static variable...
I need to know how to implement it the right way..

Thanks chep.-.

```<code><?php
echo "pre-Class Assignation<br/>";
class Assignation {
  private $VVal_1 = 1;
  private $VNam_1 = "One";
  private $VVal_2K = 2000;
  private $VNam_2K = "Two Thousands";
  private static $Hash = array();

  private static function Assigning(){
    if(!empty(self::$Hash)) return;
    self::$Hash[$this->VVal_1] = $this->VNam_1;
    self::$Hash[$this->VVal_2K] = $this->VNam_2K;
  }

  public static function GetVal($Nam) {
    self::Assigning();
    if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
    return -1;//error
  }

  public static function GetNam($Val) {
    self::Assigning();
    if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
    return "Error";
  }
}
echo "post-Class Testing<br/>";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid<br/>";
echo Assignation::GetNam(20);
echo "post-Class Sample<br/>";
//Testing::MyPrint();
?>
</code>```

This code is not running, somebody help me testing the code...
result:

```<code>pre-Class Assignation
post-Class Assignation
post-Class Testing
</code>```

that mean:
"    echo Assignation::GetVal("BLABLA");"
have error...

答:
In Assigning(), try using self::$Hash rather than $this->Hash and remove the global $Hash. Same applies for calling Assigning(): self::Assigning() as your comments suggest.

$this references the current object, so you must use self:: for all static functions and member data when inside the class.

Also, if this is your real code and not just a sample, you may want to check whether you have already done initialization, otherwise you will be doing it for every call to GetVal() and GetNam(). You could do this by adding something like if(!empty(self::$Hash)) return at the beginning of Assigning()

EDIT

```<code>private static function Assigning() {
    if(!empty(self::$Hash)) return; // already populated
    self::$Hash = array();
    self::$Hash[$this->VVal_1] = $this->VNam_1;
    //....Multiple Items
    self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
</code>```

Body:
class Assignation {
  private $VVal_1 = 1;
  private $VNam_1 = "One";
  //....Multiple Items
  private $VVal_2000 = 2000; //For Example
  private $VNam_2000 = "Two Thousands"; //For Example
  private static $Hash = array(); //How to initialize???

  private static function Assigning(){
  //This function for to assign the array elements (initialize)
    global $Hash;
    $this->Hash = array(); //to empty Hash variable and not add more data than it should.
    $this->Hash[$this->VVal_1] = $this->VNam_1;
    //....Multiple Items
    $this->Hash[$this->VVal_2000] = $this->VNam_2000;
  }

  public static function GetVal($Nam) {
    $this->Assigning();  //or use self::Assigning(); //I want to avoid this call
    if (array_search($Nam, $this->Hash))
      return array_search($Nam, $this->Hash);
    return -1;//error
  }

  public static function GetNam($Val) {
    $this->Assigning();  //or use self::Assigning(); //I want to avoid this call
    if (array_key_exists($Val, $this->Hash))
      return $this->Hash[$Val];
    return "Error";
  }
}

Class Testing {
  static $OtherVal = Assignation::GetVal("BLABLA"); //for example
  static $OtherNam = Assignation::GetNam(20); //for example
  //Other functions...
}

Hi, you can see my script or code php...
I need to initialize the Hash array, this have static word because I need to use it in other static function. And this "other function" need to use it for other static variable...
I need to know how to implement it the right way..

Thanks chep.-.

<?php
echo "pre-Class Assignation
";
class Assignation {
  private $VVal_1 = 1;
  private $VNam_1 = "One";
  private $VVal_2K = 2000;
  private $VNam_2K = "Two Thousands";
  private static $Hash = array();

  private static function Assigning(){
    if(!empty(self::$Hash)) return;
    self::$Hash[$this->VVal_1] = $this->VNam_1;
    self::$Hash[$this->VVal_2K] = $this->VNam_2K;
  }

  public static function GetVal($Nam) {
    self::Assigning();
    if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
    return -1;//error
  }

  public static function GetNam($Val) {
    self::Assigning();
    if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
    return "Error";
  }
}
echo "post-Class Testing
";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid
";
echo Assignation::GetNam(20);
echo "post-Class Sample
";
//Testing::MyPrint();
?>

This code is not running, somebody help me testing the code...
result:

pre-Class Assignation
post-Class Assignation
post-Class Testing

that mean:
"    echo Assignation::GetVal("BLABLA");"
have error...

Body:
In Assigning(), try using self::$Hash rather than $this->Hash and remove the global $Hash. Same applies for calling Assigning(): self::Assigning() as your comments suggest.

$this references the current object, so you must use self:: for all static functions and member data when inside the class.

Also, if this is your real code and not just a sample, you may want to check whether you have already done initialization, otherwise you will be doing it for every call to GetVal() and GetNam(). You could do this by adding something like if(!empty(self::$Hash)) return at the beginning of Assigning()

EDIT

private static function Assigning() {
    if(!empty(self::$Hash)) return; // already populated
    self::$Hash = array();
    self::$Hash[$this->VVal_1] = $this->VNam_1;
    //....Multiple Items
    self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}


问:
Asp.Net Core Swagger Sort Tags Alphabetically
I'm using asp.net core 6 & Swashbuckle.AspNetCore

and I'm using SwaggerAnnotations in my actions

But my Tags Groups are not ordered

Here's my Swagger UI page

My Program.cs :

```<code>builder.Services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new OpenApiInfo {
    Title = "Api", Version = "v1"
  });
  c.EnableAnnotations();
});

 ....

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c => {
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
  c.InjectStylesheet("/swagger-ui/css/custom.css");
});

</code>```

答:
I got the solution

I created this Custom DocumentFiler thats sorts the Tags

```<code>public class OrderTagsDocumentFilter: IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Tags = swaggerDoc.Tags
             .OrderBy(x => x.Name).ToList();
    }
}

</code>```

and added it to Program.cs

```<code>
services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new OpenApiInfo {
    Title = "Shoppy.WebApi", Version = "v1"
  });
  c.EnableAnnotations();

  c.DocumentFilter<OrderTagsDocumentFilter>();
});

</code>```

Body:
I'm using asp.net core 6 & Swashbuckle.AspNetCore

and I'm using SwaggerAnnotations in my actions

But my Tags Groups are not ordered

Here's my Swagger UI page

My Program.cs :

builder.Services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new OpenApiInfo {
    Title = "Api", Version = "v1"
  });
  c.EnableAnnotations();
});

 ....

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c => {
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
  c.InjectStylesheet("/swagger-ui/css/custom.css");
});

Body:
I got the solution

I created this Custom DocumentFiler thats sorts the Tags

public class OrderTagsDocumentFilter: IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Tags = swaggerDoc.Tags
             .OrderBy(x => x.Name).ToList();
    }
}

and added it to Program.cs

services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new OpenApiInfo {
    Title = "Shoppy.WebApi", Version = "v1"
  });
  c.EnableAnnotations();

  c.DocumentFilter<OrderTagsDocumentFilter>();
});


问:
Asp.Net Core 6 Scoped Filter inject UserManager
I'm working on linking Twilio Verify into an Asp.Net Core web site.  I'm pretty sure I have to figure out how to access UserManager in the filter (constructor).  But, I don't know how to access it.

My VerifyFilter:

```<code>public class VerifyFilter : IAsyncResourceFilter
{
   private readonly UserManager<ApplicationUser> _manager;

   public VerifyFilter(UserManager<ApplicationUser> manager)
   { _manager = manager; }

   public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
   { // cut just to make listing a bit shorter }
}
</code>```

My program.cs file currently looks like this:

```<code>builder.Services.AddScoped<VerifyFilter>();
</code>```

What I don't know is how I get the UserManager so I can pass it in.

I have another scoped right above it and I had to do this to get Verification to work.

```<code>Configuration.Twilio twilio = new Configuration.Twilio();
builder.Services.AddScoped<IVerification>(t => new Verification(twilio));
</code>```

So I'm sure it's just a matter of figuring out how to get UserManager to pass in as a constructor, but with MinimalAPI and .Net Core 6.0, I don't know where it is at.

My entire program.cs file:

```<code>using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using test4.Data;
using test4.Filters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<IdentityUser>(
        options =>
        {
           // These will get updated to production versions later.
           options.SignIn.RequireConfirmedAccount = true;
           options.Password.RequiredLength = 1;
        })
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddRazorPages();

builder.Services.AddScoped<VerifyFilter>();

builder.Services.AddControllers(op =>
{
   op.Filters.Add<VerifyFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   app.UseMigrationsEndPoint();
}
else
{
   app.UseExceptionHandler("/Error");
   // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
   app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();
</code>```

Any suggestions?

Thanks,
Nick

答:
You could try to register the filter via the following code:</p>
```<code>//register the Identity service

//register the custom filters.
builder.Services.AddControllers(op =>
{
    op.Filters.Add<VerifyFilter>();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
</code>```

Body:
I'm working on linking Twilio Verify into an Asp.Net Core web site.  I'm pretty sure I have to figure out how to access UserManager in the filter (constructor).  But, I don't know how to access it.

My VerifyFilter:

public class VerifyFilter : IAsyncResourceFilter
{
   private readonly UserManager<ApplicationUser> _manager;

   public VerifyFilter(UserManager<ApplicationUser> manager)
   { _manager = manager; }

   public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
   { // cut just to make listing a bit shorter }
}

My program.cs file currently looks like this:

builder.Services.AddScoped<VerifyFilter>();

What I don't know is how I get the UserManager so I can pass it in.

I have another scoped right above it and I had to do this to get Verification to work.

Configuration.Twilio twilio = new Configuration.Twilio();
builder.Services.AddScoped<IVerification>(t => new Verification(twilio));

So I'm sure it's just a matter of figuring out how to get UserManager to pass in as a constructor, but with MinimalAPI and .Net Core 6.0, I don't know where it is at.

My entire program.cs file:

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using test4.Data;
using test4.Filters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<IdentityUser>(
        options =>
        {
           // These will get updated to production versions later.
           options.SignIn.RequireConfirmedAccount = true;
           options.Password.RequiredLength = 1;
        })
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddRazorPages();

builder.Services.AddScoped<VerifyFilter>();

builder.Services.AddControllers(op =>
{
   op.Filters.Add<VerifyFilter>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   app.UseMigrationsEndPoint();
}
else
{
   app.UseExceptionHandler("/Error");
   // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
   app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

Any suggestions?

Thanks,
Nick

Body:
You could try to register the filter via the following code:

//register the Identity service

//register the custom filters.
builder.Services.AddControllers(op =>
{
    op.Filters.Add<VerifyFilter>();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


问:
Canvas element not extending fullpage even when set to scrollHeight?
I'm working on a browser extension (Chrome / Edge) that injects a Canvas onto any given page, and allows me to draw a rectangle.

The Canvas element SHOULD extend the full scrollHeight of any given page, and it ALMOST does. It just seems to stop just before the footer (as in pic)

How can I fix this so that the Canvas is TRULY FULL PAGE?

Relevant CSS (via JavaScript) and JavaScript below

{
    document.width = '100%';
    document.height = '100%';
    document.body.style.padding = 0;
    document.body.style.margin = 0;
    document.body.width = '100%';
    document.body.height = '100%';
    document.body.style.cursor = "crosshair";

    mainCanvas.style.position = 'absolute';
    mainCanvas.style.top = 0;
    mainCanvas.style.left = 0;
    mainCanvas.width = document.body.scrollWidth;
    mainCanvas.height = document.body.scrollHeight;  // This should be fullpage?
}
```

答:
I think by adding pixel unit using string literal may help.</p>
```<code>{
    mainCanvas.style.width = `${document.body.scrollWidth}px`;
    mainCanvas.style.height = `${document.body.scrollHeight}px`;
}
</code>```

Body:
I think by adding pixel unit using string literal may help.

{
    mainCanvas.style.width = `${document.body.scrollWidth}px`;
    mainCanvas.style.height = `${document.body.scrollHeight}px`;
}


问:
How do you properly stop execution of an express.js endpoint?
I have a middleware error handler that is working great but next(err) and return and return next(err) seems to not stop execution when dealing with promises. What is the proper way to stop execution of my code when an error is found?

For reference: err is a standard Error class in this case.

I don't think you need the code in userProvider.fetchFriends to help with this but if that's wrong please let me know.

```<code>  const uid = req.query.steamUserId;

  //Use the userProvider to get steam friend data
  const friendData = await userProvider.fetchFriends(uid)
  .catch(err => {
    return next(err); //Does not stop execution. Why? just next(err) doesn't either.
  });

  //Putting this after every catch works but seems very stupid. How do I avoid this?
  if(res.writableEnded)
    return;

  ...Other code that runs but causes errors
}
</code>```

答:
The issue was that I was mixing async/await with .then/.catch. Needed to use try/catch.

ty @jonsharpe

```<code>export const getSteamFriends = async (req, res, next) => {
  try{
    const uid = req.query.steamUserId;

    //Use the userProvider to get steam friend data
    const friendData = await userProvider.fetchFriends(uid);

    //more code in the middle
  } catch(e) {
    return next(e);
  }
};
</code>```

Body:
I have a middleware error handler that is working great but next(err) and return and return next(err) seems to not stop execution when dealing with promises. What is the proper way to stop execution of my code when an error is found?

For reference: err is a standard Error class in this case.

I don't think you need the code in userProvider.fetchFriends to help with this but if that's wrong please let me know.

  const uid = req.query.steamUserId;

  //Use the userProvider to get steam friend data
  const friendData = await userProvider.fetchFriends(uid)
  .catch(err => {
    return next(err); //Does not stop execution. Why? just next(err) doesn't either.
  });

  //Putting this after every catch works but seems very stupid. How do I avoid this?
  if(res.writableEnded)
    return;

  ...Other code that runs but causes errors
}

Body:
The issue was that I was mixing async/await with .then/.catch. Needed to use try/catch.

ty @jonsharpe

export const getSteamFriends = async (req, res, next) => {
  try{
    const uid = req.query.steamUserId;

    //Use the userProvider to get steam friend data
    const friendData = await userProvider.fetchFriends(uid);

    //more code in the middle
  } catch(e) {
    return next(e);
  }
};


问:
Angular + Git - How to Include a file from a package exists inside node_modules
I have ng-payment-card package and I've made some modifications in a file inside the package, and I need to include this file in the git commit in order to not reset it every time I make npm install.

I tried to write in .gitignore like this:

```<code>!/node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js
</code>```

but the same, the file hasn't been added to the commit.

答:
Even if the file is currently ignored, you can force adding it:

```<code>git add --force  node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js
</code>```

That way, everything else remains ignored, while your file becomes tracked.

Body:
I have ng-payment-card package and I've made some modifications in a file inside the package, and I need to include this file in the git commit in order to not reset it every time I make npm install.

I tried to write in .gitignore like this:

!/node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js

but the same, the file hasn't been added to the commit.

Body:
Even if the file is currently ignored, you can force adding it:

git add --force  node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js

That way, everything else remains ignored, while your file becomes tracked.


问:
Install npcap silently without npcap OEM Edition
Is there a way to silently install the npcap driver without the OEM Edition?</p>

答: you can use version 0.96,the version is last allow free silent installation</p>


问:
How to read MKV bytes as video?
I am receiving fragment of MKV video in bytes. I need to take 1st frame of it for later processing without saving video in disk. For similar problem with image I use OpenCV or PIL and everything works fine, however, I am not able to do the same with video data. Any tips how to read video from bytes to memory object that I could use for later processing with OpenCV or some other library?</p>

答:
Mark Setchell got it right; though - in 2022 - you don't have to drop down all the way to get_reader anymore to do this.

Setup:

Create a test video:

```<code>ffmpeg -f lavfi -i testsrc -t 5 testsrc.mkv
</code>```

create a MKV bytes string

from pathlib import Path

mkv_bytes = Path("testsrc.mkv").read_bytes()

```
<p><strong>Read the first frame:</strong></p>
<p><em>ImageIO<2.15.0</em></p>
<pre class="lang-py prettyprint-override"><code>import imageio as iio

req = iio.core.Request(mkv_bytes, "r")

# note: this is a bit of a hack, see
# https://github.com/imageio/imageio/issues/686
req._extension = ".mkv"

first_frame = iio.imread(req)

</code>```

ImageIO>2.15.0 (releases this week - W6 2022)

import imageio as iio

first_frame = iio.v3.imread(mkv_bytes, format_hint=".mkv")
```

Title: How to read MKV bytes as video?

Body:
Mark Setchell got it right; though - in 2022 - you don't have to drop down all the way to get_reader anymore to do this.

Setup:

Create a test video:

ffmpeg -f lavfi -i testsrc -t 5 testsrc.mkv

create a MKV bytes string

from pathlib import Path

mkv_bytes = Path("testsrc.mkv").read_bytes()

Read the first frame:

ImageIO<2.15.0

import imageio as iio

req = iio.core.Request(mkv_bytes, "r")

# note: this is a bit of a hack, see
# https://github.com/imageio/imageio/issues/686
req._extension = ".mkv"

first_frame = iio.imread(req)

ImageIO>2.15.0 (releases this week - W6 2022)

import imageio as iio

first_frame = iio.v3.imread(mkv_bytes, format_hint=".mkv")


问:
Circular dependency best practice
What is the best way to solve this.

I have projects the following projects:

Model

Logic (references model)

Synchronization (references both model and logic)

Web (references all projects)

All runs fine, the web project fires the synchronization project, which uses model and logic, and does it's work.
But now, some times, the logic project also has to call a method in the synchronization project, but this reference cannot be added because of the circular dependency that is not allowed.

What would be the easiest way to make this whole thing work?

A bit more on the synchronization project.
Synchronization works on it's own. It runs processes that bring data from an external database to the database in my application. It does this by creating objects based on the model and saves them by using the logic.
This works fine, and gives us the ability to simply create another synchronization project/assembly that could do the same thing, but targeted at a completely different type of database.

The problem is, that we now, from time to time, want to call a method in the sychronization project to update some data in the other direction / to the external database.

答:
Why not move the method that Logic needs to the Logic project?  Synchronization can then call the method in Logic, since it references Logic.

Of course, I'm assuming there isn't a whole bunch of other code in Synchronization that this method requires.  If there is, then perhaps it's time for a fifth project, perhaps called something like "Utility" or "Common".

There's also the possibility that Synchronization and Logic both need similar methods but not quite the same, in which case you make two separate methods, one in each project.

Title: Circular dependency best practice


问:
How to filter a nested dict by the key of the nested element?
I have a nested dictionary of source words, target words, and their frequency counts. It looks like this:
src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

I am trying to filter the dictionary so that only key-value pairs that are prepositions (including multi-word prepositions) remain. To that end, I've written the following:

```<code>tgt_preps = set(["devant", "pour", "sur", "à"]) #set of initial target prepositions

src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

new_tgt_preps = [] #list of new target prepositions

for src, d in src_tgt_dict.items(): #loop into the dictionary
    for tgt, count in d.items(): #loop into the nested dictionary
        check_prep = []
        if "-" in tgt: #check to see if hyphen occurs in the target word (this is to capture multi-word prepositions that are not in the original preposition set)
            check_prep.append(tgt[0:(tgt.index("-"))]) #if there's a hyphen, append the preceding word to the check_prep list
            for t in check_prep:
                if t in tgt_preps: # check to see if the token preceding the hyphen is a preposition
                    new_tgt_preps.append(tgt) #if yes, append the multi-word preposition to the list of new target prepositions

tgt_preps.update(new_tgt_preps) # update the set of prepositions to include the multi-word prepositions

temp_2_src_tgt_dict = {} # create new dict for filtering
for src, d in src_tgt_dict.items(): # loop into the dictionary
    for tgt, count in d.items(): # loop into the nested dictionary
        if tgt in tgt_preps: # if the target is in the set of target prepositions
            temp_2_src_tgt_dict[tgt] = count # add to the new dict with the tgt as the key and the count as the value
</code>```

When I print the new dict, I get the following:

{'devant': 4, 'pour': 7, 'sur': 2, 'à-côté-de': 5}

And it totally makes sense why I get that, because that's what I told the machine to do. But that's not my intention!

What I want is:

{"in-front-of:{"devant":4}, "for":{"pour":7}, "on":{"sur":2}, {"next-to":{"à-côté-de":5}}

I've tried to instantiate the nested dictionary by writing:

temp_2_src_tgt_dict[tgt][src] = count

but that throws up a Key Error.

I've also tried:

```<code>new_tgt_dict = {}
for i in src_tgt_dict.items():
    for j in tgt_preps:
        if j in list(i[1].keys())[0][:len(j)]:
            new_tgt_dict.update({i[0]: i[1]})
</code>```

But that outputs {'in-front-of': {'devant': 4}, 'next-to': {'à-côté-de': 5}, 'for': {'pour': 7}, 'on': {'sur': 2, 'panda-et': 2}}, which is correct in format, but the value 'panda-et' should not be included because it does not occur in tgt_preps when updated with new_tgt_preps.

Can anyone provide any suggestions or advice? Thank you in advance for your help.

答:
Maybe something like this:

from collections import defaultdict

new_tgt_dict = defaultdict(dict)
for k, v in src_tgt_dict.items():
  for k1, v1 in v.items():
    k_temp = k1
    if "-" in k1:
      k_temp = k1[0:(k1.index("-"))]
    if k_temp in tgt_preps:
      new_tgt_dict[k].update({k1: v1})
print(dict(new_tgt_dict))
```
```{'in-front-of': {'devant': 4}, 'next-to': {'à-côté-de': 5}, 'for': {'pour': 7}, 'on': {'sur': 2}}
```

Body:
I have a nested dictionary of source words, target words, and their frequency counts. It looks like this:
src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

I am trying to filter the dictionary so that only key-value pairs that are prepositions (including multi-word prepositions) remain. To that end, I've written the following:

tgt_preps = set(["devant", "pour", "sur", "à"]) #set of initial target prepositions

src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

new_tgt_preps = [] #list of new target prepositions

for src, d in src_tgt_dict.items(): #loop into the dictionary
    for tgt, count in d.items(): #loop into the nested dictionary
        check_prep = []
        if "-" in tgt: #check to see if hyphen occurs in the target word (this is to capture multi-word prepositions that are not in the original preposition set)
            check_prep.append(tgt[0:(tgt.index("-"))]) #if there's a hyphen, append the preceding word to the check_prep list
            for t in check_prep:
                if t in tgt_preps: # check to see if the token preceding the hyphen is a preposition
                    new_tgt_preps.append(tgt) #if yes, append the multi-word preposition to the list of new target prepositions

tgt_preps.update(new_tgt_preps) # update the set of prepositions to include the multi-word prepositions

temp_2_src_tgt_dict = {} # create new dict for filtering
for src, d in src_tgt_dict.items(): # loop into the dictionary
    for tgt, count in d.items(): # loop into the nested dictionary
        if tgt in tgt_preps: # if the target is in the set of target prepositions
            temp_2_src_tgt_dict[tgt] = count # add to the new dict with the tgt as the key and the count as the value

When I print the new dict, I get the following:

{'devant': 4, 'pour': 7, 'sur': 2, 'à-côté-de': 5}

And it totally makes sense why I get that, because that's what I told the machine to do. But that's not my intention!

What I want is:

{"in-front-of:{"devant":4}, "for":{"pour":7}, "on":{"sur":2}, {"next-to":{"à-côté-de":5}}

I've tried to instantiate the nested dictionary by writing:

temp_2_src_tgt_dict[tgt][src] = count

but that throws up a Key Error.

I've also tried:

new_tgt_dict = {}
for i in src_tgt_dict.items():
    for j in tgt_preps:
        if j in list(i[1].keys())[0][:len(j)]:
            new_tgt_dict.update({i[0]: i[1]})

But that outputs {'in-front-of': {'devant': 4}, 'next-to': {'à-côté-de': 5}, 'for': {'pour': 7}, 'on': {'sur': 2, 'panda-et': 2}}, which is correct in format, but the value 'panda-et' should not be included because it does not occur in tgt_preps when updated with new_tgt_preps.

Can anyone provide any suggestions or advice? Thank you in advance for your help.

Body:
Maybe something like this:

from collections import defaultdict

new_tgt_dict = defaultdict(dict)
for k, v in src_tgt_dict.items():
  for k1, v1 in v.items():
    k_temp = k1
    if "-" in k1:
      k_temp = k1[0:(k1.index("-"))]
    if k_temp in tgt_preps:
      new_tgt_dict[k].update({k1: v1})
print(dict(new_tgt_dict))

{'in-front-of': {'devant': 4}, 'next-to': {'à-côté-de': 5}, 'for': {'pour': 7}, 'on': {'sur': 2}}


问:
Variable export without function call
I am trying to export a variable that gets updated from state. The challenge I have is that I cannot modify how the variable is being exported, as it is being used in way too many files at the moment.

Maybe can call the function from another file to execute?

```<code>import { useAppDispatch, useAppSelector } from "../redux/hooks";

export const Content = () => {
  const { store } = useAppSelector((state) => state.StoreReducer);
  return store;
};

export const currency =
  Content() && Content()?.currency ? Content()?.currency : "USD";

export default {
  CURRENCY: currency}
</code>```

React Error:

```<code>Invalid hook call. Hooks can only be called inside of the body of a function component.
</code>```

答:
The error message is clear, react hooks can only be called inside of the body of a function component. But you are calling the Content function in a module scope. You can get the whole state by using store.getState().

import store from '<somewhere>/store';

export const Content = () => {
  const { store } = store.getState().StoreReducer;
  return store;
};

export const currency =
  Content() && Content()?.currency ? Content()?.currency : "USD";

export default { CURRENCY: currency }
```

Title: Variable export without function call

Body:
I am trying to export a variable that gets updated from state. The challenge I have is that I cannot modify how the variable is being exported, as it is being used in way too many files at the moment.

Maybe can call the function from another file to execute?

import { useAppDispatch, useAppSelector } from "../redux/hooks";

export const Content = () => {
  const { store } = useAppSelector((state) => state.StoreReducer);
  return store;
};

export const currency =
  Content() && Content()?.currency ? Content()?.currency : "USD";

export default {
  CURRENCY: currency}

React Error:

Invalid hook call. Hooks can only be called inside of the body of a function component.


问:
VS Code Remote - Can't run 'code' command in WSL Ubuntu 18 or WSL 2 Ubuntu 20 - wrong path
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

```<code>$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found
</code>```

When I run the following, it installs the VS Code Server and the command works as expected:

```<code>$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .
</code>```

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

```<code>barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code
</code>```

Can anyone help please?

答:
Keep it simple S*upid method:

Download & install vscode again. link for windows

(Ubuntu example) apt update && yes | apt upgrade

Try to launch code from wsl

You should see something like:

```<code>Updating VS Code Server to version 5554b12acf27056905806867f251c859323ff7e9
Removing previous installation...
Installing VS Code Server for x64 (5554b12acf27056905806867f251c859323ff7e9)
</code>```

Body:
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found

When I run the following, it installs the VS Code Server and the command works as expected:

$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code

Can anyone help please?

Body:
Keep it simple S*upid method:

Download & install vscode again. link for windows

(Ubuntu example) apt update && yes | apt upgrade

Try to launch code from wsl

You should see something like:

Updating VS Code Server to version 5554b12acf27056905806867f251c859323ff7e9
Removing previous installation...
Installing VS Code Server for x64 (5554b12acf27056905806867f251c859323ff7e9)


问:
Cannot compile SchedulerBinding.instance.addPostFrameCallback and executeAfterBuild() async not working either
In my app the user is presented with a puzzle, drawn by a re-implementation of Flutter's CustomerPainter class and accepting moves made by tapping on the Canvas. The Canvas is continually updated and re-drawn to show the moves. When the user makes the last move and completes a correct solution, the app should tell the user so. The app is using Flutter's AlertDialog to issue such messages to the user.

The problem is that the app is deep in the paint() method of CustomPainter when a solution situation is detected. Any attempt to issue a message at that point crashes the app. The message to the user does appear, but by that time the app has crashed. The error messages are either:

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:

       setState() or markNeedsBuild() called during build.

or

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:

       Build scheduled during frame.

These messages are followed by comprehensive advice as to what has happened and what to do. There are also several suggestions on Stack Overflow, but I cannot get any of them to work.

If I write SchedulerBinding.instance.addPostFrameCallback in my widget-build it fails to compile because it wants several parts from BindingBase. SchedulerBinding is a mixin. If I try to mixin BindingBase to my Widget, compilation fails again because BindingBase is a class, with a constructor, not a mixin.

If I go the async way, using Future executeAfterBuild(), the app compiles but crashes again, apparently because the async function executes straight away (as is normal) and is not scheduled after the widget-build, as suggested in some of the Stack Overflow posts. The app is definitely not in setState() when it crashes, so maybe marksNeedsBuild() is triggering the crash somehow.

I am using Flutter 2.8.2 and Dart 2.15.1, plus sound null safety. Has Flutter's widget-scheduling policy changed? The Stack Overflow posts I refer to are up to 3 years old.

答:
have you tried putting setState in :</p>
```<code>WidgetsBinding.instance?.addPostFrameCallback((_) {setState((){});})
</code>```

Body:
have you tried putting setState in :

WidgetsBinding.instance?.addPostFrameCallback((_) {setState((){});})


问:
Why horizontal scroll bar not working on listview qml?
I have used almost all solutions on Stackoverflow to make it work. But none of them worked?

What changes can be done so that horizontal scroll bar work?

I used the qt docs also but still not working. Please give some examples. I just need horizontal scroll in listview. Or other view also.

main.qml

Rectangle {

    id: frame

    width: 300
    height: 300
    anchors.top: meaning.bottom

     ListView {

        width: 300
        height: 300
        anchors.centerIn: parent
        id: myList
        model: myModel
        highlight: highlightBar
        clip: true

        snapMode: ListView.SnapToItem

        headerPositioning: ListView.OverlayHeader

        header: Rectangle {
            id: headerItem
            width: myList.width
            height: 30
            z: 2

            color: "gray"

            Text {
                text: "Simple Text List"
                color: "white"
            }
        }

        delegate: Item {
            id: delegateItem
            width: 400
            height: 20
            Text {
                text: name
            }

            MouseArea {
                id: mArea
                anchors.fill: parent
                onClicked: {
                    myList.currentIndex = index
                }
            }
        }
    }

    Component {
        id: highlightBar
        Rectangle {
            width: parent.width
            height: 20
            color: "#FFFF88"
        }
    }

    ListModel {
        id: myModel
    }

        ScrollBar {
        id: vbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Vertical
        size: frame.height / content.height
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

    ScrollBar {
        id: hbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Horizontal
        size: frame.width / content.width
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }
}
```

Please make change to this so horizontal scroll work.
Thanks.

答:
QML ListView is a Flickable subclass.

To show scrollbars in a Flickable you need to provide contentWidth and/or contentHeight and the desired flickableDirection.

Here is an example of a ListView that scrolls both ways:

import QtQuick
import QtQuick.Controls
import QtQuick.Window

Window {
  visible: true
  width: 640
  height: 480
  title: qsTr("Hello World")

  ListView {
    anchors.fill: parent
    ScrollBar.vertical: ScrollBar {}
    ScrollBar.horizontal: ScrollBar {}
    flickableDirection: Flickable.HorizontalAndVerticalFlick
    contentWidth: 1000
    model: ["lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "ut", "enim", "ad", "minim", "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "ut", "aliquip", "ex", "ea", "commodo", "consequat", "duis", "aute", "irure", "dolor", "in", "reprehenderit", "in", "voluptate", "velit", "esse", "cillum", "dolore", "eu", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident", "sunt", "in", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum"]
    delegate: Label {
      width: ListView.view.width
      horizontalAlignment: Text.AlignHCenter
      text: modelData
    }
  }
}
```

Body:
I have used almost all solutions on Stackoverflow to make it work. But none of them worked?

What changes can be done so that horizontal scroll bar work?

I used the qt docs also but still not working. Please give some examples. I just need horizontal scroll in listview. Or other view also.

main.qml

Rectangle {

    id: frame

    width: 300
    height: 300
    anchors.top: meaning.bottom

     ListView {

        width: 300
        height: 300
        anchors.centerIn: parent
        id: myList
        model: myModel
        highlight: highlightBar
        clip: true

        snapMode: ListView.SnapToItem

        headerPositioning: ListView.OverlayHeader

        header: Rectangle {
            id: headerItem
            width: myList.width
            height: 30
            z: 2

            color: "gray"

            Text {
                text: "Simple Text List"
                color: "white"
            }
        }

        delegate: Item {
            id: delegateItem
            width: 400
            height: 20
            Text {
                text: name
            }

            MouseArea {
                id: mArea
                anchors.fill: parent
                onClicked: {
                    myList.currentIndex = index
                }
            }
        }
    }

    Component {
        id: highlightBar
        Rectangle {
            width: parent.width
            height: 20
            color: "#FFFF88"
        }
    }

    ListModel {
        id: myModel
    }

        ScrollBar {
        id: vbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Vertical
        size: frame.height / content.height
        anchors.top: parent.top
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

    ScrollBar {
        id: hbar
        hoverEnabled: true
        active: hovered || pressed
        orientation: Qt.Horizontal
        size: frame.width / content.width
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }
}

Please make change to this so horizontal scroll work.
Thanks.


问:
Is there downside replacing all remember(value) with remember { derivedStateOf { value } }?
As in https://developer.android.com/jetpack/compose/side-effects, we have derivedStateOf which helps prevent unnecessary Recomposition.

With that, it makes me think, should we always use derivedStateOf instead of remember(value) as below?

```<code>// Instead of using
remember(value1) { ... }

// Use
remember { derivedStateOf {value1} }
</code>```

Doing so will also ensure we don't recompose the function that contains the mutableState, but just all the composable functions using that mutableState.

Is there any downside of using derivedStateOf as opposed to remember(value)?

答:
derivedStateOf is for observing a change or or a property change in State.

if value1 in both cases is a class that is not State derivedStateOf won't update

```<code>@Composable
private fun DerivedStateOfExample() {

    var numberOfItems by remember {
        mutableStateOf(0)
    }

    val count = numberOfItems

    val rememberedCount = remember(count) {
        count
    }

    val derivedCountWithoutState by remember {
        derivedStateOf {
            count
        }
    }

    val derivedCountWithState by remember {
        derivedStateOf {
            numberOfItems
        }
    }

    // Use derivedStateOf when a certain state is calculated or derived from other state objects.
    // Using this function guarantees that the calculation will only occur whenever one
    // of the states used in the calculation changes.
    val derivedStateMax by remember {
        derivedStateOf {
            numberOfItems > 5
        }
    }

    val newMax = remember(count > 5) {
        count
    }

    val derivedStateMin by remember {
        derivedStateOf {
            numberOfItems > 0
        }
    }

    Column(modifier = Modifier.padding(horizontal = 8.dp)) {

        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(
                text = "Items: $numberOfItems\n" +
                        "derivedCountWithoutState: $derivedCountWithoutState\n" +
                        "derivedCountWithState: $derivedCountWithState\n" +
                        "newMax:$newMax\n" +
                        "rememberedCount:$rememberedCount, count: $count",
                modifier = Modifier.weight(1f)
            )
            IconButton(onClick = { numberOfItems++ }) {
                Icon(imageVector = Icons.Default.Add, contentDescription = "add")
            }
            Spacer(modifier = Modifier.width(4.dp))
            IconButton(onClick = { if (derivedStateMin) numberOfItems-- }) {
                Icon(imageVector = Icons.Default.Remove, contentDescription = "remove")
            }
        }

        if (derivedStateMax) {
            Text("Can't be more than 5 items", color = Color(0xffE53935))
        }
    }
}
</code>```

derivedCountWithState won't update because it doesn't observe a state. Same goes for derivedStateMax when the value was not derived from numberOfItems but count > 5

Also newMax is updated when when remember(count > 5) turns from false to true. This is where derivedStateOf comes handy, you can check change in each update of State with a condition.

Body:
As in https://developer.android.com/jetpack/compose/side-effects, we have derivedStateOf which helps prevent unnecessary Recomposition.

With that, it makes me think, should we always use derivedStateOf instead of remember(value) as below?

// Instead of using
remember(value1) { ... }

// Use
remember { derivedStateOf {value1} }

Doing so will also ensure we don't recompose the function that contains the mutableState, but just all the composable functions using that mutableState.

Is there any downside of using derivedStateOf as opposed to remember(value)?

Body:
derivedStateOf is for observing a change or or a property change in State.

if value1 in both cases is a class that is not State derivedStateOf won't update

@Composable
private fun DerivedStateOfExample() {

    var numberOfItems by remember {
        mutableStateOf(0)
    }

    val count = numberOfItems

    val rememberedCount = remember(count) {
        count
    }

    val derivedCountWithoutState by remember {
        derivedStateOf {
            count
        }
    }

    val derivedCountWithState by remember {
        derivedStateOf {
            numberOfItems
        }
    }

    // Use derivedStateOf when a certain state is calculated or derived from other state objects.
    // Using this function guarantees that the calculation will only occur whenever one
    // of the states used in the calculation changes.
    val derivedStateMax by remember {
        derivedStateOf {
            numberOfItems > 5
        }
    }

    val newMax = remember(count > 5) {
        count
    }

    val derivedStateMin by remember {
        derivedStateOf {
            numberOfItems > 0
        }
    }

    Column(modifier = Modifier.padding(horizontal = 8.dp)) {

        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(
                text = "Items: $numberOfItems\n" +
                        "derivedCountWithoutState: $derivedCountWithoutState\n" +
                        "derivedCountWithState: $derivedCountWithState\n" +
                        "newMax:$newMax\n" +
                        "rememberedCount:$rememberedCount, count: $count",
                modifier = Modifier.weight(1f)
            )
            IconButton(onClick = { numberOfItems++ }) {
                Icon(imageVector = Icons.Default.Add, contentDescription = "add")
            }
            Spacer(modifier = Modifier.width(4.dp))
            IconButton(onClick = { if (derivedStateMin) numberOfItems-- }) {
                Icon(imageVector = Icons.Default.Remove, contentDescription = "remove")
            }
        }

        if (derivedStateMax) {
            Text("Can't be more than 5 items", color = Color(0xffE53935))
        }
    }
}

derivedCountWithState won't update because it doesn't observe a state. Same goes for derivedStateMax when the value was not derived from numberOfItems but count > 5

Also newMax is updated when when remember(count > 5) turns from false to true. This is where derivedStateOf comes handy, you can check change in each update of State with a condition.


问:
running a batch file from C#
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }
</code>```

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks

答:
How to run console application from Windows Service?

You will want to the set the p.StartInfo with FileName="cmd.exe" and Arguments="c:\\thebatfile.bat" i believe

Title: running a batch file from C#

Body:
UPDATE
** STILL LOOKING FOR A CORRECT ANSWER **
I have the following code in my windows service and I want to run a batch file. I want the command prompt window up so I can see progress

here is my code but my batch file code doesnt work

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;

    namespace Watcher
    {
        public partial class Watcher : ServiceBase
        {
            public Watcher()
            {
                InitializeComponent();
            FolderWatcher.Created += FolderWatcher_Created;
            FolderWatcher.Deleted += FolderWatcher_Deleted;
            FolderWatcher.Renamed += FolderWatcher_Renamed;
            }

            protected override void OnStart(string[] args)
            {

                          // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "C:\\myFile.bat";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            }

            protected override void OnStop()
            {
            }

            private void FolderWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been created. ");
                writer.Close();
            }

            private void FolderWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\FolderLog.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been deleted. ");
                writer.Close();
            }

            private void FolderWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
            {
                TextWriter writer = new StreamWriter("C:\\folder\\log.txt", true);
                writer.WriteLine(DateTime.Now + " A new folder/file with name " + e.Name + " has been renamed. ");
                writer.Close();
            }

        }
    }

It does not execute the batch file. I am a newbie in .net and C# and I am not sure what to do from here.
thanks