问:
Flutter: Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized
Any solution to solve this problem?

Stacktrace:

```<code>[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
#0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:73:7)
#1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:86:4)
#2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
#3      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:314:35)
<asynchronous suspension>
#4      MethodChannel.invokeMapMethod (package:f<…>
</code>```

答:
Solution: Call WidgetsFlutterBinding.ensureInitialized(); before calling asynchronous functions.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();   //  ADD THIS BEFORE YOUR ASYNC FUNCTION CALL.
  await Firestore.instance.settings(...);      //  NOW YOU CAN CALL ASYNC FUNCTION.
  ...
  runApp(
    ...
  )
```

Body:
Any solution to solve this problem?

Stacktrace:

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
#0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:73:7)
#1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:86:4)
#2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
#3      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:314:35)
<asynchronous suspension>
#4      MethodChannel.invokeMapMethod (package:f<…>


来源: stackexchange

问:
AngularFirebase google signin idToken sometimes return user profile
This is a simple ionic and capacitor app, targeted at iOS and Android. We are authenticating users with AngularFirebase using the folliwng code:

```<code>private async loginGoogleWeb() {
  const provider = new firebase.auth.GoogleAuthProvider();
  provider.addScope('profile');
  provider.addScope('email');
  const credential = await this.afAuth.auth.signInWithPopup(provider);

  this.updateUserData(credential);
}
</code>```

Strange thing is that SOMETIMES the response in credential.credential.idTokenincludes the user profile (given_name, family_name, etc.). But most of the time, the idToken does not include this info.

Any idea as to why this could happen? Any help will be greatly appreciated.

答:
So after a lot of searching and reading, it turns out that Firebase does not return the idToken with the expected profile. According to one of the answers to this issue posted in Firebase Github:

As I said earlier your requests for features are reasonable, however
  we have discussed these things in the past and have determined that we
  won't add them to Firebase Auth right now. Since this issue tracker is
  meant to track bugs in the SDK or feature requests that we plan to
  implement, I am going to close this issue.

What I finally did is "exchange" the access_token provided by firebase and get the user profile using the following url: https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token={firebase_provided_access_token}

Just posting this in case someone bumps into this problem in the future.

ContentLicense: CC BY-SA 4.0

Body:
This is a simple ionic and capacitor app, targeted at iOS and Android. We are authenticating users with AngularFirebase using the folliwng code:

private async loginGoogleWeb() {
  const provider = new firebase.auth.GoogleAuthProvider();
  provider.addScope('profile');
  provider.addScope('email');
  const credential = await this.afAuth.auth.signInWithPopup(provider);

  this.updateUserData(credential);
}

Strange thing is that SOMETIMES the response in credential.credential.idTokenincludes the user profile (given_name, family_name, etc.). But most of the time, the idToken does not include this info.

Any idea as to why this could happen? Any help will be greatly appreciated.


问:
Cookies not transfering between pages (JS)
Coockies not transfering beetwen pages. I use JavaScript to specify them. When I write the same thing in the browser console on the page, it works:

```<code><script type="text/javascript" LANGUAGE="javascript">
    console.log("js working");
    window.onload = function(){
        console.log("window.onload working");
        console.log('document.getElementsByName("dbname")[0]');
        console.log(document.getElementsByName("dbname")[0]);
        if(typeof(document.getElementsByName("dbname")[0])!="undefined"){
            dbOpts=document.getElementsByName("dbname")[0].getElementsByTagName("option");
            console.log('dbOpts');
            console.log(dbOpts);
            for(i=0;i<dbOpts.length;i++){
                console.log(dbOpts[i].getAttribute("selected")!=null);
                if (dbOpts[i].getAttribute("selected")!=null) dbselectedparam=dbOpts[i].getAttribute("value");
            }
            console.log(dbselectedparam);
            document.cookie = "dbselectedparam="+dbselectedparam+"; path=/";
        }
    }
</script>
</code>```

How to fix this?

答:
you need to set the Expires of a cookie, otherwise it will be deleted when you close the browser/navigate away.

here is a great cookie script from quirksmode

```<code>function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
</code>```

Body:
Coockies not transfering beetwen pages. I use JavaScript to specify them. When I write the same thing in the browser console on the page, it works:

How to fix this?

Body:
you need to set the Expires of a cookie, otherwise it will be deleted when you close the browser/navigate away.

here is a great cookie script from quirksmode

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}


问:
How to execute commands in CMD using python?
I want to automate cmd commands using python but I also want the commands to show in CMD like I wrote them manually after launching the script. So for example, I want to use dir command in cmd, I tried doing that using subprocess module and the command executes properly but I also need the command to show like I wrote it myself before executing. I dont want the command to only execute and show the results. For example after launching the python script I want it to look like that:

C:\Users\User\Bob>dir

And after that, the output of the command would show below. How do I do that?

My code that I used to execute dir command in cmd:

```<code>import subprocess, os
list_files = subprocess.run('dir', shell=True)
os.system("pause")
</code>```

It executes the command just fine but I need the command as well.

答:
There is a nice library called invoke which can help you to automate shell commands with python. I've used it a couple times to do exactly that. You can install it via python -m pip install invoke. To make it output the shell command itself as well as it's output you could use it like this:

from invoke import run
result = run("echo hello", hide=False, echo=True)
```

<p>output would be</p>

<pre class="lang-sh prettyprint-override"><code>echo hi
hi
</code>```

Have a look at the documentation for the runners here.

Body:
I want to automate cmd commands using python but I also want the commands to show in CMD like I wrote them manually after launching the script. So for example, I want to use dir command in cmd, I tried doing that using subprocess module and the command executes properly but I also need the command to show like I wrote it myself before executing. I dont want the command to only execute and show the results. For example after launching the python script I want it to look like that:

C:\Users\User\Bob>dir

And after that, the output of the command would show below. How do I do that?

My code that I used to execute dir command in cmd:

import subprocess, os
list_files = subprocess.run('dir', shell=True)
os.system("pause")

It executes the command just fine but I need the command as well.

Body:
There is a nice library called invoke which can help you to automate shell commands with python. I've used it a couple times to do exactly that. You can install it via python -m pip install invoke. To make it output the shell command itself as well as it's output you could use it like this:

from invoke import run
result = run("echo hello", hide=False, echo=True)

output would be

echo hi
hi

Have a look at the documentation for the runners here.


问:
Calling Windows Form Method from its User Control
I have a User Control on My windows Form, and there is a button on my user control on click of which I want to call its form method.

Thanx

答:
Rethink your approach.  If there is a cross-cutting conern that is shared by both the user control and the form, don't put the code for it on the form.  By nature the user control can be shared across multiple forms, and there is no good reason why the user control should be tightly coupled to a specific form.

Move the code into a shared library/class and access it from the click even of the button on the user control.  This way the user control won't care which form it is on.

That said, if you really need to access the user control from the form, pass an instance of the form into the control at runtime:

```<code>protected void Form_Load(object sender, EventArgse)
{
    myUserControl.MainForm = this;
}
</code>```

Then you can access public properties/methods on the MainForm from the usercontrol's MainForm reference:

```<code>protected void MyButton_Click(object sender, EventArgs e)
{
    MainForm.Foo();
}
</code>```

Will call the Foo method in the MainForm instance.

(It has been a while since I did WinForms - so the method signatures for the event handlers might be slightly off, but the general principles should apply).

ContentLicense: CC BY-SA 3.0

Body:
Rethink your approach.  If there is a cross-cutting conern that is shared by both the user control and the form, don't put the code for it on the form.  By nature the user control can be shared across multiple forms, and there is no good reason why the user control should be tightly coupled to a specific form.

Move the code into a shared library/class and access it from the click even of the button on the user control.  This way the user control won't care which form it is on.

That said, if you really need to access the user control from the form, pass an instance of the form into the control at runtime:

protected void Form_Load(object sender, EventArgse)
{
    myUserControl.MainForm = this;
}

Then you can access public properties/methods on the MainForm from the usercontrol's MainForm reference:

protected void MyButton_Click(object sender, EventArgs e)
{
    MainForm.Foo();
}

Will call the Foo method in the MainForm instance.

(It has been a while since I did WinForms - so the method signatures for the event handlers might be slightly off, but the general principles should apply).


问:
css grid grows over 100% width with fr but not with minmax

.small-container { width: 200px; }
.small-container > div { margin: 16px; }
.border { box-shadow: 0 0 2px 2px black; }

.break-long-text {
    width: 100%;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.grid-fr {
    display: grid;
    grid-template-columns: 1fr;
}

.grid-minmax {
    display: grid;
    grid-template-columns: minmax(120px, 1fr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small-container">
  <div class="grid-fr">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
  <div class="grid-minmax">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
</div></code>```

The two grids are completely the same, the only difference is the grid-template-columns value. However, one grid respects the width of its parent (200px) and the other ignores the width.

grid: grid-template-columns: 1fr; => ignores parent-width and continues until the content is filled

grid: grid-template-columns: minmax(120px, 1fr); => Only goes up to parent-width (200px) and then becomes as high as necessary. However, it is still larger than the defined min-width (120px), which is of course correct since 1fr is larger than 120px in this example.

Since in the end both should have the same width of 1fr, I wonder about different results. Is this a bug or expected behavior?  And why does the second grid work the way I expect it to and not the first?

So should I always use minmax if I don't want one cell to be larger than its parent?

答:
Solution:

Setting min-width:0 of .break-long-text container will do the trick.

.small-container { width: 200px; }
.small-container > div { margin: 16px; }
.border { box-shadow: 0 0 2px 2px black; }

.min-width-0{
    min-width: 0;
}
.break-long-text {
    width: 100%;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.grid-fr {
    display: grid;
    grid-template-columns: 1fr;
}

.grid-minmax {
    display: grid;
    grid-template-columns: minmax(120px, 1fr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small-container">
  <div class="grid-fr">
    <div class="break-long-text border min-width-0">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
  <div class="grid-fr">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
  <div class="grid-minmax">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
</div></code>```

Explanation:

From css-tricks:

The minimum width of a grid column is auto. (The same is true for flex items, by the way.)

And since auto is entirely based on content, we can say it is “indefinitely” sized, its dimensions flex. If we were to put an explicit width on the column, like 50% or 400px, then we would say it is “definitely” sized.

To apply our fix, we need to make sure that there is the column has a definite minimum width instead of auto.

Body:
.small-container { width: 200px; }
.small-container > div { margin: 16px; }
.border { box-shadow: 0 0 2px 2px black; }

.break-long-text {
    width: 100%;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.grid-fr {
    display: grid;
    grid-template-columns: 1fr;
}

.grid-minmax {
    display: grid;
    grid-template-columns: minmax(120px, 1fr);
}

      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG

      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG

The two grids are completely the same, the only difference is the grid-template-columns value. However, one grid respects the width of its parent (200px) and the other ignores the width.

grid: grid-template-columns: 1fr; => ignores parent-width and continues until the content is filled

grid: grid-template-columns: minmax(120px, 1fr); => Only goes up to parent-width (200px) and then becomes as high as necessary. However, it is still larger than the defined min-width (120px), which is of course correct since 1fr is larger than 120px in this example.

Since in the end both should have the same width of 1fr, I wonder about different results. Is this a bug or expected behavior?  And why does the second grid work the way I expect it to and not the first?

So should I always use minmax if I don't want one cell to be larger than its parent?

Body:
Solution:

Setting min-width:0 of .break-long-text container will do the trick.

.small-container { width: 200px; }
.small-container > div { margin: 16px; }
.border { box-shadow: 0 0 2px 2px black; }

.min-width-0{
    min-width: 0;
}
.break-long-text {
    width: 100%;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.grid-fr {
    display: grid;
    grid-template-columns: 1fr;
}

.grid-minmax {
    display: grid;
    grid-template-columns: minmax(120px, 1fr);
}

<div class="small-container">
  <div class="grid-fr">
    <div class="break-long-text border min-width-0">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
  <div class="grid-fr">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
  <div class="grid-minmax">
    <div class="break-long-text border">
      LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG
    </div>
  </div>
</div>

Explanation:

From css-tricks:

The minimum width of a grid column is auto. (The same is true for flex items, by the way.)

And since auto is entirely based on content, we can say it is “indefinitely” sized, its dimensions flex. If we were to put an explicit width on the column, like 50% or 400px, then we would say it is “definitely” sized.

To apply our fix, we need to make sure that there is the column has a definite minimum width instead of auto.


问:
What happens if cursor.executemany fails in Python
I am using cursor.executemany to insert thousands of rows into snowflake database from some other source. So if in case the insert fails due to some reason, does it rollback all the inserts?

Is there some way to insert only if the same row does not exist yet? There is no primary key nor unique key in the table

答:
So if in case the insert fails due to some reason, does it rollback all the inserts?

The cursor.executemany(…) implementation in Snowflake's Python Connector fills a multi-row INSERT INTO command, whose values are pre-evaluated by the query compiler before the inserts run, so they all run together or fail early if a value is unacceptable to its defined column type.

Is there some way to insert only if the same row does not exist yet? There is no primary key nor unique key in the table

If there are no ID-like columns, you'll need to define a condition that qualifies two rows to be the same (such as a multi-column match).

Assuming your new batch of inserts are in a temporary table TEMP, the following SQL can insert into the DESTINATION table by performing a check of all rows against a set from the DESTINATION table.

Using HASH(…) as a basis for comparison, comparing all columns in each row together (in order):

INSERT INTO DESTINATION
  SELECT *
  FROM TEMP
  WHERE
    HASH(*) IS NOT IN ( SELECT HASH(*) FROM DESTINATION )
```

As suggested by Christian in the comments, the MERGE SQL command can also be used, once you have an identifier strategy (join keys). This too requires the new rows to be placed in a temporary table first, and offers an ability to perform an UPDATE if a row is already found.

Note: HASH(…) may have collisions and isn't the best fit. Better is to form an identifier using one or more of your table's columns, and compare them together. Your question lacks information about table and data characteristics, so I've picked a very simple approach involving HASH(…) here.

Body:
So if in case the insert fails due to some reason, does it rollback all the inserts?

The cursor.executemany(…) implementation in Snowflake's Python Connector fills a multi-row INSERT INTO command, whose values are pre-evaluated by the query compiler before the inserts run, so they all run together or fail early if a value is unacceptable to its defined column type.

Is there some way to insert only if the same row does not exist yet? There is no primary key nor unique key in the table

If there are no ID-like columns, you'll need to define a condition that qualifies two rows to be the same (such as a multi-column match).

Assuming your new batch of inserts are in a temporary table TEMP, the following SQL can insert into the DESTINATION table by performing a check of all rows against a set from the DESTINATION table.

Using HASH(…) as a basis for comparison, comparing all columns in each row together (in order):

INSERT INTO DESTINATION
  SELECT *
  FROM TEMP
  WHERE
    HASH(*) IS NOT IN ( SELECT HASH(*) FROM DESTINATION )

As suggested by Christian in the comments, the MERGE SQL command can also be used, once you have an identifier strategy (join keys). This too requires the new rows to be placed in a temporary table first, and offers an ability to perform an UPDATE if a row is already found.

Note: HASH(…) may have collisions and isn't the best fit. Better is to form an identifier using one or more of your table's columns, and compare them together. Your question lacks information about table and data characteristics, so I've picked a very simple approach involving HASH(…) here.


问:
How to get the smallest item from the second items of a tuple list?
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

```<code>graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}
</code>```

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

答:
Your problem comes when dealing when pair like 2: [(5, 9)] where there is juse 1 item, when accessing [1] this will fail, you gotta check the length before

```<code>def get_min(graph, key, position=1):
    values = graph[key]
    if len(values) > position:
      return min(values[position])
    return -1

graph = {1: [(3, 5), (4, 1), (5, 4)],2:[(5, 9)],3: [(5, 1), (6, 1)],4: [(2, 11), (8, 2)],
         5: [(4, 6), (2, 6)],6: [(7, 1)],7: [(5, 7), (2, 1)],8: [(2, 6)],}

for k,v in graph.items():
  print(k, get_min(graph, k))

1 => 1
2 => -1
3 => 1
4 => 2
5 => 2
6 => -1
7 => 1
8 => -1
</code>```

Body:
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.

I have the following graph

graph = {
    1: [(3, 5), (4, 1),  (5, 4)],
    2: [(5, 9)],
    3: [(5, 1), (6, 1)],
    4: [(2, 11), (8, 2)],
    5: [(4, 6), (2, 6)],
    6: [(7, 1)],
    7: [(5, 7), (2, 1)],
    8: [(2, 6)],
}

I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.

My current approach is min((graph[s])[1]), but this doesn't really work and mostly returns Index Errors.

Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1] now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).

Body:
Your problem comes when dealing when pair like 2: [(5, 9)] where there is juse 1 item, when accessing [1] this will fail, you gotta check the length before

def get_min(graph, key, position=1):
    values = graph[key]
    if len(values) > position:
      return min(values[position])
    return -1

graph = {1: [(3, 5), (4, 1), (5, 4)],2:[(5, 9)],3: [(5, 1), (6, 1)],4: [(2, 11), (8, 2)],
         5: [(4, 6), (2, 6)],6: [(7, 1)],7: [(5, 7), (2, 1)],8: [(2, 6)],}

for k,v in graph.items():
  print(k, get_min(graph, k))

1 => 1
2 => -1
3 => 1
4 => 2
5 => 2
6 => -1
7 => 1
8 => -1


问:
Assign a single cell to an array causes "Type Mismatch"
A fairly simple solution exists, I'm sure!

I have data held in a single Excel column that can have one to many entries.I need to add this to an array.

The code I have works well when there are 2 or more entries.

However, I get a type mismatch when there is only one value. I've tried a number of work-arounds, but no success! Here's the code:

```<code>Option Explicit
Private Namez() As Variant

With Sheets("Names")
    Range("A1").Select
    Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
If Lrow = 1 Then ' Attempt at coding for a single value
  Namez = Sheets("Names").Range("A1").Value ' Here's where it errors
  Else
  Namez = Sheets("Names").Range("A1:A" & Lrow).Value ' Or here (before adding the LRow = 1 line)
End If
</code>```

答:
i think you can do it like this way :</p>

```<code>Option Explicit
Private Namez() As Variant

With Sheets("Names")
    Range("A1").Select
    Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With

ReDim Namez(1 To Lrow)
For i = 1 To Lrow
    Namez(i) = Cells(i, 1).Value
Next
</code>```

Body:
A fairly simple solution exists, I'm sure!

I have data held in a single Excel column that can have one to many entries.I need to add this to an array.

The code I have works well when there are 2 or more entries.

However, I get a type mismatch when there is only one value. I've tried a number of work-arounds, but no success! Here's the code:

Option Explicit
Private Namez() As Variant

With Sheets("Names")
    Range("A1").Select
    Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
If Lrow = 1 Then ' Attempt at coding for a single value
  Namez = Sheets("Names").Range("A1").Value ' Here's where it errors
  Else
  Namez = Sheets("Names").Range("A1:A" & Lrow).Value ' Or here (before adding the LRow = 1 line)
End If

Body:
i think you can do it like this way :

Option Explicit
Private Namez() As Variant

With Sheets("Names")
    Range("A1").Select
    Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
End With

ReDim Namez(1 To Lrow)
For i = 1 To Lrow
    Namez(i) = Cells(i, 1).Value
Next


问:
Counting duplicate value only once in excel or VBA , will auto calculate my total of room type when i adding new room
this is my Room record. i need to put formula or VBA code to count my type of room.</p>

```<code>BedNum  RoomNum  RoomType         RoomType    totalcount
1001#1   1001     Studio           Studio         3
1001#2   1001     Studio           2br1cr         2
1001#3   1001     Studio           3br1cr         1
1002#1   1002     2br1cr
1002#2   1002     2br1cr
1003#1   1003     3br1cr
1003#2   1003     3br1cr
1004#1   1004     Studio
1004#2   1004     Studio
1005#1   1005     2br1cr
1005#2   1005     2br1cr
1006#1   1006     Studio
1006#2   1006     Studio
---------------------------------------------------------
above list is my Excel record , i wanna count in the rightside with formula or either VBA code ,
my RoomNumber will always increase and adding new room , what i want is total up the count of my roomtype.
</code>```

答:
Well use countifs() and countif(), like this:

Edit:
And if you wish to produce a list automatically you can look at this, but getting the list to be sorted I leave to you:

Body:
this is my Room record. i need to put formula or VBA code to count my type of room.

BedNum  RoomNum  RoomType         RoomType    totalcount
1001#1   1001     Studio           Studio         3
1001#2   1001     Studio           2br1cr         2
1001#3   1001     Studio           3br1cr         1
1002#1   1002     2br1cr
1002#2   1002     2br1cr
1003#1   1003     3br1cr
1003#2   1003     3br1cr
1004#1   1004     Studio
1004#2   1004     Studio
1005#1   1005     2br1cr
1005#2   1005     2br1cr
1006#1   1006     Studio
1006#2   1006     Studio
---------------------------------------------------------
above list is my Excel record , i wanna count in the rightside with formula or either VBA code ,
my RoomNumber will always increase and adding new room , what i want is total up the count of my roomtype.


问:
How do I concatenate text in a query in sql server?
The following SQL:

```<code>SELECT notes + 'SomeText'
FROM NotesTable a
</code>```

Give the error:

The data types nvarchar and text are incompatible in the add operator.

答: If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.</p>

OwnerDisplayName: Oglester

Body:
The following SQL:

SELECT notes + 'SomeText'
FROM NotesTable a

Give the error:

The data types nvarchar and text are incompatible in the add operator.

LastEditorDisplayName: Ray Vega

OwnerDisplayName: Edoode


问:
What does "static this()" outside of a class mean?
I'm very well aware of static constructors, but what does it mean to have a static this() outside of a class?

```<code>import std.stdio;

static this(){

  int x = 0;

}

int main(){

  writeln(x); // error

  return 0;
}
</code>```

And how do I access the variables define in static this() ?

答:
It's a module constructor. That code is run once for each thread (including the main thread).

There are also module destructors as well as shared module constructors and destructors:

```<code>static this()
{
   writeln("This is run on the creation of each thread.");
}

static ~this()
{
   writeln("This is run on the destruction of each thread.");
}

shared static this()
{
   writeln("This is run once at the start of the program.");
}

shared static ~this()
{
   writeln("This is run once at the end of the program.");
}
</code>```

The purpose of these is basically to initialise and deinitialise global variables.

Body:
I'm very well aware of static constructors, but what does it mean to have a static this() outside of a class?

import std.stdio;

static this(){

  int x = 0;

}

int main(){

  writeln(x); // error

  return 0;
}

And how do I access the variables define in static this() ?

Body:
It's a module constructor. That code is run once for each thread (including the main thread).

There are also module destructors as well as shared module constructors and destructors:

static this()
{
   writeln("This is run on the creation of each thread.");
}

static ~this()
{
   writeln("This is run on the destruction of each thread.");
}

shared static this()
{
   writeln("This is run once at the start of the program.");
}

shared static ~this()
{
   writeln("This is run once at the end of the program.");
}

The purpose of these is basically to initialise and deinitialise global variables.


问:
select from two independent table based on not exist a row in a third table joining them
I have a problem regarding an SQL query.
I need all rows from two independent tables those do not have a row joining them in a third table. The query is working this way but it has a very bad performance.

now my query look like this:

```<code>SELECT s.id,
       u.id
FROM   table1 s,
       table2 u
WHERE  NOT EXISTS
       (
              SELECT *
              FROM   table3 sj
              WHERE  sj.s_id=s.id
              AND    sj.u_id=u.id
       )
</code>```

Keys on table3 are:

```<code>ALTER TABLE `table3`
    ADD PRIMARY KEY (`id`),
    ADD KEY `s_id` (`s_id`),
    ADD KEY `u_id` (`u_id`);
</code>```

table1 has 4 rows,
table2 has 80.000 rows,
table3 has 30.000 rows

Any ideas how to optimise it?
Now the query takes up to 20 minutes to give results.

Edit:
Regarding the 20 minutes -> i forgot to set a key on the table3(u_id)
After setting the key it required just some seconds. Great.

答:
Your query seems to me like the right way to do what you want. I would just rewrite the old-school implicit join to an explicit cross join (but that’s semantically équivalent).

For performance, you need an index on table3(s_id, u_id).

However, you need to keep in mind that cross joining the tables generates a derived tables of about 2.4 billions rows, so there is still lot of work to do for the database in the not exists condition.

If sid and uid are not unique in the source table, then you can deduplicate before cross joining:

```<code>select ...
from (select distinct id from table1) s
cross join (select distinct id from table3) u
where not exists (...)
</code>```

Body:
I have a problem regarding an SQL query.
I need all rows from two independent tables those do not have a row joining them in a third table. The query is working this way but it has a very bad performance.

now my query look like this:

SELECT s.id,
       u.id
FROM   table1 s,
       table2 u
WHERE  NOT EXISTS
       (
              SELECT *
              FROM   table3 sj
              WHERE  sj.s_id=s.id
              AND    sj.u_id=u.id
       )

Keys on table3 are:

ALTER TABLE `table3`
    ADD PRIMARY KEY (`id`),
    ADD KEY `s_id` (`s_id`),
    ADD KEY `u_id` (`u_id`);

table1 has 4 rows,
table2 has 80.000 rows,
table3 has 30.000 rows

Any ideas how to optimise it?
Now the query takes up to 20 minutes to give results.

Edit:
Regarding the 20 minutes -> i forgot to set a key on the table3(u_id)
After setting the key it required just some seconds. Great.

Body:
Your query seems to me like the right way to do what you want. I would just rewrite the old-school implicit join to an explicit cross join (but that’s semantically équivalent).

For performance, you need an index on table3(s_id, u_id).

However, you need to keep in mind that cross joining the tables generates a derived tables of about 2.4 billions rows, so there is still lot of work to do for the database in the not exists condition.

If sid and uid are not unique in the source table, then you can deduplicate before cross joining:

select ...
from (select distinct id from table1) s
cross join (select distinct id from table3) u
where not exists (...)


问:
I loop through data frame, graph histogram for each column, use column name as graph title, print first value instead
I'd like to loop through columns with purrr::map and print a histogram for each of them. This works.

```<code>library(tidyverse)
library(patchwork)

iris %>% # example data
  select(-Species) %>% # drop one non-numeric col
  map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
         geom_histogram() # graph histogram
       ) %>% # output is list of graphs
  wrap_plots() # wrap list using patchwork
</code>```

But the graphs are pretty cryptic without titles to tell you which graph belongs to which column.

I tried adding a ggtitle option.

```<code>library(tidyverse)
library(patchwork)

iris %>%
  select(-Species) %>%
  map( ~ ggplot(iris, aes(x = .)) +
         geom_histogram() +
         ggtitle(.)
       ) %>%
  wrap_plots()
</code>```

However, it prints the first value of each column as the title, not the colname.

```<code>head(iris, 1) # for reference

</code>```

What should I be doing differently to get colnames as graph titles for the individual graphs? I can make do with proper x axis labels as well.

答:
Update: A solution with map2() is as follows. By extracting the column names to a separate vector as the .y argument, we can use it as the argument to xlab().

```<code>iris %>%
     select(-Species) %>%
     map2(.,.y = colnames(.), ~ ggplot(iris, aes(x = .x)) +
               geom_histogram() +
               xlab(.y)
     ) %>%
     wrap_plots()
</code>```

...and the output:

Original Post: One solution with lapply() looks like this.

```<code>chartList <- lapply(1:4,function(y){
     ggplot(iris, aes(x = iris[[y]])) +
          geom_histogram() +
          ggtitle(colnames(iris[y]))

})
wrap_plots(chartList)
</code>```

...and the output:

We can clean things up a bit if we replace ggtitle() with xlab() so the label prints below the x axis.

```<code>chartList <- lapply(1:4,function(y){
     ggplot(iris, aes(x = iris[[y]])) +
          geom_histogram() +
          xlab(colnames(iris[y]))

})
wrap_plots(chartList)
</code>```

Body:
I'd like to loop through columns with purrr::map and print a histogram for each of them. This works.

library(tidyverse)
library(patchwork)

iris %>% # example data
  select(-Species) %>% # drop one non-numeric col
  map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
         geom_histogram() # graph histogram
       ) %>% # output is list of graphs
  wrap_plots() # wrap list using patchwork

But the graphs are pretty cryptic without titles to tell you which graph belongs to which column.

I tried adding a ggtitle option.

library(tidyverse)
library(patchwork)

iris %>%
  select(-Species) %>%
  map( ~ ggplot(iris, aes(x = .)) +
         geom_histogram() +
         ggtitle(.)
       ) %>%
  wrap_plots()

However, it prints the first value of each column as the title, not the colname.

head(iris, 1) # for reference

What should I be doing differently to get colnames as graph titles for the individual graphs? I can make do with proper x axis labels as well.

Body:
Update: A solution with map2() is as follows. By extracting the column names to a separate vector as the .y argument, we can use it as the argument to xlab().

iris %>%
     select(-Species) %>%
     map2(.,.y = colnames(.), ~ ggplot(iris, aes(x = .x)) +
               geom_histogram() +
               xlab(.y)
     ) %>%
     wrap_plots()

...and the output:

Original Post: One solution with lapply() looks like this.

chartList <- lapply(1:4,function(y){
     ggplot(iris, aes(x = iris[[y]])) +
          geom_histogram() +
          ggtitle(colnames(iris[y]))

})
wrap_plots(chartList)

...and the output:

We can clean things up a bit if we replace ggtitle() with xlab() so the label prints below the x axis.

chartList <- lapply(1:4,function(y){
     ggplot(iris, aes(x = iris[[y]])) +
          geom_histogram() +
          xlab(colnames(iris[y]))

})
wrap_plots(chartList)


问:
Learning c++, compilation error "no matching function for call"
In the book Accelerated C+ I'm trying to run the code

```<code>#include <iostream>
#include <string>

int main() {
std::cout << "Please enter  your name: ";
std::string name;
std::cin >> name;

const std::string greeting = "Hello, " + name + "!";

const std::string spaces(greeting.size(), " ");
const std::string second = "* " + spaces + " *";

const std::string first(second.size(), + "*");

std::cout << std::endl;
std::cout << first << std::endl;
std::cout << second << std::endl;
std::cout << "* " << greeting << " *" << std::endl;
std::cout << second << std::endl;
std::cout << first << std::endl;

return 0;
}
</code>```

And its giving me a compilation error that says:

```<code>c:\Users\darkL\Desktop\cLearn\learnOne.cpp: In function 'int main()':
c:\Users\darkL\Desktop\cLearn\learnOne.cpp:15:47: error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(std::__cxx11::basic_string<char>::size_type, const char [2])'
     const std::string first(second.size(), "*");
                                               ^
In file included from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/string:52,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/locale_classes.h:40,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/ios_base.h:41,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/ios:42,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/ostream:38,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/iostream:39,
                 from c:\Users\darkL\Desktop\cLearn\learnOne.cpp:1:
C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/basic_string.h:604:9: note: candidate: 'template<class _InputIterator, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(_InputIterator, _InputIterator, const _Alloc&)'
         basic_string(_InputIterator __beg, _InputIterator __end,
         ^~~~~~~~~~~~
C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/basic_string.h:604:9: note:   template argument deduction/substitution failed:
c:\Users\darkL\Desktop\cLearn\learnOne.cpp:15:47: note:   deduced conflicting types for parameter '_InputIterator' ('unsigned int' and 'const char*')
     const std::string first(second.size(), "*");
                                                  ^
</code>```

does that mean the size() function is not valid for greeting? or is spaces() not valid?

答:
The second argument for the std::string constructor needs to be a char, not a string:

```<code>const std::string spaces(greeting.size(), ' ');
</code>```

You also need to do the same thing for the following line, and get rid of the + symbol:

```<code>const std::string first(second.size(), + "*");  // wrong
</code>```

like this:

```<code>const std::string first(second.size(), '*');
</code>```

Note that you could leave the + in there, but it doesn't do anything useful, and will be confusing to people reading your code, so you should avoid it.

Body:
In the book Accelerated C+ I'm trying to run the code

#include <iostream>
#include <string>

int main() {
std::cout << "Please enter  your name: ";
std::string name;
std::cin >> name;

const std::string greeting = "Hello, " + name + "!";

const std::string spaces(greeting.size(), " ");
const std::string second = "* " + spaces + " *";

const std::string first(second.size(), + "*");

std::cout << std::endl;
std::cout << first << std::endl;
std::cout << second << std::endl;
std::cout << "* " << greeting << " *" << std::endl;
std::cout << second << std::endl;
std::cout << first << std::endl;

return 0;
}

And its giving me a compilation error that says:

c:\Users\darkL\Desktop\cLearn\learnOne.cpp: In function 'int main()':
c:\Users\darkL\Desktop\cLearn\learnOne.cpp:15:47: error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(std::__cxx11::basic_string<char>::size_type, const char [2])'
     const std::string first(second.size(), "*");
                                               ^
In file included from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/string:52,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/locale_classes.h:40,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/ios_base.h:41,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/ios:42,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/ostream:38,
                 from C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/iostream:39,
                 from c:\Users\darkL\Desktop\cLearn\learnOne.cpp:1:
C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/basic_string.h:604:9: note: candidate: 'template<class _InputIterator, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(_InputIterator, _InputIterator, const _Alloc&)'
         basic_string(_InputIterator __beg, _InputIterator __end,
         ^~~~~~~~~~~~
C:/Mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/basic_string.h:604:9: note:   template argument deduction/substitution failed:
c:\Users\darkL\Desktop\cLearn\learnOne.cpp:15:47: note:   deduced conflicting types for parameter '_InputIterator' ('unsigned int' and 'const char*')
     const std::string first(second.size(), "*");
                                                  ^

does that mean the size() function is not valid for greeting? or is spaces() not valid?

Body:
The second argument for the std::string constructor needs to be a char, not a string:

const std::string spaces(greeting.size(), ' ');

You also need to do the same thing for the following line, and get rid of the + symbol:

const std::string first(second.size(), + "*");  // wrong

like this:

const std::string first(second.size(), '*');

Note that you could leave the + in there, but it doesn't do anything useful, and will be confusing to people reading your code, so you should avoid it.


问:
Python - differentiating similar images
I am trying to detect the differences in two images in python (object present or not). I tried different approaches with opencv and pillow for python. The goal is to check if an object is present or not. And if possible i want to extract the coordinates of the changes (with a bounding box)

The problem is, that the images are not 100% identical. There is always a very slight change in angle or lighting. Thresholding didnt do the trick as expected....

Is there any other approaches that you would suggest?

Thanks in advance

答:
You can use the Structural similarity index for a robust image comparison:

https://scikit-image.org/docs/dev/auto_examples/transform/plot_ssim.html

This is implemented on scikit-image package.

Title: Python - differentiating similar images


问:
MySQL - best way to update multiple rows based on text sent/fail
I have a PHP script that runs daily, loops through all users to send them a text, and updates their status. It's basically like this...(pseudo-code)

```<code>$sql="SELECT UserPhone from users WHERE Status='LOW'";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
   // loop through and send texts
}
// then update status
$sql="UPDATE users SET Status='MED'";
</code>```

I can detect whether the text was sent successfully, and I'd like to only update the user's status if the text was successful. My first instinct is to move the UPDATE into the while loop and update each user's row individually, something like this, pseudo-code again:

```<code>while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
    $sent=sendText($phone);
    if($sent) {
        $sql=UPDATE users SET Status='MED' WHERE UserPhone=$phone";
    }
}
</code>```

This feels clunky to me and I'm guessing isn't good for performance. It feels like I should be able to store/remember which texts sent and update all those users with a single UPDATE (or at least something that doesn't require a new UPDATE for every row).

I know just enough MySQL to do dumb stuff with it. Is there a better way to do this?

答:
You could do something like this:

```<code>$sql="SELECT UserPhone from users WHERE Status='LOW'";
$successes = []
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
   // loop through and send texts, set $ok to the success/fail
   if ($ok) {
      $successes[] = $row['UserPhone']
   }
}
// then update status
$placeholders = implode(",", array_fill(0, count($successes), "?");
$sql="UPDATE users SET Status='MED' WHERE UserPhone IN ($placeholders)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param(str_repeat("s", count($successes)), ...$successes);
$stmt->execute();
</code>```

But this is a risk. What if the PHP script is interrupted partway through? For example, during the while loop, perhaps one of the text-sendings causes a fatal error and the script exits, losing the information accumulated so far about which texts succeeded.

I worked for a couple of years at SchoolMessenger.com. We sent up to 9 million texts per day (it may be higher now since I left that job).

Here's the pseudocode for how we did the task (our service was written in Java, not PHP):

```<code>for each user who should be sent a text {
  INSERT INTO Tasks SET UserPhone = ?, Message = ?, Status = 'TODO'
}
</code>```

Then we have one row per user per text to send. There's another program monitoring this Tasks table, looking for any tasks with status of 'TODO'. When this finds that some rows exist:

```<code>for each row in Tasks that is 'TODO' {
  Send the text message
  Check success
  Update the status on that one row to 'Success' or 'Fail'
}
</code>```

This seems clunky, but a lot of systems like this are designed to remember where they left off if they crash. Saving the result to the database one step at a time helps, because once the program starts up, it can see which texts were already sent, and avoid re-sending any texts (because parents of school children would not like to receive the same message repeatedly).

Body:
I have a PHP script that runs daily, loops through all users to send them a text, and updates their status. It's basically like this...(pseudo-code)

$sql="SELECT UserPhone from users WHERE Status='LOW'";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
   // loop through and send texts
}
// then update status
$sql="UPDATE users SET Status='MED'";

I can detect whether the text was sent successfully, and I'd like to only update the user's status if the text was successful. My first instinct is to move the UPDATE into the while loop and update each user's row individually, something like this, pseudo-code again:

while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
    $sent=sendText($phone);
    if($sent) {
        $sql=UPDATE users SET Status='MED' WHERE UserPhone=$phone";
    }
}

This feels clunky to me and I'm guessing isn't good for performance. It feels like I should be able to store/remember which texts sent and update all those users with a single UPDATE (or at least something that doesn't require a new UPDATE for every row).

I know just enough MySQL to do dumb stuff with it. Is there a better way to do this?

Body:
You could do something like this:

$sql="SELECT UserPhone from users WHERE Status='LOW'";
$successes = []
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
   // loop through and send texts, set $ok to the success/fail
   if ($ok) {
      $successes[] = $row['UserPhone']
   }
}
// then update status
$placeholders = implode(",", array_fill(0, count($successes), "?");
$sql="UPDATE users SET Status='MED' WHERE UserPhone IN ($placeholders)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param(str_repeat("s", count($successes)), ...$successes);
$stmt->execute();

But this is a risk. What if the PHP script is interrupted partway through? For example, during the while loop, perhaps one of the text-sendings causes a fatal error and the script exits, losing the information accumulated so far about which texts succeeded.

I worked for a couple of years at SchoolMessenger.com. We sent up to 9 million texts per day (it may be higher now since I left that job).

Here's the pseudocode for how we did the task (our service was written in Java, not PHP):

for each user who should be sent a text {
  INSERT INTO Tasks SET UserPhone = ?, Message = ?, Status = 'TODO'
}

Then we have one row per user per text to send. There's another program monitoring this Tasks table, looking for any tasks with status of 'TODO'. When this finds that some rows exist:

for each row in Tasks that is 'TODO' {
  Send the text message
  Check success
  Update the status on that one row to 'Success' or 'Fail'
}

This seems clunky, but a lot of systems like this are designed to remember where they left off if they crash. Saving the result to the database one step at a time helps, because once the program starts up, it can see which texts were already sent, and avoid re-sending any texts (because parents of school children would not like to receive the same message repeatedly).


问:
insertion sort with dictionary
```<code>stock={'meat':100,'fish':50,'bread':70, 'milk':35,'chips':15, 'apple':10,'orange':10, 'rice':10,'honey':10,'lemon':10}

def insertionSort( theSeq ):
    n = len( theSeq )

    for i in range(1, n):
       key = theSeq[i]
       pos = i
       while pos > 0 and key < theSeq[pos - 1]:
           theSeq[pos] = theSeq[pos-1]
           pos -= 1

    theSeq[pos] = key

print('Input List:', stock)
insertionSort(stock)
print('Sorted List:', stock)
</code>```

these are my codes and i have been trying to sort my dictionary using insertion sort but i keep running into this error and have no idea what to.

i would like my output to be a list of unsorted dictionary followed by a list of the sorted dictionary

i would appreciate any help i can get
thank you in advance

答:
Dicts are not sequences (although they preserve insertion order in Python 3.7+). You can convert it to a list:

```<code>L = list(stock.items())
insertionSort(L)
print(L)
</code>```

... But apparently your algorithm doesn't work, since this is the output:

```<code>[('lemon', 10), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('milk', 35), ('orange', 10), ('rice', 10)]
</code>```

Title: insertion sort with dictionary

Body:
stock={'meat':100,'fish':50,'bread':70, 'milk':35,'chips':15, 'apple':10,'orange':10, 'rice':10,'honey':10,'lemon':10}

def insertionSort( theSeq ):
    n = len( theSeq )

    for i in range(1, n):
       key = theSeq[i]
       pos = i
       while pos > 0 and key < theSeq[pos - 1]:
           theSeq[pos] = theSeq[pos-1]
           pos -= 1

    theSeq[pos] = key

print('Input List:', stock)
insertionSort(stock)
print('Sorted List:', stock)

these are my codes and i have been trying to sort my dictionary using insertion sort but i keep running into this error and have no idea what to.

i would like my output to be a list of unsorted dictionary followed by a list of the sorted dictionary

i would appreciate any help i can get
thank you in advance

Body:
Dicts are not sequences (although they preserve insertion order in Python 3.7+). You can convert it to a list:

L = list(stock.items())
insertionSort(L)
print(L)

... But apparently your algorithm doesn't work, since this is the output:

[('lemon', 10), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('milk', 35), ('orange', 10), ('rice', 10)]


问:
Unable to Construct Stacked Vue-ChartJS Line Plot
I'm trying to make a stacked line chart using Vue-ChartJS but am having difficulties getting it to stack.

I tried adding the following into the fill data function but saw no change.

```<code>scales: {
    yAxes: [{ stacked: true}]
}
</code>```

I also tried creating a this.options entry but that didn't work either. The minimal reproducible code for the chart is as follows, any advice or help would be much appreciated!

```<code>## LineChart.js
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted() {
    this.renderChart(this.chartData, this.options)
  }
}

</code>```

```<code>## LineChart.vue
<template>
  <div class="small">
    <line-chart :chart-data="chartData"></line-chart>
    <button @click="fillData()">Randomize</button>
  </div>
</template>

<script>
import LineChart from '../store/LineChart.js'

export default {
  components: {
    LineChart
  },
  data() {
    return {
      chartData: null
    }
  },
  mounted() {
    this.fillData()
  },
  methods: {
    fillData() {
      this.chartData = {
        labels: [this.getRandomInt(), this.getRandomInt()],
        datasets: [
          {
            label: 'Data One',
            backgroundColor: '#f87979',
            data: [this.getRandomInt(), this.getRandomInt()]
          },
          {
            label: 'Data Two',
            backgroundColor: '#C23596',
            data: [this.getRandomInt(), this.getRandomInt()]
          }
        ]
      }
    },
    getRandomInt() {
      return Math.floor(Math.random() * (50 - 5 + 1)) + 5
    }
  }
}
</script>

<style>
.small {
  max-width: 600px;
  margin: 150px auto;
}
</style>

</code>```

答:
You need to pass scales in the options:

```<code>...

<div class="small">
  <line-chart :chart-data="chartData" :options="options"></line-chart>
  <button @click="fillData()">Randomize</button>
</div>

...

data() {
  return {
    chartData: null,
    options: {
      scales: {
        yAxes: [
          {
            stacked: true
          }
        ]
      },
    },
  }
},
</code>```

Body:
I'm trying to make a stacked line chart using Vue-ChartJS but am having difficulties getting it to stack.

I tried adding the following into the fill data function but saw no change.

scales: {
    yAxes: [{ stacked: true}]
}

I also tried creating a this.options entry but that didn't work either. The minimal reproducible code for the chart is as follows, any advice or help would be much appreciated!

## LineChart.js
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted() {
    this.renderChart(this.chartData, this.options)
  }
}

## LineChart.vue
<template>

    <line-chart :chart-data="chartData"></line-chart>
    <button @click="fillData()">Randomize</button>

</template>

Body:
You need to pass scales in the options:

...

<div class="small">
  <line-chart :chart-data="chartData" :options="options"></line-chart>
  <button @click="fillData()">Randomize</button>
</div>

...

data() {
  return {
    chartData: null,
    options: {
      scales: {
        yAxes: [
          {
            stacked: true
          }
        ]
      },
    },
  }
},


问:
saving webbrowser url to xml and retriving
I am trying to save my webbrowser controler URL to a xml file but I am getting an issue with certain characters preventing the save.

When I open a simple URL like this:

www.saypeople.com

It succesfully saves, however when I want to save webpage url like this:

http://scholar.google.com.pk/scholar?as_q=filetype:pdf +transistor+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en

The save fails.

I have checked a lot things and have discovered that my code only does not save when the url contains any of the two characters &<.

Please help me out.

Here is my code...

```<code>    public static DialogResult Show(string Title,  String url)
    {
        MsgBox = new addfav();
        MsgBox.textBox1.Text = Title;
        MsgBox.textBox2.Text = url;
        MsgBox.ShowDialog();
        return result;

    }
    const string dataxml = "data.xml";

    private void button1_Click(object sender, EventArgs e)
    {
       //textBox2.Text containing webpage url
       //textBox1.Text containing webpage title

        try
        {
            XmlTextReader reader = new XmlTextReader(dataxml);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode currNode;

            XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
            docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>" + "<url>"+  textBox2.Text + "</url>" + "</fav>";
            // insert the availability node into the document
            currNode = doc.DocumentElement;
            currNode.InsertAfter(docFrag, currNode.LastChild);
            //save the output to a file
            doc.Save(dataxml);
            this.DialogResult = DialogResult.OK;
            MessageBox.Show("Sucessfully Added");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.ToString());
            this.DialogResult = DialogResult.Cancel;
        }

        MsgBox.Close();
    }
</code>```

and
how can i retrive url by searching specific title in xml.

```<code><fav>
<Title>hello</Title>
<url><![CDATA[http://scholar.google.com.pk/scholar?as_q=filetype:pdf +hello+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en]]></url>
</fav>
<fav>
<Title>toad</Title>
<url><![CDATA[http://www.sciencedaily.com/search/?keyword=toad+ AND unknown OR unclear]]></url>
</fav>
</code>```

i want to search and save the url of toad title in string... please help me out...
thx

答:
To navigate through an XML file, you have to use a navigator as shown here.

```<code>XPathDocument xpathDoc = new XPathDocument([location of the file]);
XPathNavigator Navigator = xpathDoc.CreateNavigator();

String url_nav = "fav/url/text()";
XPathNodeIterator url_iterator = Navigator.Select(url_nav);

String URL_value = url_iterator.Current.Value;

url_iterator.MoveNext();
</code>```

If the file is too heavily nested, go for XML serialization.

Body:
I am trying to save my webbrowser controler URL to a xml file but I am getting an issue with certain characters preventing the save.

When I open a simple URL like this:

www.saypeople.com

It succesfully saves, however when I want to save webpage url like this:

http://scholar.google.com.pk/scholar?as_q=filetype:pdf +transistor+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en

The save fails.

I have checked a lot things and have discovered that my code only does not save when the url contains any of the two characters &<.

Please help me out.

Here is my code...

    public static DialogResult Show(string Title,  String url)
    {
        MsgBox = new addfav();
        MsgBox.textBox1.Text = Title;
        MsgBox.textBox2.Text = url;
        MsgBox.ShowDialog();
        return result;

    }
    const string dataxml = "data.xml";

    private void button1_Click(object sender, EventArgs e)
    {
       //textBox2.Text containing webpage url
       //textBox1.Text containing webpage title

        try
        {
            XmlTextReader reader = new XmlTextReader(dataxml);
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode currNode;

            XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
            docFrag.InnerXml = "<fav>" + "<Title>" + textBox1.Text + "</Title>" + "<url>"+  textBox2.Text + "</url>" + "</fav>";
            // insert the availability node into the document
            currNode = doc.DocumentElement;
            currNode.InsertAfter(docFrag, currNode.LastChild);
            //save the output to a file
            doc.Save(dataxml);
            this.DialogResult = DialogResult.OK;
            MessageBox.Show("Sucessfully Added");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.ToString());
            this.DialogResult = DialogResult.Cancel;
        }

        MsgBox.Close();
    }

and
how can i retrive url by searching specific title in xml.

<fav>
<Title>hello</Title>
<url><![CDATA[http://scholar.google.com.pk/scholar?as_q=filetype:pdf +hello+ AND&num=10&btnG=Search+Scholar&as_epq=&as_oq=unknown+unclear&as_eq=&as_occt=any&as_sauthors=+ &as_publication=+ &as_ylo=&as_yhi=&as_sdt=1.&as_sdtp=on&as_sdtf=&as_sdts=5&hl=en]]></url>
</fav>
<fav>
<Title>toad</Title>
<url><![CDATA[http://www.sciencedaily.com/search/?keyword=toad+ AND unknown OR unclear]]></url>
</fav>

i want to search and save the url of toad title in string... please help me out...
thx

Body:
To navigate through an XML file, you have to use a navigator as shown here.

XPathDocument xpathDoc = new XPathDocument([location of the file]);
XPathNavigator Navigator = xpathDoc.CreateNavigator();

String url_nav = "fav/url/text()";
XPathNodeIterator url_iterator = Navigator.Select(url_nav);

String URL_value = url_iterator.Current.Value;

url_iterator.MoveNext();

If the file is too heavily nested, go for XML serialization.


问:
fopen in binary mode returns null to existing file
I have a binary file ('''simdisk.bin'''). I opened it in  'r'  mode and i've no problems to read it. Now, i want to open it in binary mode (rb+) to write and read in binary, but i get a nill pointer.

I made a test.c file to try it with this main:

```<code>int main(int argc, char const *argv[])
{
 fp = fopen("simdisk.bin", "rb+");
 printf("Ptr: %p\n", fp);
 fclose(fp);
}
</code>```

答:
Effectively i haven`t the permissions to write on it. I had to change the permissions: "chmod 777 simdisk.bin".

Thanks!

Body:
I have a binary file ('''simdisk.bin'''). I opened it in  'r'  mode and i've no problems to read it. Now, i want to open it in binary mode (rb+) to write and read in binary, but i get a nill pointer.

I made a test.c file to try it with this main:

int main(int argc, char const *argv[])
{
 fp = fopen("simdisk.bin", "rb+");
 printf("Ptr: %p\n", fp);
 fclose(fp);
}


问:
Why does container div insist on being slightly larger than IMG or SVG content?
I'm trying to produce yet another lightbox as much needed HTML/CSS/Javascript practice, but I've encountered a styling issue that looks trivial (and probably is!) but I just can't solve it.

I have a div that contains an img. No matter what I try (border, margin, padding, auto height etc.) I just can't make the div shrink to match the image dimensions. I've reduced the problem to this:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <title>Layout experiments</title>

        <style type="text/css">
            #lightbox {
                margin: 0;
                padding: 0;
                position    : fixed;
                left        : 50%;
                margin-left : -320px;
                top         : 100px;
                border-radius: 22px;
                background  : #e0e0f0;
                color       : #102020;
            }

            #lightbox img {
                border-radius: 15px;
            }
            .imagebg {
                margin      : 7px;
                background  : black;
                border-radius: 15px;
                height      : 100%;
            }

        </style>

    </head>
    <body>

        <div id="lightbox">
            <div class="imagebg">
                <img src="picture.jpg">
            </div>
        </div>
    </body>
</html>
</code>```

'picture.jpg' is 640x400, but the container div wants to be 640x404, the difference showing itself as a black strip below the image. The div exists so that I can fade the image to black by blending it's opacity down to 0, swap it, then blend it back in.

I've looked at the computed styles in multiple browsers and can't see where the 4px delta is coming from.

答:
Apart from other working answers, setting display property of parent to flex worked for me as well:

```<code>.imagebg { display: flex }
</code>```

Body:
I'm trying to produce yet another lightbox as much needed HTML/CSS/Javascript practice, but I've encountered a styling issue that looks trivial (and probably is!) but I just can't solve it.

I have a div that contains an img. No matter what I try (border, margin, padding, auto height etc.) I just can't make the div shrink to match the image dimensions. I've reduced the problem to this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <title>Layout experiments</title>

'picture.jpg' is 640x400, but the container div wants to be 640x404, the difference showing itself as a black strip below the image. The div exists so that I can fade the image to black by blending it's opacity down to 0, swap it, then blend it back in.

I've looked at the computed styles in multiple browsers and can't see where the 4px delta is coming from.

Body:
Apart from other working answers, setting display property of parent to flex worked for me as well:

.imagebg { display: flex }


问:
Pages must fill the whole ViewPager2 (use match_parent)
I have an item layout where I display an image, product name, and product image. I must display image in 1:1.5 ration using constraint layout. But when I load a small image, below texts not displaying.

Below is my code of item XML:-

```<code><?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/coordinatorLayoutCartRoot"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.jackandphantom.circularimageview.RoundedImage
            android:id="@+id/imageViewSlider"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:layout_constraintBottom_toTopOf="@id/tvTitle"
            app:layout_constraintDimensionRatio="WH,1:1.4"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:rounded_radius="0"
            tools:src="@tools:sample/avatars" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="4dp"
            android:text="Fitted crew neck sweater"
            android:textColor="@color/colorBlack"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/imageViewSlider" />

        <TextView
            android:id="@+id/tvPrice"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="4dp"
            android:text="$34.00"
            android:textColor="@color/colorBlack"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tvTitle" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

Output with long image:- https://i.imgur.com/QVnljX6.png

Output with small image:- https://i.imgur.com/0ZwkVwE.png

And if I replace match_parent with wrap_content, app crashes with below error :-

java.lang.IllegalStateException: Pages must fill the whole ViewPager2 (use match_parent)

答:
You should to write like this:</p>

```<code>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view: View = inflater.inflate(R.layout.yourlayout, parent, false)
    view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    return ViewHolder(view)
}
inner class ViewHolder(itemView: View) :
    RecyclerView.ViewHolder(itemView) {
}
</code>```

Body:
I have an item layout where I display an image, product name, and product image. I must display image in 1:1.5 ration using constraint layout. But when I load a small image, below texts not displaying.

Below is my code of item XML:-

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/coordinatorLayoutCartRoot"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.jackandphantom.circularimageview.RoundedImage
            android:id="@+id/imageViewSlider"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:layout_constraintBottom_toTopOf="@id/tvTitle"
            app:layout_constraintDimensionRatio="WH,1:1.4"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:rounded_radius="0"
            tools:src="@tools:sample/avatars" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="4dp"
            android:text="Fitted crew neck sweater"
            android:textColor="@color/colorBlack"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/imageViewSlider" />

        <TextView
            android:id="@+id/tvPrice"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="4dp"
            android:text="$34.00"
            android:textColor="@color/colorBlack"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tvTitle" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Output with long image:- https://i.imgur.com/QVnljX6.png

Output with small image:- https://i.imgur.com/0ZwkVwE.png

And if I replace match_parent with wrap_content, app crashes with below error :-

java.lang.IllegalStateException: Pages must fill the whole ViewPager2 (use match_parent)

Body:
You should to write like this:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view: View = inflater.inflate(R.layout.yourlayout, parent, false)
    view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    return ViewHolder(view)
}
inner class ViewHolder(itemView: View) :
    RecyclerView.ViewHolder(itemView) {
}


问:
Mocking Internal State
I'm looking for a suitable mocking tool to mock internal states (e.g. void methods).  I know Powermock and JMock can do this but I have not made a choice yet.  I have more experience with EasyMock but have not tried mocking internal states.  I'm not so sure if it is inherently supported.  I'm still scouring its documentation.</p>

答:
Let's say you have a class like this where you've got an annoying bit of internal state (which is access by a method called doSomething) and it's stopping you testing myMethod.

```<code>public class Me {
     public int myMethod () {
         doSomething();
         return 7;
     }

     void doSomething() {
          // Access some internal state which is hard to mock
     }
}
</code>```

You can deal with this by just overriding that in your test.

```<code>@Test
public void testMyMethod () {
    Me fixture = new Me() {
       @Override
       void doSomething() {
       }
    }
    Assert.assertEquals(7, fixture.myMethod());
}
</code>```

Using Mockito you can achieve the same with spy and doAnswer.  For example.

```<code>    Me me = new Me(); // the original fixture

    Me mySpy = spy(me); // a spied version when you can copy the behaviour
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock inv) throws Throwable {
            throw new Exception("Hello!");
        }
    }).when(mySpy).doSomething();

    // Will throw an exception or obviously whatever you put in the body of the answer method
    mySpy.doSomething();
</code>```

Title: Mocking Internal State

Body:
Let's say you have a class like this where you've got an annoying bit of internal state (which is access by a method called doSomething) and it's stopping you testing myMethod.

public class Me {
     public int myMethod () {
         doSomething();
         return 7;
     }

     void doSomething() {
          // Access some internal state which is hard to mock
     }
}

You can deal with this by just overriding that in your test.

@Test
public void testMyMethod () {
    Me fixture = new Me() {
       @Override
       void doSomething() {
       }
    }
    Assert.assertEquals(7, fixture.myMethod());
}

Using Mockito you can achieve the same with spy and doAnswer.  For example.

    Me me = new Me(); // the original fixture

    Me mySpy = spy(me); // a spied version when you can copy the behaviour
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock inv) throws Throwable {
            throw new Exception("Hello!");
        }
    }).when(mySpy).doSomething();

    // Will throw an exception or obviously whatever you put in the body of the answer method
    mySpy.doSomething();


问:
After changing the "Price Class" in "CloudFront" the change has no effect
I changed the Price Class of an Amazon CloudFront distribution, but even after a few days it continues to pass traffic to regions that are no longer listed.

Do I need to do something for the change to take effect?

答:
Price class can limit distribution regions saving on delivery cost if you are willing to compromise performance.

Even if you set a limiting price class (Eg. only US, Canada and Europe) CloudFront may occasionally serve requests from an edge location in a region that is not included in your price class - when this happens you will be charged by the least expensive region in your price class.

See here for more details


问:
Is there any generic API on android to set a new font on anyforeground windows textview or editor
I am looking to find if there is any way to set a font on foreground windows textbox or editor on android.
ex like what we have sendmessage or postmessage on windows we can send a font in these and system applies that font to the specified window. Is there anything similar on android?</p>

答:
Android uses styles and themes to set look and feel. You can set a theme at the application level, activity level, or for individual views. Modify AndroidManifest.xml to set themes at the application or activity level. All of it is described in: https://developer.android.com/guide/topics/ui/look-and-feel/themes#Theme. It includes detailed sample code and should take no more than 15 to read and implement.

In your theme you can include a font to use. Fonts can be easily defined in XML starting at API level 26 (easily compared to how you needed to do it before API 26). The details can be found here: https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml. In that documentation it will tell you how to set a font and apply it to an individual view or to a style. This reading should also take no longer than 15 minutes and includes detailed sample code.

Your steps will be, after just reading the above two official Android docs, to 1) define your font, 2) set the font in a style. 3) use the style as a theme and set your application or activity to use that theme in AndroidManifest.xml. If you set your theme in AndroidManifest.xml. And by reading the docs, you'll be a master at defining and implementing different levels of themes!


问:
Parsing date with MySQL
I have a date of the type

August 15, 2009

I'm trying to parse it with

DATE_FORMAT('August 15, 2009', '%M %e, %Y')

But it is not working returns NULL.

Oh mighty overflowers, do you have any idea what might be the problem?

答:
See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format</p>

```<code>mysql> SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
        -> '2013-05-01'
</code>```

Title: Parsing date with MySQL

Body:
See http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date-format

mysql> SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
        -> '2013-05-01'


问:
SQL query to display Count of records based in range from another table
I have two tables Range and Employee.

Range table consists of columns

```<code>minimum_salary, maximum salary, program
</code>```

(Available programs for that salary like platinum and silver etc).

Employee table has columns

```<code>Emp_Id, Emp_Name, Salary
</code>```

https://i.stack.imgur.com/RKaXP.png

I want to write a SQL query in such a way that it gets the  count of employees who fall under the given salary range in range table, please refer screenshot for tables and result set.

Any help is appreciated. Thanks

答:
Please, add a column into Range table that name Emp_ID. Because, it help to join two table. I mean need primary key & foreign key.

Query:

```<code>select COUNT(e.empID), r.program
FROM rangeTable AS r
INNER JOIN empTable AS e ON e.salary BETWEEN r.min_salary AND r.max_salary
GROUP BY r.program
</code>```

Body:
I have two tables Range and Employee.

Range table consists of columns

minimum_salary, maximum salary, program

(Available programs for that salary like platinum and silver etc).

Employee table has columns

Emp_Id, Emp_Name, Salary

https://i.stack.imgur.com/RKaXP.png

I want to write a SQL query in such a way that it gets the  count of employees who fall under the given salary range in range table, please refer screenshot for tables and result set.

Any help is appreciated. Thanks

Body:
Please, add a column into Range table that name Emp_ID. Because, it help to join two table. I mean need primary key & foreign key.

Query:

select COUNT(e.empID), r.program
FROM rangeTable AS r
INNER JOIN empTable AS e ON e.salary BETWEEN r.min_salary AND r.max_salary
GROUP BY r.program


问:
How to solve divisible triangular problem (ProjectEuler) efficiently in Kotlin?
I was solving problems on the the ProjectEuler, And I am stuck on the 12th problem, the following code takes too longer not even done in five minutes and my CPU got warm.

Essentially what I am doing is generate a sequence of triangular numbers by adding successive natural numbers like:

1 -> 1 (i.e. 1)

2 -> 3 (i.e. 1+2)

3 -> 6 (i.e. 1+2+3)

And so on, then finding the first triangular number which has more than 500 factors (i.e. 501 factors).

fun main() {
    val numbers = generateTriangularNumbers()
    val result = numbers.first {
        val count = factorOf(it).count()
        //        println(count) // just to see the count
        count > 500
    }
    println(result)
}

// Finds factor of input [x]
private fun factorOf(x: Long): Sequence<Long> = sequence {
    var current = 1L
    while (current <= x) {
        if (x % current == 0L) yield(current++) else current++
    }
}

// generates triangular numbers, like 1, 3, 6, 10. By adding numbers like 1+2+3+...n.
private fun generateTriangularNumbers(from: Long = 1): Sequence<Long> = sequence {
    val mapper: (Long) -> Long = { (1..it).sum() }
    var current = from
    while (true) yield(mapper(current++))
}
```

The count (number of factors of triangular numbers) is hardly getting over 200, Is there a way to efficiently solve this problem, maybe within a minute?

答:
Project Euler is about math. Programming comes second. You need to do some homework.

Prove that triangular numbers are in form of n*(n+1)/2. Trivial.

Prove that n and n+1 are coprime. Trivial.

Prove, or at least convince yourself, that d(n) is multiplicative.

Combine this knowledge to come up with an efficient algorithm. You wouldn't need to actually compute the triangular numbers, and you would need to factorize the number much smaller; memoization would also avoid quite a few factorizations.

Body:
I was solving problems on the the ProjectEuler, And I am stuck on the 12th problem, the following code takes too longer not even done in five minutes and my CPU got warm.

Essentially what I am doing is generate a sequence of triangular numbers by adding successive natural numbers like:

1 -> 1 (i.e. 1)

2 -> 3 (i.e. 1+2)

3 -> 6 (i.e. 1+2+3)

And so on, then finding the first triangular number which has more than 500 factors (i.e. 501 factors).

fun main() {
    val numbers = generateTriangularNumbers()
    val result = numbers.first {
        val count = factorOf(it).count()
        //        println(count) // just to see the count
        count > 500
    }
    println(result)
}

// Finds factor of input [x]
private fun factorOf(x: Long): Sequence<Long> = sequence {
    var current = 1L
    while (current <= x) {
        if (x % current == 0L) yield(current++) else current++
    }
}

// generates triangular numbers, like 1, 3, 6, 10. By adding numbers like 1+2+3+...n.
private fun generateTriangularNumbers(from: Long = 1): Sequence<Long> = sequence {
    val mapper: (Long) -> Long = { (1..it).sum() }
    var current = from
    while (true) yield(mapper(current++))
}

The count (number of factors of triangular numbers) is hardly getting over 200, Is there a way to efficiently solve this problem, maybe within a minute?


问:
Stop link from loading
I have been trying for a few hours now and decided to finally post here. I have been trying so many methods to get my links to stop with preventDefault, this way I can load in content async.

All my links that i have tried that are apart of the template (like in the header) work perfectly, but any of the links brought in through an async view (and generated via js) completely skip over this snippet of code. I wanted to track anything that has a className "router" and stop the default action and run the function navigate instead.

```<code>var routeclicked = document.getElementsByClassName('router');
    for(let i = 0; i < routeclicked.length; i++) {
      routeclicked[i].addEventListener("click", e => {
        console.log("Router is: " + routeclicked[i]);
        e.preventDefault();
        router = routeclicked[i].pathname;
        console.log("Router 2 is: " + router);
        navigate();
      });
    }
</code>```

答:
Attach a listener to "body" or the first non-dynamic parent.

You could go for  Event.target and .closest().

Also, don't put functions inside for loops, it defies the reusability of functions.

const navigate = (EL) => {
  location = EL.pathname;
}

const navigateHandler = (ev) => {
  const EL = ev.target.closest(".router"); // Self or closest
  if (!EL) return;
  ev.preventDefault();
  navigate(EL);
}

document.querySelector("body").addEventListener("click", navigateHandler);```

Title: Stop link from loading

Body:
I have been trying for a few hours now and decided to finally post here. I have been trying so many methods to get my links to stop with preventDefault, this way I can load in content async.

All my links that i have tried that are apart of the template (like in the header) work perfectly, but any of the links brought in through an async view (and generated via js) completely skip over this snippet of code. I wanted to track anything that has a className "router" and stop the default action and run the function navigate instead.

var routeclicked = document.getElementsByClassName('router');
    for(let i = 0; i < routeclicked.length; i++) {
      routeclicked[i].addEventListener("click", e => {
        console.log("Router is: " + routeclicked[i]);
        e.preventDefault();
        router = routeclicked[i].pathname;
        console.log("Router 2 is: " + router);
        navigate();
      });
    }


问:
Allow everything for IdentityServer client?
I have finished setting up Identity Server, and it is now giving me an invalid scope error. I don't care about scopes, I simply want to allow access to everything, as long as they get the access token initially.

When not passing scope, or passing an empty scope Identity Server complains about no scopes have been allowed, because I don't want any? I have not set any anywhere

How can I get an access token without scopes?

答:
According to OAuth 2.0 specification, an application can request one or more scopes. Which means, you must ask for at least one of the scopes. OIDC specification states that you must ask for at least "openid" scope (required; to indicate that the application intends to use OIDC to verify the user's identity).

So, you cannot get access token without asking for "openid" scope. "OpenID Connect requests MUST contain the openid scope value"


问:
best/correct way to add value="" to a <button>
I've been creating buttons in two ways:

```<code><button class="....>NAME</button>
</code>```

and

```<code><div class="btn-group....
     <label class="btn...><input>NAME</input></label>
     <label...
</div>
</code>```

Question is, if I were to add a value to a button (to be manipulated on pressing the button), where /should/ I do that? In the label, the input, or use the < button> method? I'm ignorant, I know.

答: That depends on the value you want to modify. If you just want to change the Text on the button, you can use both by editing the innerHTML-Value of the Element the text is in via JavaScript. This would be in this cases the  and the  If you want to modify things like an onClick-Event I'd prefer to use the  method, but it's possible with both of them.</p>

Body:
I've been creating buttons in two ways:

<button class="....>NAME</button>

and

<div class="btn-group....
     <input>NAME</input>
     <label...

Question is, if I were to add a value to a button (to be manipulated on pressing the button), where /should/ I do that? In the label, the input, or use the < button> method? I'm ignorant, I know.


问:
Retrieve characters from a string
What is the best way to get a list of characters [a-z] from a string ignoring any other special character or number?</p>

答:
Limiting yourself to a-z might remove characters you want. e.g. it remove uppercase and letters other than a-z.  You might prefer to try

```<code>String alphaOnly = text.replaceAll("[^\\p{Alpha}]", "");
</code>```

This includes upper and lower case letters from any language.

Title: Retrieve characters from a string

Body:
Limiting yourself to a-z might remove characters you want. e.g. it remove uppercase and letters other than a-z.  You might prefer to try

String alphaOnly = text.replaceAll("[^\\p{Alpha}]", "");

This includes upper and lower case letters from any language.


问:
How do I create an incrementing filename in Python?
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the code again it will going to increment the file name. and will not overwrite the existing one. I am thinking of checking the filename first on the directory and if they are the same the code will generate a new filename:</p>

```<code>fh = open("sample.xml", "w")
rs = [blockresult]
fh.writelines(rs)
fh.close()
</code>```

答:
Here is one more example. Code tests whether a file exists in the directory or not if exist it does increment in the last index of the file name and saves
The typical file name is: Three letters of month_date_lastindex.txt ie.e.g.May10_1.txt</p>

```<code>import time
import datetime
import shutil
import os
import os.path

da=datetime.datetime.now()

data_id =1
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%b%d")
data_id=str(data_id)
filename = st+'_'+data_id+'.dat'
while (os.path.isfile(str(filename))):
    data_id=int(data_id)
    data_id=data_id+1
    print(data_id)
    filename = st+'_'+str(data_id)+'.dat'
    print(filename)

shutil.copyfile('Autonamingscript1.py',filename)

f = open(filename,'a+')
f.write("\n\n\n")
f.write("Data comments: \n")

f.close()
</code>```

Body:
I'm creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it overwrites the old file into the new one because they do have the same file name. How do I increment the file names so that whenever I try to run the code again it will going to increment the file name. and will not overwrite the existing one. I am thinking of checking the filename first on the directory and if they are the same the code will generate a new filename:

fh = open("sample.xml", "w")
rs = [blockresult]
fh.writelines(rs)
fh.close()

Body:
Here is one more example. Code tests whether a file exists in the directory or not if exist it does increment in the last index of the file name and saves
The typical file name is: Three letters of month_date_lastindex.txt ie.e.g.May10_1.txt

import time
import datetime
import shutil
import os
import os.path

da=datetime.datetime.now()

data_id =1
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%b%d")
data_id=str(data_id)
filename = st+'_'+data_id+'.dat'
while (os.path.isfile(str(filename))):
    data_id=int(data_id)
    data_id=data_id+1
    print(data_id)
    filename = st+'_'+str(data_id)+'.dat'
    print(filename)

shutil.copyfile('Autonamingscript1.py',filename)

f = open(filename,'a+')
f.write("\n\n\n")
f.write("Data comments: \n")

f.close()


问:
Getting 'psutil.AccessDenied (pid=6836)' error using psutil
I want to check if a program is running or not, so I searched and I tried this , in this way:

```<code>import psutil
if "notepad.exe" in (p.name() for p in psutil.process_iter()):
    print('program is running')
else:
    print('not running')
</code>```

but I get this error:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~/temp.py", line 2, in <module>
    if "notepad.exe" in (p.name() for p in psutil.process_iter()):
  File "~/temp.py", line 2, in <genexpr>
    if "notepad.exe" in (p.name() for p in psutil.process_iter()):
  File "~\Python\Python38-32\lib\site-packages\psutil\__init__.py", line 630, in name
    name = self._proc.name()
  File "~\Python\Python38-32\lib\site-packages\psutil\_pswindows.py", line 750, in name
    return os.path.basename(self.exe())
  File "~\Python\Python38-32\lib\site-packages\psutil\_pswindows.py", line 681, in wrapper
    raise convert_oserror(err, pid=self.pid, name=self._name)
psutil.AccessDenied: psutil.AccessDenied (pid=6836)

Process finished with exit code 1
```

am I doing something wrong with this simple code?
or is there another alternative way?

EDIT: sorry, i forgot to mention im on windows, not linux,  can u give me solutions for windows platform?

答:
You may need administrator / root privileges on your system.

If you can get a command prompt, try to use sudo before running python to elevate your privileges to the root user. Or give your user Administrator level access.

Body:
I want to check if a program is running or not, so I searched and I tried this , in this way:

import psutil
if "notepad.exe" in (p.name() for p in psutil.process_iter()):
    print('program is running')
else:
    print('not running')

but I get this error:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "~/temp.py", line 2, in <module>
    if "notepad.exe" in (p.name() for p in psutil.process_iter()):
  File "~/temp.py", line 2, in <genexpr>
    if "notepad.exe" in (p.name() for p in psutil.process_iter()):
  File "~\Python\Python38-32\lib\site-packages\psutil\__init__.py", line 630, in name
    name = self._proc.name()
  File "~\Python\Python38-32\lib\site-packages\psutil\_pswindows.py", line 750, in name
    return os.path.basename(self.exe())
  File "~\Python\Python38-32\lib\site-packages\psutil\_pswindows.py", line 681, in wrapper
    raise convert_oserror(err, pid=self.pid, name=self._name)
psutil.AccessDenied: psutil.AccessDenied (pid=6836)

Process finished with exit code 1

am I doing something wrong with this simple code?
or is there another alternative way?

EDIT: sorry, i forgot to mention im on windows, not linux,  can u give me solutions for windows platform?