问:
What is the safest way to split a "Floating Point Number String" into its Whole and Fractional Parts
I have developed the following short function to split a number passed to it in a string format into its Whole and Fractional Parts (also outputted as strings).

Note1: The Whole part of the number can run into large numbers (in excess of 50 digits).

Note 2: The output result (the Whole and the Fraction strings) will not be converted into an integer or a float but will be further manipulated only as a string due to the Javascript rounding for large numbers. So going back to numbers is not a concern here

Because the function detects the machine's locale automatically, it is therefore expected that the user enters (passes) the number in the locale of his local machine or otherwise the number is generated programmatically and passed to the function.

The number is expected to be passed as a "string" due to the very large length and also because there is no handling for numbers passed in exponent (e) format.

The function uses the toLocaleString() to detect the decimal and thousand separators.

I have tested the function with the major number systems (.,' space) and so far, so good.

The question is, how safe will this code be, and are there any alternative better and safer methods to do it or corrections/changes necessary?

Thanks

 function splitFloatString(NumString) {
    var decimalSeparator  = (1.1).toLocaleString().substring(1,2);  // Get Decimal Separator
    var thousandSeparator = (1000).toLocaleString().substring(1,2); // Get Thousands Separator
    NumString += "";                                                // ensure a string
    var fraction ="0";                                              // default no fractional part
    NumString = NumString.replace(RegExp("\\"+thousandSeparator,"g"),"");   //remove thousand separators if any

    if (RegExp("\\"+decimalSeparator,"g").test(NumString)) {        // test for decimal separator
       var n = NumString.split(decimalSeparator);                   // Split at Decimal Seprator
       NumString = n[0];                                            // The Whole part
       if (n.length==2) fraction = n[1];                            // The Fractional part
       if (fraction=="") fraction ="0";
       }

  console.log("Whole: ("+NumString+"), Fraction: ("+fraction+")");  // added for testing
  //return n=[NumString,fraction];                                  // normal return uncomment
}

 //------------------------------------------------------------------------------------
 // Tests assuming user's machine and user enters/passes US-EN separators as an example
 //------------------------------------------------------------------------------------
        splitFloatString("123456789123456699999887788812340786.45678907656912574321115194123123456789");
        splitFloatString("1,234,567,891,234,566,999,998,888,812,340.456520754186789075194123123456789");
        splitFloatString("200")
        splitFloatString("0.")
        splitFloatString(123456.2349999)
        splitFloatString("")
        splitFloatString()```

答:
According to me, you are just complicating the whole thing unnecessarily. Here's a simple way to achieve the same result.

function getLocaleSeparators() {
  const testNumber = 1000.1.toLocaleString()
  return [testNumber.substring(1,2), testNumber.substring(5,6)]
}

function splitFloatString(number) {
  const numberString = number.toString()
  const [thousandSeparator, decimalSeparator] = getLocaleSeparators()
  let [wholePart, fractionPart] = numberString.replace(new RegExp(thousandSeparator, 'g'), '').split(decimalSeparator)
  wholePart = wholePart || "0"
  fractionPart = fractionPart || "0"
  console.log(`Whole: ${wholePart}, Fraction: ${fractionPart}`);
}
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getLocaleSeparators() {
  const testNumber = 1000.1.toLocaleString()
  return [testNumber.substring(1,2), testNumber.substring(5,6)]
}

function splitFloatString(number) {
  const numberString = number.toString()
  const [thousandSeparator, decimalSeparator] = getLocaleSeparators()
  let [wholePart, fractionPart] = numberString.replace(new RegExp(thousandSeparator, 'g'), '').split(decimalSeparator)
  wholePart = wholePart || "0"
  fractionPart = fractionPart || "0"
  console.log(`Whole: ${wholePart}, Fraction: ${fractionPart}`);
}

splitFloatString("123456789123456699999887788812340786.45678907656912574321115194123123456789");
splitFloatString("1,234,567,891,234,566,999,998,888,812,340.456520754186789075194123123456789");
splitFloatString("200")
splitFloatString("0.")
splitFloatString(123456.2349999)
splitFloatString("")</code>```

Body:
According to me, you are just complicating the whole thing unnecessarily. Here's a simple way to achieve the same result.

function getLocaleSeparators() {
  const testNumber = 1000.1.toLocaleString()
  return [testNumber.substring(1,2), testNumber.substring(5,6)]
}

function splitFloatString(number) {
  const numberString = number.toString()
  const [thousandSeparator, decimalSeparator] = getLocaleSeparators()
  let [wholePart, fractionPart] = numberString.replace(new RegExp(thousandSeparator, 'g'), '').split(decimalSeparator)
  wholePart = wholePart || "0"
  fractionPart = fractionPart || "0"
  console.log(`Whole: ${wholePart}, Fraction: ${fractionPart}`);
}

function getLocaleSeparators() {
  const testNumber = 1000.1.toLocaleString()
  return [testNumber.substring(1,2), testNumber.substring(5,6)]
}

function splitFloatString(number) {
  const numberString = number.toString()
  const [thousandSeparator, decimalSeparator] = getLocaleSeparators()
  let [wholePart, fractionPart] = numberString.replace(new RegExp(thousandSeparator, 'g'), '').split(decimalSeparator)
  wholePart = wholePart || "0"
  fractionPart = fractionPart || "0"
  console.log(`Whole: ${wholePart}, Fraction: ${fractionPart}`);
}

splitFloatString("123456789123456699999887788812340786.45678907656912574321115194123123456789");
splitFloatString("1,234,567,891,234,566,999,998,888,812,340.456520754186789075194123123456789");
splitFloatString("200")
splitFloatString("0.")
splitFloatString(123456.2349999)
splitFloatString("")


来源: stackexchange

问:
Why can i not access attributes from another class in swift?
Im making a userProfile class in swift which includes the following code:

```<code>class userProfile {

    var firstname: String!
    var username: String!
    var lastname: String!
    var uid: String!

     init(uid: String, dictionary: Dictionary<String, AnyObject>) {

         self.uid = uid

         if let username = dictionary["username"]as? String {
             self.username = username
         }

         if let firstname = dictionary["firstname"]as? String {
             self.firstname = firstname
         }

         if let lastname = dictionary["lastname"]as? String {
             self.lastname = lastname
         }
     }
}
</code>```

and i am trying to access the the attributes in another class with the following code:

```<code> var user: userProfile? {
      didSet {
          let fullName = userProfile?.firstname
          firstname.text = fullName
     }
 }
</code>```

But when i do this i get the following error and i don't know why:

Type 'userProfile?' has no member 'firstname'

how di i fix this?

答:
Here is a fix (you tried to access class, but should be instance) :

```<code> var user: userProfile? {
      didSet {
          let fullName = user?.firstname // << here !!

          firstname.text = fullName    // I can't say if this valid
     }
 }
</code>```

To avoid such ambiguity you should follow a rule to name classes in UpperCase, ie. in you case UserProfile.

ContentLicense: CC BY-SA 4.0

Body:
Im making a userProfile class in swift which includes the following code:

class userProfile {

    var firstname: String!
    var username: String!
    var lastname: String!
    var uid: String!

     init(uid: String, dictionary: Dictionary<String, AnyObject>) {

         self.uid = uid

         if let username = dictionary["username"]as? String {
             self.username = username
         }

         if let firstname = dictionary["firstname"]as? String {
             self.firstname = firstname
         }

         if let lastname = dictionary["lastname"]as? String {
             self.lastname = lastname
         }
     }
}

and i am trying to access the the attributes in another class with the following code:

 var user: userProfile? {
      didSet {
          let fullName = userProfile?.firstname
          firstname.text = fullName
     }
 }

But when i do this i get the following error and i don't know why:

Type 'userProfile?' has no member 'firstname'

how di i fix this?

Body:
Here is a fix (you tried to access class, but should be instance) :

 var user: userProfile? {
      didSet {
          let fullName = user?.firstname // << here !!

          firstname.text = fullName    // I can't say if this valid
     }
 }

To avoid such ambiguity you should follow a rule to name classes in UpperCase, ie. in you case UserProfile.


问:
How to findByIdAndUpdate() without deleting existing data?
Let's say I have a mongoose Person model that looks like this:

```<code>const PersonSchema = new mongoose.Schema({
    name: String,
    address: {
        street: String,
        number: number
    }
});
</code>```

Then I have a method for updating people's info, like this:

```<code>const updatePerson = async (req, res) => {
    const updatedPerson = await Person.findByIdAndUpdate(req.params.id, req.body, { new: true });
    return updatedPerson;
}
</code>```

So far, so good. Now let's say I have this record in my database:

```<code>{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Freddy",
    "address": {
         "street": "Elm Street",
         "number": 42
    }
}
</code>```

And I want to update the name and the street, so I send this request:

```<code>{ "name": "Ryu", "address": { "street": "fighter" } }
</code>```

My document will become like this:

```<code>{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Ryu",
    "address": { "street": "fighter" }
}
</code>```

In other words, the "number" property was deleted from the record. Since I didn't provide a value for "number" in my request, the original one was overwritten by undefined. Is there any way I can preserve existing data with the .findByIdAndUpdate() method?

I know you can do this with .findById(), updating what you need "manually" and then calling .save(), but I guess it would be more elegant if you could pass some option to .findByIdAndUpdate() instead.

答:
try this </p>

```<code>Person.findByIdAndUpdate(req.params.id,{$set:
{'fieldtoupdate1':newvalue1,'fieldtoupdate2':newvalue2}}).exec()
</code>```

Body:
Let's say I have a mongoose Person model that looks like this:

const PersonSchema = new mongoose.Schema({
    name: String,
    address: {
        street: String,
        number: number
    }
});

Then I have a method for updating people's info, like this:

const updatePerson = async (req, res) => {
    const updatedPerson = await Person.findByIdAndUpdate(req.params.id, req.body, { new: true });
    return updatedPerson;
}

So far, so good. Now let's say I have this record in my database:

{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Freddy",
    "address": {
         "street": "Elm Street",
         "number": 42
    }
}

And I want to update the name and the street, so I send this request:

{ "name": "Ryu", "address": { "street": "fighter" } }

My document will become like this:

{
    "_id": "5ed2918bc96be94f130e1354",
    "name": "Ryu",
    "address": { "street": "fighter" }
}

In other words, the "number" property was deleted from the record. Since I didn't provide a value for "number" in my request, the original one was overwritten by undefined. Is there any way I can preserve existing data with the .findByIdAndUpdate() method?

I know you can do this with .findById(), updating what you need "manually" and then calling .save(), but I guess it would be more elegant if you could pass some option to .findByIdAndUpdate() instead.

Body:
try this

Person.findByIdAndUpdate(req.params.id,{$set:
{'fieldtoupdate1':newvalue1,'fieldtoupdate2':newvalue2}}).exec()


问:
Nginx redirects subdomain foo to www.foo to www.www.foo etc
I just changed my config from a regular to a wildcard certificate. Now my nginx is misbehaving.

```<code># redirect http to https
server {
  listen      80 default_server;
  listen      [::]:80 default_server;
  return      301 https://$host$request_uri;
}

# redirect naked to www
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name example.com;
  include     ssl.conf;
  return      301 https://www.$host$request_uri;
}

# serve subdomain www
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name www.example.com;
  include     ssl.conf;
  # ...
}

# serve subdomain mmm
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name mmm.example.com;
  include     ssl.conf;
  # ...
}

# ...etc.
</code>```

The above works, but fails for non-existent subdomains (instead of returning 404). So if I try notexist.example.com it will redirect me to www.notexist.example.com and give me a certificate warning. If I click ok, it will redirect to www.www.notexist.example.com, and then www.www.www.notexist.example.com, etc.

What am I doing wrong?

答:
Since you want to catch all non-existent subdomains you need an extra server block at the end, marked as default - like listen 443 ssl default_server; The server_name for this block does not matter - as long as it does not match any of the other server blocks (so you can simply use server_name _;)

Any domain that is not already handled by another server block will be handled by the default one - you can either redirect to your canonical domain or just return 404.

Body:
I just changed my config from a regular to a wildcard certificate. Now my nginx is misbehaving.

# redirect http to https
server {
  listen      80 default_server;
  listen      [::]:80 default_server;
  return      301 https://$host$request_uri;
}

# redirect naked to www
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name example.com;
  include     ssl.conf;
  return      301 https://www.$host$request_uri;
}

# serve subdomain www
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name www.example.com;
  include     ssl.conf;
  # ...
}

# serve subdomain mmm
server {
  listen      443 ssl http2;
  listen      [::]:443 ssl http2;
  server_name mmm.example.com;
  include     ssl.conf;
  # ...
}

# ...etc.

The above works, but fails for non-existent subdomains (instead of returning 404). So if I try notexist.example.com it will redirect me to www.notexist.example.com and give me a certificate warning. If I click ok, it will redirect to www.www.notexist.example.com, and then www.www.www.notexist.example.com, etc.

What am I doing wrong?


问:
Convert array to list by using dictionary
if you have an array, and you want to convert it by using your defined dictionary, how do you do?
input:

```<code>my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
x=np.array(2,6,8,1,.....)
</code>```

output:

```<code>y=("F","J","A","J",.....)
</code>```

We have tried this:

```<code>my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
a = np.empty(len(x))
for i in range(0,len(x)):
    b=my_dict[x[i,0]]
    a[i,0]=b
</code>```

答:
dict.get() won't throw KeyNotFoundError exception if the key doesn't exist.

```<code>my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}

# With KeyNotFoundError handled
x=[my_dict.get(i) for i in [2,6,8,1,10,11]]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
if you have an array, and you want to convert it by using your defined dictionary, how do you do?
input:

my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
x=np.array(2,6,8,1,.....)

output:

y=("F","J","A","J",.....)

We have tried this:

my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}
a = np.empty(len(x))
for i in range(0,len(x)):
    b=my_dict[x[i,0]]
    a[i,0]=b

Body:
dict.get() won't throw KeyNotFoundError exception if the key doesn't exist.

my_dict = {1 : 'J',2:'F', 3:'M',4: 'A',5: 'M',6 : 'J',7:'J', 8:'A',9: 'S',10: '0',11 : 'N',12:'D'}

# With KeyNotFoundError handled
x=[my_dict.get(i) for i in [2,6,8,1,10,11]]


问:
error: expected color but got (raw string) color/gray
I have switched to android studio 3. after many problem that I fixed, I got this error:

color/colorPrimary but i go this error:Error:(87, 5) error: expected color but got (raw string) color/gray

答:
Color value should be a hex color code like #A5D3F4 OR a color reference with @ sign, like  @color/colorPrimary. before use these reference, you must create resources like res/values/color.xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
    <color name="LabelColor_text_50">#FFFFFF</color>
    <color name="ValueColor_text_50">#333322</color>
    <color name="LabelColor_bg_50">#A5D3F4</color>
    <color name="ValueColor_bg_50">#E6EEF4</color>
</resources>
</code>```

And use these name as <item name="someName">@color/LabelColor_text_50</item>

Body:
Color value should be a hex color code like #A5D3F4 OR a color reference with @ sign, like  @color/colorPrimary. before use these reference, you must create resources like res/values/color.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
    <color name="LabelColor_text_50">#FFFFFF</color>
    <color name="ValueColor_text_50">#333322</color>
    <color name="LabelColor_bg_50">#A5D3F4</color>
    <color name="ValueColor_bg_50">#E6EEF4</color>
</resources>

And use these name as <item name="someName">@color/LabelColor_text_50</item>


答:
One solution to your problem is to update the object's property directly by setting its value and not setting the object to a new object.

Old:

```<code>{ "name": "Ryu", "address": { "street": "fighter" } }
</code>```

New:

```<code>{ "name": "Ryu", "address.street": "fighter" }
</code>```

Title: How to findByIdAndUpdate() without deleting existing data?

Body:
One solution to your problem is to update the object's property directly by setting its value and not setting the object to a new object.

Old:

{ "name": "Ryu", "address": { "street": "fighter" } }

New:

{ "name": "Ryu", "address.street": "fighter" }


问:
Problem to save picture to mediaLibrary with expo
i'm completly new to react and react native too, but i'm trying to learn it.

I'm having a problem when i try to save picture to my phone gallery

So, i'm importing

```<code>import { MediaLibrary } from 'expo-media-library'
</code>```

also i'm usigng states

```<code>const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [cameraRef, setCameraRef] = useState(null)
</code>```

and here all works fine except saving the photo

```<code><TouchableOpacity style={{alignSelf: 'center'}} onPress={async() => {
            if(cameraRef){
              let photo = await cameraRef.takePictureAsync();
              console.log('photo', photo);
              MediaLibrary.saveToLibraryAsync(photo.uri)

            }
          }}>
</code>```

in my console log i see the object

```<code>    photo Object {
     "height": 4156,
     "uri": "file:///var/mobile/Containers/Data/Application/B7CCEDB6-DFC5-4898-BD70-B2FF1159FC1B/Library/Caches/ExponentExperienceData/%2540anonymous%252Ftest-5bfa90d8-12e9-44fe-a19d-69bb5eeb74b9/Camera/D783C734-29B9-489B-9798-A0737388E93C.jpg",
     "width": 2376,
}
</code>```

But i'm not able to find a way to save it to camera roll, i'm always getting this error

```<code>[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_expoMediaLibrary.MediaLibrary.saveToLibraryAsync')]
</code>```

Any help would be appreciate

R.

答:
I think you're getting undefined object error with promise since you did not also concerned MediaLibrary.saveToLibraryAsync() with await.

You should maybe put MediaLibrary.saveToLibraryAsync() with await too just like you did on takePictureAsync() since it is a async function.

```<code>let photo = await cameraRef.takePictureAsync();
console.log('photo', photo);
await MediaLibrary.saveToLibraryAsync(photo.uri);
</code>```

Just an assumption, hope it will help you to solve it.

Body:
i'm completly new to react and react native too, but i'm trying to learn it.

I'm having a problem when i try to save picture to my phone gallery

So, i'm importing

import { MediaLibrary } from 'expo-media-library'

also i'm usigng states

const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [cameraRef, setCameraRef] = useState(null)

and here all works fine except saving the photo

<TouchableOpacity style={{alignSelf: 'center'}} onPress={async() => {
            if(cameraRef){
              let photo = await cameraRef.takePictureAsync();
              console.log('photo', photo);
              MediaLibrary.saveToLibraryAsync(photo.uri)

            }
          }}>

in my console log i see the object

    photo Object {
     "height": 4156,
     "uri": "file:///var/mobile/Containers/Data/Application/B7CCEDB6-DFC5-4898-BD70-B2FF1159FC1B/Library/Caches/ExponentExperienceData/%2540anonymous%252Ftest-5bfa90d8-12e9-44fe-a19d-69bb5eeb74b9/Camera/D783C734-29B9-489B-9798-A0737388E93C.jpg",
     "width": 2376,
}

But i'm not able to find a way to save it to camera roll, i'm always getting this error

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_expoMediaLibrary.MediaLibrary.saveToLibraryAsync')]

Any help would be appreciate

R.

Body:
I think you're getting undefined object error with promise since you did not also concerned MediaLibrary.saveToLibraryAsync() with await.

You should maybe put MediaLibrary.saveToLibraryAsync() with await too just like you did on takePictureAsync() since it is a async function.

let photo = await cameraRef.takePictureAsync();
console.log('photo', photo);
await MediaLibrary.saveToLibraryAsync(photo.uri);

Just an assumption, hope it will help you to solve it.


问:
Silverlight and unsafe code
I know there is no direct way to have unsafe code in silverlight C# code but nothing really stops us from having unsafe code in a WCF service, and then referencing this service from Silverlight, yes? Probably not the ideal thing to do but has anyone ever needed to do such a thing? I'm thinking I may need this but not sure of any other way to get around it, especially since the code I need to acces is writtenin C++.

THanks much

答: As you said, there's nothing stopping you from using unsafe code on the server-side.</p>

Title: Silverlight and unsafe code


问:
Fill missing values based unique IDs from another column
I have a data frame with User ID and a Device Model values

The User ID is unique for each user however there are duplicates for multiple logins and there are no missing values
Device Model has missing value

I need to address the same device model for users that has the same User ID. Like This:

```<code>    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   NAN         1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   NAN         1590761773215-7300441

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441
</code>```

Does anybody knows how to solve this? I tried to use join (below) but it didnt work and I dont know any other solution for this

```<code>join_df_device = pd.merge(device_model_df,device_type_nonull,on ='Device Model',how ='left')
</code>```

join_df_device

答:
Although Ch3steR's answer is easier in this case, here's a solution with merging as you tried:

```<code>df[['User ID']].merge(df.dropna().drop_duplicates(), on='User ID')
</code>```

Result:

```<code>                 User ID Device Model
0  1590761773215-7300441    iPhone 11
1  1590761773215-7300441    iPhone 11
2  1590761549649-1399336    iPhone XR
3  1590761549649-1399336    iPhone XR
4  1589030810407-6386535     iPhone 7
</code>```

Body:
I have a data frame with User ID and a Device Model values

The User ID is unique for each user however there are duplicates for multiple logins and there are no missing values
Device Model has missing value

I need to address the same device model for users that has the same User ID. Like This:

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   NAN         1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   NAN         1590761773215-7300441

    Device Model        User ID

0   iPhone 11   1590761773215-7300441
1   iPhone XR   1590761549649-1399336
2   iPhone XR   1590761549649-1399336
3   iPhone 7    1589030810407-6386535
4   iPhone 11   1590761773215-7300441

Does anybody knows how to solve this? I tried to use join (below) but it didnt work and I dont know any other solution for this

join_df_device = pd.merge(device_model_df,device_type_nonull,on ='Device Model',how ='left')

join_df_device

Body:
Although Ch3steR's answer is easier in this case, here's a solution with merging as you tried:

df[['User ID']].merge(df.dropna().drop_duplicates(), on='User ID')

Result:

                 User ID Device Model
0  1590761773215-7300441    iPhone 11
1  1590761773215-7300441    iPhone 11
2  1590761549649-1399336    iPhone XR
3  1590761549649-1399336    iPhone XR
4  1589030810407-6386535     iPhone 7


问:
Kendo datepicker select today onward only
I had this date range in here, but I want date from only can select today and onward only.
Meaning I cannot select date previous than today.

dateFrom >= today and dateUntil >= dateFrom

FULL DEMO

答: You can use min property of datepicker which will set the minimal date range. Updated dojo is here.</p>


问:
is there a way to convert a json object to json l file
I have an array of objects. I need to convert it in .jsonl format and send it as response using node in a lambda function
i have been trying to change it as a string and add '\n' to make it a new line but it didn't work </p>

答:
Simple code to generate jsonlines.  jsonlines is really just a bunch of one-line JSON objects stringified and concatenated with newlines between them.  That's it.

The other issue you will need to deal with is escaping unicode, so when you write to a file, you must use UTF-8 encoding.

repl.it demo using jsonlines npm library: https://repl.it/repls/AngelicGratefulMoto

Simple plain JS demo:

data = [{ jsonlines: 'is awesome' },{ jsonlines: 'is awesome' },{ jsonlines: 'is awesome' },{ jsonlines: 'is awesome' },{ jsonlines: 'is awesome' }]

console.log(
data.map(x=>JSON.stringify(x)).join('\n')
)```


问:
Python 3: obtain struct.pack output that matches Python 2 struct.pack output
In Python 2:

```<code>import struct
struct.pack('B', 21)[0] # returns '\x15'
</code>```

In Python 3:

```<code>import struct
struct.pack('B', 21)[0] # returns 21
</code>```

Is there some way to create the byte string returned by Python 2 in Python 3? Any pointers would be greatly appreciated!

答:
Just don't index the byte string it returns:</p>

```<code>>>> struct.pack('B', 21)
b'\x15'
</code>```

Body:
In Python 2:

import struct
struct.pack('B', 21)[0] # returns '\x15'

In Python 3:

import struct
struct.pack('B', 21)[0] # returns 21

Is there some way to create the byte string returned by Python 2 in Python 3? Any pointers would be greatly appreciated!

Body:
Just don't index the byte string it returns:

>>> struct.pack('B', 21)
b'\x15'


问:
raycaster in threejs only selects a single part of my gltf model at a time
Hi there I am completely new to three.js so any help is appreciated.

I have a gltf model in which many parts make a single model. I want to select the model as a whole but when I am using raycaster to select the model I am selecting those individual parts.

Example: Let's say I have a cube when I am hovering over it only a single face is getting selected at a time.

below is my code... Any help is appreciated

```<code>    var raycaster = new Raycaster();

    loader.load("Purplelogo/Purplelogo.gltf", ( gltf ) => {

    scene.add( gltf.scene );

    gltf.scene.position.set(2,-0.9,1);
    gltf.scene.scale.set(0.9,0.9,0.9);
    gltf.scene.rotation.set(2,2,5);

  });

  raycaster.setFromCamera( mouse, camera );

  var intersects2 = raycaster.intersectObjects( scene2.children, true );

  for ( var i = 0; i < intersects2.length; i++ ) {

    intersects2[ i ].object.rotateX(3)

  }
</code>```

答:
You need to somehow find the root of the file. You can do that in 1000 different ways.

Here's one

```<code>let obj = intersects2[ i ].object;

// walk up until you get to the root of the gltf file
while (obj !== gltf.scene && obj.parent) {
  obj = obj.parent;
}

if (obj === gltf.scene) {
  // it's the root of the scene
</code>```

Here's another

```<code>// at load time
const allMeshesInGLTF = new Set();
gltf.scene.traverse(node => {
  if (node.isMesh) {
    allMeshesInGLTF.add(node);
  }
});

// then at pick time
let obj = intersects2[ i ].object;
if (allMeshesInGLTF.has(obj)) {
  // an object in the scene picked, use gltf.scene
</code>```

Here's another

```<code>// at load time
gltf.scene.traverse(node => {
  if (node.isMesh) {
    node.gltf = gltf;
  }
});

// at pick time
let obj = intersects2[ i ].object;
if (obj.gltf) {
  // use obj.gltf.scene

</code>```

etc...

Body:
Hi there I am completely new to three.js so any help is appreciated.

I have a gltf model in which many parts make a single model. I want to select the model as a whole but when I am using raycaster to select the model I am selecting those individual parts.

Example: Let's say I have a cube when I am hovering over it only a single face is getting selected at a time.

below is my code... Any help is appreciated

    var raycaster = new Raycaster();

    loader.load("Purplelogo/Purplelogo.gltf", ( gltf ) => {

    scene.add( gltf.scene );

    gltf.scene.position.set(2,-0.9,1);
    gltf.scene.scale.set(0.9,0.9,0.9);
    gltf.scene.rotation.set(2,2,5);

  });

  raycaster.setFromCamera( mouse, camera );

  var intersects2 = raycaster.intersectObjects( scene2.children, true );

  for ( var i = 0; i < intersects2.length; i++ ) {

    intersects2[ i ].object.rotateX(3)

  }

Body:
You need to somehow find the root of the file. You can do that in 1000 different ways.

Here's one

let obj = intersects2[ i ].object;

// walk up until you get to the root of the gltf file
while (obj !== gltf.scene && obj.parent) {
  obj = obj.parent;
}

if (obj === gltf.scene) {
  // it's the root of the scene

Here's another

// at load time
const allMeshesInGLTF = new Set();
gltf.scene.traverse(node => {
  if (node.isMesh) {
    allMeshesInGLTF.add(node);
  }
});

// then at pick time
let obj = intersects2[ i ].object;
if (allMeshesInGLTF.has(obj)) {
  // an object in the scene picked, use gltf.scene

Here's another

// at load time
gltf.scene.traverse(node => {
  if (node.isMesh) {
    node.gltf = gltf;
  }
});

// at pick time
let obj = intersects2[ i ].object;
if (obj.gltf) {
  // use obj.gltf.scene

etc...


问:
Django | Error when insert imageName with for into static url
Error when we want to insert image file name into static url. No all has imageName.

Error:

Invalid block tag

Code:

```<code><img width="40%" src="{% static 'files/img/
{% for i in questions %}
  {% i.imageName %}
{% endfor %}
' %}">
</code>```

答:
This isn't built into Django but you can try something along these lines.</p>

```<code>files = os.listdir(os.path.join(settings.STATIC_ROOT, "files/img"))

{% for file in files %}
    <img width="40%" src="{{file}}">
{% endfor %}
</code>```

Body:
This isn't built into Django but you can try something along these lines.

files = os.listdir(os.path.join(settings.STATIC_ROOT, "files/img"))

{% for file in files %}
    <img width="40%" src="{{file}}">
{% endfor %}


问:
c++ function to find the sum of four minimum maximum elements in an array not working
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

```<code>void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}
</code>```

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.

答:
Assuming you can use the standard library:

void miniMaxSum(const std::vector<int> & arr) {
  std::array<int, 4> small_numbers;
  std::partial_sort_copy(arr.begin(), arr.end(),
                         small_numbers.begin(), small_numbers.end(),
                         std::less<int>());

  std::array<int, 4> large_numbers;
  std::partial_sort_copy(arr.begin(), arr.end(),
                         large_numbers.begin(), large_numbers.end(),
                         std::greater<int>());

  std::cout << std::accumulate(small_numbers.begin(), small_numbers.end(), 0)
            << " "
            << std::accumulate(large_numbers.begin(), large_numbers.end(), 0)
            << std::endl;
}
```

Shown to work on https://repl.it/repls/EntireTornBotany

Body:
I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.

here is my code:

void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}

this code gives the correct output for maxsum but the minsum is wrong in all the testcases.
please help me find the error in the code
Thanks in advance.

Body:
Assuming you can use the standard library:

void miniMaxSum(const std::vector<int> & arr) {
  std::array<int, 4> small_numbers;
  std::partial_sort_copy(arr.begin(), arr.end(),
                         small_numbers.begin(), small_numbers.end(),
                         std::less<int>());

  std::array<int, 4> large_numbers;
  std::partial_sort_copy(arr.begin(), arr.end(),
                         large_numbers.begin(), large_numbers.end(),
                         std::greater<int>());

  std::cout << std::accumulate(small_numbers.begin(), small_numbers.end(), 0)
            << " "
            << std::accumulate(large_numbers.begin(), large_numbers.end(), 0)
            << std::endl;
}

Shown to work on https://repl.it/repls/EntireTornBotany


问:
Need to add Spaces at certain Indexes
So this is data i have,

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
</code>```

These are the index position where i need to add spaces,

```<code>d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
</code>```

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction
```

<p>and so on.....</p>

<p>I have calculated the indexes by doing this,</p>

```s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
```

<p>When I individually try and add the space using the index, I get an output,</p>

```d[0:s[0]] + ' ' + d[s[0]:]
```

<p>I get the following, which is correct</p>

<pre class="lang-none prettyprint-override"><code>'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube
</code>```

But, when I try and iterate over the indexes, i get List out of Range

```<code>temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range
</code>```

答:
You can transform the string to list and then insert spaces and then transform back.

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
d = list(d)
for index,i in enumerate(s):
    d.insert(index + i, " ")
d = ''.join(d)
print(d)
</code>```

Output:

```<code>CC Carbon CopyCAI Computer Aided InstructionCDMA Code Division Multiple AccessCRT Cathode Ray TubeCAD Computer Aided DesignCADD Computer Aided Design DraftingCD Compact DiskCDRW Compact Disk RewritableCAM Computer Aided ManufacturingCROM Computerized Range MotionCDROMCompactDiskReadOnlyMemory
</code>```

Title: Need to add Spaces at certain Indexes

Body:
So this is data i have,

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]

These are the index position where i need to add spaces,

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction

and so on.....

I have calculated the indexes by doing this,

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

When I individually try and add the space using the index, I get an output,

d[0:s[0]] + ' ' + d[s[0]:]

I get the following, which is correct

'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube

But, when I try and iterate over the indexes, i get List out of Range

temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range

Body:
You can transform the string to list and then insert spaces and then transform back.

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
d = list(d)
for index,i in enumerate(s):
    d.insert(index + i, " ")
d = ''.join(d)
print(d)

Output:

CC Carbon CopyCAI Computer Aided InstructionCDMA Code Division Multiple AccessCRT Cathode Ray TubeCAD Computer Aided DesignCADD Computer Aided Design DraftingCD Compact DiskCDRW Compact Disk RewritableCAM Computer Aided ManufacturingCROM Computerized Range MotionCDROMCompactDiskReadOnlyMemory


问:
I don't see team in Xcode I'm member of
This question could be a duplicate of this one - SO Question but that question was asked 2 years ago and didn't get answered. Also, there were many questions related to this issues even before, but they are outdated now.

So, I got invited to an Apple Developer account with a role of Admin and I don't see that team in Xcode, that person, who invited me has individual account. Moreover, I'm a member of other developer accounts and I can see them and use. But that accounts are of organisation types.

If anyone faced same issue - how can I fix that?
Simply logging out of account in Xcode and relaunching/restarting Mac didn't help.

答:
I'm going to guess that what the account holder actually did was this (as described by the docs):

Individuals enrolled in the Apple Developer Program can give up to 10 users access to their content in App Store Connect. All users receive access only to App Store Connect and are not considered part of the team in the Apple Developer Program.

That sounds like exactly your situation as you describe it.

Title: I don't see team in Xcode I'm member of


问:
How to reload the current page once without changing the URL in javascript?
I am using the following javascript code to set a language cookie for users when they visit my site:

```<code>function setCookie(name, value, expires) {
    var expires = "";
    if(expires) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while(c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if(c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
function delCookie(name) {
    document.cookie = name+'=; expires=Wed, 31 Dec 1969 23:59:59 GMT; path=/'; // expires=-1
}

// After the page has finished loading, check that the user already has a language cookie?
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) { // If not, set language cookie
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
    }
    if(getCookie('language')) { // If the user already has a language cookie
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') { // If the user's language cookie is not supported
            setCookie('language', 'en'); // Then use English as the default
        }
    }
}, false);
</code>```

Now, I want after setting the language cookie for the user, the current page will be reloaded once without changing the URL (without adding the hash #, parameter,...).

I tried setting the cookie, then using location.reload(), once reloading will delete that cookie as follows:

```<code>// ... Skip Cookie Code ...
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
            setCookie('needreload', 'yes');
        }
        else {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('language')) {
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('needreload') == 'yes') {
        location.reload();
        delCookie('needreload');
    }
}, false);
</code>```

However, that makes my website reload constantly, infinite times instead of just once.

Please show me the method to solve this problem. I would appreciate the solution you give!

答:
Try setting value of needreload cookie to "no" before you do location.reload()

```<code>if(getCookie('needreload') == 'yes') {
        setCookie('needreload', 'no');
        location.reload();
        delCookie('fc_reload');
      //im not sure delCookie fc_reload will be executed
      //as page will pe refreshed and control goes off
 }
</code>```

Body:
I am using the following javascript code to set a language cookie for users when they visit my site:

function setCookie(name, value, expires) {
    var expires = "";
    if(expires) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while(c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if(c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
function delCookie(name) {
    document.cookie = name+'=; expires=Wed, 31 Dec 1969 23:59:59 GMT; path=/'; // expires=-1
}

// After the page has finished loading, check that the user already has a language cookie?
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) { // If not, set language cookie
        if(lang == 'vi') {
            setCookie('language', 'vi');
        }
        else {
            setCookie('language', 'en');
        }
    }
    if(getCookie('language')) { // If the user already has a language cookie
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') { // If the user's language cookie is not supported
            setCookie('language', 'en'); // Then use English as the default
        }
    }
}, false);

Now, I want after setting the language cookie for the user, the current page will be reloaded once without changing the URL (without adding the hash #, parameter,...).

I tried setting the cookie, then using location.reload(), once reloading will delete that cookie as follows:

// ... Skip Cookie Code ...
document.addEventListener('DOMContentLoaded', function() {
    var lang = navigator.language || navigator.browserLanguage || navigator.userLanguage || navigator.systemLanguage;
    lang = lang.slice(0, 2).toLowerCase();
    if(!getCookie('language')) {
        if(lang == 'vi') {
            setCookie('language', 'vi');
            setCookie('needreload', 'yes');
        }
        else {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('language')) {
        if(getCookie('language') != 'vi' || getCookie('language') != 'en') {
            setCookie('language', 'en');
            setCookie('needreload', 'yes');
        }
    }
    if(getCookie('needreload') == 'yes') {
        location.reload();
        delCookie('needreload');
    }
}, false);

However, that makes my website reload constantly, infinite times instead of just once.

Please show me the method to solve this problem. I would appreciate the solution you give!

Body:
Try setting value of needreload cookie to "no" before you do location.reload()

if(getCookie('needreload') == 'yes') {
        setCookie('needreload', 'no');
        location.reload();
        delCookie('fc_reload');
      //im not sure delCookie fc_reload will be executed
      //as page will pe refreshed and control goes off
 }


问:
Widget in Listview.builder do not space evenly in Row

I build a row of date with ListView.builder, each listview is a column with Day and Date.
I want it to space evenly in the Row, but mainAxisAlignment: MainAxisAlignment.spaceEvenly seems only centred the listview :/

Another question is why do I need to wrap the listview builder with a fixed height?
It worked but I don't think this is the best approach.

Thanks everyone in advance.

```<code>import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class TimeSlot extends StatefulWidget {
  @override
  _TimeSlotState createState() => _TimeSlotState();
}

class _TimeSlotState extends State<TimeSlot> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: 55,
          child: ListView.builder(
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              itemCount: 8,
              itemBuilder: (context, i) {
                final weekDay = DateTime.now().add(
                  Duration(days: i),
                );
                final day = DateFormat.E().format(weekDay).substring(0, 2);
                final date = DateFormat.d().format(weekDay);
                return Column(
                  children: <Widget>[
                    Text(
                      day,
                      style: TextStyle(
                        color: Color.fromRGBO(30, 41, 51, 0.5),
                      ),
                    ),
                    SizedBox(
                      height: 7,
                    ),
                    CircleAvatar(
                      backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                      radius: 14,
                      child: CircleAvatar(
                        backgroundColor: Colors.white,
                        child: Text(
                          date,
                          style: TextStyle(color: Colors.black, fontSize: 12),
                        ),
                        radius: 13,
                      ),
                    ),
                  ],
                );
              }),
        ),
      ],
    );
  }
}
</code>```

答:
Row checks all the children inside and then with the mainAxisAlignment.SpaceEvenly property it gives the correct space between them, the problem is that Row only detects one child inside, ListView.Builder (well the container wrapping the listview), even if the Listview has X amount of children, row only know he has one listview so it doesn't do anything. You either use row or listview.builder. This is an example using only Row and building the children inside with a for (and because they are in the children list of the row, now row can detect them and apply the correct mainAxisAlignment)</p>

```<code>class TimeSlot extends StatefulWidget {
  @override
  _TimeSlotState createState() => _TimeSlotState();
}

class _TimeSlotState extends State<TimeSlot> {

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        for(int i = 0; i <= 8; i++)
        SingleDate(DateTime.now().add(Duration(days: i)))
      ],
    );
  }
}

class SingleDate extends StatelessWidget{
   final DateTime weekDay;

   SingleDate(this.weekDay);

   @override
   Widget build(BuildContext context){
     final day = MaterialLocalizations.of(context)
                .formatMediumDate(weekDay)
                .substring(
                    0,
                    MaterialLocalizations.of(context)
                        .formatMediumDate(weekDay)
                        .indexOf(','));
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  day,
                  style: TextStyle(
                    color: Color.fromRGBO(30, 41, 51, 0.5),
                  ),
                ),
                SizedBox(
                  height: 7,
                ),
                CircleAvatar(
                  backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                  radius: 14,
                  child: CircleAvatar(
                    backgroundColor: Colors.white,
                    child: Text(
                      weekDay.day.toString(),
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                    radius: 13,
                  ),
                ),
              ],
            );
   }

}
</code>```

Body:
I build a row of date with ListView.builder, each listview is a column with Day and Date.
I want it to space evenly in the Row, but mainAxisAlignment: MainAxisAlignment.spaceEvenly seems only centred the listview :/

Another question is why do I need to wrap the listview builder with a fixed height?
It worked but I don't think this is the best approach.

Thanks everyone in advance.

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class TimeSlot extends StatefulWidget {
  @override
  _TimeSlotState createState() => _TimeSlotState();
}

class _TimeSlotState extends State<TimeSlot> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: 55,
          child: ListView.builder(
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              itemCount: 8,
              itemBuilder: (context, i) {
                final weekDay = DateTime.now().add(
                  Duration(days: i),
                );
                final day = DateFormat.E().format(weekDay).substring(0, 2);
                final date = DateFormat.d().format(weekDay);
                return Column(
                  children: <Widget>[
                    Text(
                      day,
                      style: TextStyle(
                        color: Color.fromRGBO(30, 41, 51, 0.5),
                      ),
                    ),
                    SizedBox(
                      height: 7,
                    ),
                    CircleAvatar(
                      backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                      radius: 14,
                      child: CircleAvatar(
                        backgroundColor: Colors.white,
                        child: Text(
                          date,
                          style: TextStyle(color: Colors.black, fontSize: 12),
                        ),
                        radius: 13,
                      ),
                    ),
                  ],
                );
              }),
        ),
      ],
    );
  }
}

Body:
Row checks all the children inside and then with the mainAxisAlignment.SpaceEvenly property it gives the correct space between them, the problem is that Row only detects one child inside, ListView.Builder (well the container wrapping the listview), even if the Listview has X amount of children, row only know he has one listview so it doesn't do anything. You either use row or listview.builder. This is an example using only Row and building the children inside with a for (and because they are in the children list of the row, now row can detect them and apply the correct mainAxisAlignment)

class TimeSlot extends StatefulWidget {
  @override
  _TimeSlotState createState() => _TimeSlotState();
}

class _TimeSlotState extends State<TimeSlot> {

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        for(int i = 0; i <= 8; i++)
        SingleDate(DateTime.now().add(Duration(days: i)))
      ],
    );
  }
}

class SingleDate extends StatelessWidget{
   final DateTime weekDay;

   SingleDate(this.weekDay);

   @override
   Widget build(BuildContext context){
     final day = MaterialLocalizations.of(context)
                .formatMediumDate(weekDay)
                .substring(
                    0,
                    MaterialLocalizations.of(context)
                        .formatMediumDate(weekDay)
                        .indexOf(','));
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  day,
                  style: TextStyle(
                    color: Color.fromRGBO(30, 41, 51, 0.5),
                  ),
                ),
                SizedBox(
                  height: 7,
                ),
                CircleAvatar(
                  backgroundColor: Color.fromRGBO(240, 242, 245, 1),
                  radius: 14,
                  child: CircleAvatar(
                    backgroundColor: Colors.white,
                    child: Text(
                      weekDay.day.toString(),
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                    radius: 13,
                  ),
                ),
              ],
            );
   }

}


问:
Unable to cast object of type 'System.DBNull' to type 'System.Type'
I have a PowerShell script trying to run a sql command using Invoke-Sqlcmd but I get the following exception:

```<code>Invoke-Sqlcmd : The pipeline has been stopped.
At D:\Scripts\powersehelscript.ps1:57 char:9
+ $rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is  null;"  ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], PipelineStoppedException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptComman
 Invoke-Sqlcmd : Unable to cast object of type 'System.DBNull' to type
'System.Type'.
At D:\Scripts\MyScript.ps1:57 char:9
+ $rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is null;"  ...
</code>```

my sql command looks like this:

```<code>$rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is null;" -Database $Database -ServerInstance $SqlServer -Username $U -Password $P
</code>```

It seems to be connecting fine to the Database and if I run the same query directly in the DB i get the results back.

From the exception I see "Unable to cast object of type 'System.DBNull' to type" but I have no clue why this casting issue is occurring

答: In case anyone reading this is looking for other conclusions, I had exact same issue of PowerShell same error and it grinding down to a single geo column.  I was simply writing some code to grab the table and export once a week for easy user reference. The Add-Type solution didn't change my outcome.  What worked for me was, in the SQL cmd, using CAST(mygeocol AS varchar(100)).  Conveniently, in SQL & PS, that brought it back to a format like "POINT (-90.1234 30.1234)" and worked great.  Hope it helps someone!</p>

Body:
I have a PowerShell script trying to run a sql command using Invoke-Sqlcmd but I get the following exception:

Invoke-Sqlcmd : The pipeline has been stopped.
At D:\Scripts\powersehelscript.ps1:57 char:9
+ $rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is  null;"  ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], PipelineStoppedException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptComman
 Invoke-Sqlcmd : Unable to cast object of type 'System.DBNull' to type
'System.Type'.
At D:\Scripts\MyScript.ps1:57 char:9
+ $rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is null;"  ...

my sql command looks like this:

$rows = Invoke-Sqlcmd -Query "SELECT * from TableName where location is null;" -Database $Database -ServerInstance $SqlServer -Username $U -Password $P

It seems to be connecting fine to the Database and if I run the same query directly in the DB i get the results back.

From the exception I see "Unable to cast object of type 'System.DBNull' to type" but I have no clue why this casting issue is occurring


答:
try:</p>

```<code>{% for i in questions %}
<img width="40%" src="{% static 'files/img/{{i.imageName}}' %}">
{% endfor %}
</code>```

Title: Django | Error when insert imageName with for into static url

Body:
Error when we want to insert image file name into static url. No all has imageName.

Error:

Invalid block tag

Code:

Body:
try:

{% for i in questions %}
<img width="40%" src="{% static 'files/img/{{i.imageName}}' %}">
{% endfor %}


问:
How to hide a text and make it accessible by screen reader?
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

```<code><span class="aria-invisible" aria-live="polite">5 selections have been made.</span>

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}
</code>```

答:
I did encounter this problem in the past.
Bootstrap has this sweet class sr-only that actually hides the content on the webpage but is accessible by the screen readers. You can check this link

Moreover, if you are not using bootstrap, you can simply implement the class yourself in your code.

.aria-invisible {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="aria-invisible">5 selections have been made. </span></code>```

I hope this helps.

Body:
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

5 selections have been made.

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}

Body:
I did encounter this problem in the past.
Bootstrap has this sweet class sr-only that actually hides the content on the webpage but is accessible by the screen readers. You can check this link

Moreover, if you are not using bootstrap, you can simply implement the class yourself in your code.

.aria-invisible {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }

<span class="aria-invisible">5 selections have been made. </span>

I hope this helps.


问:
LSTM cell implementation in Pytorch design choices
I was looking for an implementation of an LSTM cell in Pytorch that I could extend, and I found an implementation of it in the accepted answer here. I will post it here because I'd like to refer to it. There are quite a few implementation details that I do not understand, and I was wondering if someone could clarify.

```<code>import math
import torch as th
import torch.nn as nn

class LSTM(nn.Module):

    def __init__(self, input_size, hidden_size, bias=True):
        super(LSTM, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.bias = bias
        self.i2h = nn.Linear(input_size, 4 * hidden_size, bias=bias)
        self.h2h = nn.Linear(hidden_size, 4 * hidden_size, bias=bias)
        self.reset_parameters()

    def reset_parameters(self):
        std = 1.0 / math.sqrt(self.hidden_size)
        for w in self.parameters():
            w.data.uniform_(-std, std)

    def forward(self, x, hidden):
        h, c = hidden
        h = h.view(h.size(1), -1)
        c = c.view(c.size(1), -1)
        x = x.view(x.size(1), -1)

        # Linear mappings
        preact = self.i2h(x) + self.h2h(h)

        # activations
        gates = preact[:, :3 * self.hidden_size].sigmoid()
        g_t = preact[:, 3 * self.hidden_size:].tanh()
        i_t = gates[:, :self.hidden_size]
        f_t = gates[:, self.hidden_size:2 * self.hidden_size]
        o_t = gates[:, -self.hidden_size:]

        c_t = th.mul(c, f_t) + th.mul(i_t, g_t)

        h_t = th.mul(o_t, c_t.tanh())

        h_t = h_t.view(1, h_t.size(0), -1)
        c_t = c_t.view(1, c_t.size(0), -1)
        return h_t, (h_t, c_t)
</code>```

1- Why multiply the hidden size by 4 for both self.i2h and self.h2h (in the init method)

2- I don't understand the reset method for the parameters. In particular, why do we reset parameters in this way?

3- Why do we use view for h, c, and x in the forward method?

4- I'm also confused about the column bounds in the activations part of the forward method. As an example, why do we upper bound with 3 * self.hidden_size for gates?

5- Where are all the parameters of the LSTM? I'm talking about the Us and Ws here:

答:
1- Why multiply the hidden size by 4 for both self.i2h and self.h2h (in the init method)

In the equations you have included, the input x and the hidden state h are used for four calculations, where each of them is a matrix multiplication with a weight. Whether you do four matrix multiplications or concatenate the weights and do one bigger matrix multiplication and separate the results afterwards, has the same result.

input_size = 5
hidden_size = 10

input = torch.randn((2, input_size))

# Two different weights
w_c = torch.randn((hidden_size, input_size))
w_i = torch.randn((hidden_size, input_size))

# Concatenated weights into one tensor
# with size:[2 * hidden_size, input_size]
w_combined = torch.cat((w_c, w_i), dim=0)

# Output calculated by using separate matrix multiplications
out_c = torch.matmul(w_c, input.transpose(0, 1))
out_i = torch.matmul(w_i, input.transpose(0, 1))

# One bigger matrix multiplication with the combined weights
out_combined = torch.matmul(w_combined, input.transpose(0, 1))
# The first hidden_size number of rows belong to w_c
out_combined_c = out_combined[:hidden_size]
# The second hidden_size number of rows belong to w_i
out_combined_i = out_combined[hidden_size:]

# Using torch.allclose because they are equal besides floating point errors.
torch.allclose(out_c, out_combined_c) # => True
torch.allclose(out_i, out_combined_i) # => True
```

<p>By setting the output size of the linear layer to <em>4 * hidden_size</em> there are four weights with size <em>hidden_size</em>, so only one layer is needed instead of four. There is not really an advantage of doing this, except maybe a minor performance improvement, mostly for smaller inputs that don't fully exhaust the parallelisations capabilities if done individually.</p>

<blockquote>
  <p>4- I'm also confused about the column bounds in the <code>activations</code> part of the forward method. As an example, why do we upper bound with 3 * self.hidden_size for <code>gates</code>?</p>
</blockquote>

<p>That's where the outputs are separated to correspond to the output of the four individual calculations. The output is the concatenation of  <code>[i_t; f_t; o_t; g_t]</code> (not including tanh and sigmoid respectively).</p>

<p>You can get the same separation by splitting the output into four chunks with <code>torch.chunk</code>:</p>

<pre class="lang-py prettyprint-override"><code>i_t, f_t, o_t, g_t = torch.chunk(preact, 4, dim=1)
</code>```

But after the separation you would have to apply torch.sigmoid to i_t, f_t and o_t, and torch.tanh to g_t.

5- Where are all the parameters of the LSTM? I'm talking about the Us and Ws here:

The parameters W are the weights in the linear layer self.i2h and U in the linear layer self.h2h, but concatenated.

W_i, W_f, W_o, W_c = torch.chunk(self.i2h.weight, 4, dim=0)

U_i, U_f, U_o, U_c = torch.chunk(self.h2h.weight, 4, dim=0)
```

3- Why do we use view for h, c, and x in the forward method?

Based on h_t = h_t.view(1, h_t.size(0), -1) towards the end, the hidden states have the size [1, batch_size, hidden_size]. With h = h.view(h.size(1), -1) that gets rid of the first singular dimension to get size [batch_size, hidden_size]. The same could be achieved with h.squeeze(0).

2- I don't understand the reset method for the parameters. In particular, why do we reset parameters in this way?

Parameter initialisation can have a big impact on the model's learning capability. The general rule for the initialisation is to have values close to zero without being too small. A common initialisation is to draw from a normal distribution with mean 0 and variance of 1 / n, where n is the number of neurons, which in turn means a standard deviation of 1 / sqrt(n).

In this case it uses a uniform distribution instead of a normal distribution, but the general idea is similar. Determining the minimum/maximum value based on the number of neurons but avoiding to make them too small. If the minimum/maximum value would be 1 / n the values would get very small, so using 1 / sqrt(n) is more appropriate, e.g. 256 neurons: 1 / 256 = 0.0039 whereas 1 / sqrt(256) = 0.0625.

Initializing neural networks provides some explanations of different initialisations with interactive visualisations.

Body:
I was looking for an implementation of an LSTM cell in Pytorch that I could extend, and I found an implementation of it in the accepted answer here. I will post it here because I'd like to refer to it. There are quite a few implementation details that I do not understand, and I was wondering if someone could clarify.

import math
import torch as th
import torch.nn as nn

class LSTM(nn.Module):

    def __init__(self, input_size, hidden_size, bias=True):
        super(LSTM, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.bias = bias
        self.i2h = nn.Linear(input_size, 4 * hidden_size, bias=bias)
        self.h2h = nn.Linear(hidden_size, 4 * hidden_size, bias=bias)
        self.reset_parameters()

    def reset_parameters(self):
        std = 1.0 / math.sqrt(self.hidden_size)
        for w in self.parameters():
            w.data.uniform_(-std, std)

    def forward(self, x, hidden):
        h, c = hidden
        h = h.view(h.size(1), -1)
        c = c.view(c.size(1), -1)
        x = x.view(x.size(1), -1)

        # Linear mappings
        preact = self.i2h(x) + self.h2h(h)

        # activations
        gates = preact[:, :3 * self.hidden_size].sigmoid()
        g_t = preact[:, 3 * self.hidden_size:].tanh()
        i_t = gates[:, :self.hidden_size]
        f_t = gates[:, self.hidden_size:2 * self.hidden_size]
        o_t = gates[:, -self.hidden_size:]

        c_t = th.mul(c, f_t) + th.mul(i_t, g_t)

        h_t = th.mul(o_t, c_t.tanh())

        h_t = h_t.view(1, h_t.size(0), -1)
        c_t = c_t.view(1, c_t.size(0), -1)
        return h_t, (h_t, c_t)

1- Why multiply the hidden size by 4 for both self.i2h and self.h2h (in the init method)

2- I don't understand the reset method for the parameters. In particular, why do we reset parameters in this way?

3- Why do we use view for h, c, and x in the forward method?

4- I'm also confused about the column bounds in the activations part of the forward method. As an example, why do we upper bound with 3 * self.hidden_size for gates?

5- Where are all the parameters of the LSTM? I'm talking about the Us and Ws here:

Body:
1- Why multiply the hidden size by 4 for both self.i2h and self.h2h (in the init method)

In the equations you have included, the input x and the hidden state h are used for four calculations, where each of them is a matrix multiplication with a weight. Whether you do four matrix multiplications or concatenate the weights and do one bigger matrix multiplication and separate the results afterwards, has the same result.

input_size = 5
hidden_size = 10

input = torch.randn((2, input_size))

# Two different weights
w_c = torch.randn((hidden_size, input_size))
w_i = torch.randn((hidden_size, input_size))

# Concatenated weights into one tensor
# with size:[2 * hidden_size, input_size]
w_combined = torch.cat((w_c, w_i), dim=0)

# Output calculated by using separate matrix multiplications
out_c = torch.matmul(w_c, input.transpose(0, 1))
out_i = torch.matmul(w_i, input.transpose(0, 1))

# One bigger matrix multiplication with the combined weights
out_combined = torch.matmul(w_combined, input.transpose(0, 1))
# The first hidden_size number of rows belong to w_c
out_combined_c = out_combined[:hidden_size]
# The second hidden_size number of rows belong to w_i
out_combined_i = out_combined[hidden_size:]

# Using torch.allclose because they are equal besides floating point errors.
torch.allclose(out_c, out_combined_c) # => True
torch.allclose(out_i, out_combined_i) # => True

By setting the output size of the linear layer to 4 * hidden_size there are four weights with size hidden_size, so only one layer is needed instead of four. There is not really an advantage of doing this, except maybe a minor performance improvement, mostly for smaller inputs that don't fully exhaust the parallelisations capabilities if done individually.

4- I'm also confused about the column bounds in the activations part of the forward method. As an example, why do we upper bound with 3 * self.hidden_size for gates?

That's where the outputs are separated to correspond to the output of the four individual calculations. The output is the concatenation of  [i_t; f_t; o_t; g_t] (not including tanh and sigmoid respectively).

You can get the same separation by splitting the output into four chunks with torch.chunk:

i_t, f_t, o_t, g_t = torch.chunk(preact, 4, dim=1)

But after the separation you would have to apply torch.sigmoid to i_t, f_t and o_t, and torch.tanh to g_t.

5- Where are all the parameters of the LSTM? I'm talking about the Us and Ws here:

The parameters W are the weights in the linear layer self.i2h and U in the linear layer self.h2h, but concatenated.

W_i, W_f, W_o, W_c = torch.chunk(self.i2h.weight, 4, dim=0)

U_i, U_f, U_o, U_c = torch.chunk(self.h2h.weight, 4, dim=0)

3- Why do we use view for h, c, and x in the forward method?

Based on h_t = h_t.view(1, h_t.size(0), -1) towards the end, the hidden states have the size [1, batch_size, hidden_size]. With h = h.view(h.size(1), -1) that gets rid of the first singular dimension to get size [batch_size, hidden_size]. The same could be achieved with h.squeeze(0).

2- I don't understand the reset method for the parameters. In particular, why do we reset parameters in this way?

Parameter initialisation can have a big impact on the model's learning capability. The general rule for the initialisation is to have values close to zero without being too small. A common initialisation is to draw from a normal distribution with mean 0 and variance of 1 / n, where n is the number of neurons, which in turn means a standard deviation of 1 / sqrt(n).

In this case it uses a uniform distribution instead of a normal distribution, but the general idea is similar. Determining the minimum/maximum value based on the number of neurons but avoiding to make them too small. If the minimum/maximum value would be 1 / n the values would get very small, so using 1 / sqrt(n) is more appropriate, e.g. 256 neurons: 1 / 256 = 0.0039 whereas 1 / sqrt(256) = 0.0625.

Initializing neural networks provides some explanations of different initialisations with interactive visualisations.


问:
How to exclude file in flutter test coverage?
I am trying to exclude few config files from the test coverage results in the flutter test results. When I run flutter test --coverage, the output file icov.info is having information about the config files as well, which is affecting overall coverage percentage.

答:
There's a handy package to do that remove_from_coverage

https://pub.dev/packages/remove_from_coverage

This is the usage help:

```<code>Remove files with paths matching given PATTERNs from the lcov.info FILE
-f, --file=<FILE>         the target lcov.info file to manipulate
-r, --remove=<PATTERN>    a pattern of paths to exclude from coverage
-h, --help                show this help
</code>```

Basically add it to your dev_dependencies if you want to run this in your pipeline or install it globally.

Body:
There's a handy package to do that remove_from_coverage

https://pub.dev/packages/remove_from_coverage

This is the usage help:

Remove files with paths matching given PATTERNs from the lcov.info FILE
-f, --file=<FILE>         the target lcov.info file to manipulate
-r, --remove=<PATTERN>    a pattern of paths to exclude from coverage
-h, --help                show this help

Basically add it to your dev_dependencies if you want to run this in your pipeline or install it globally.


问:
Perf stat equivalent for Mac OS?
Is there a perf stat equivalent on Mac OS? I would like to do the same thing for a CLI command and googling is not yielding anything. </p>

答:
I was disappointed by the lack of a CLI equivalent to perf stat -r, so I just wrote up https://github.com/cdr/timer.

Works like:

$ timer -n 4 -q sleep 1s
--- config
command        sleep 1s
iterations     4
parallelism    1
--- percentiles
0        (fastest)         1.004
25       (1st quantile)    1.004
50       (median)          1.006
75       (3rd quantile)    1.008
100th    (slowest)         1.008
--- summary
mean      1.006
stddev    0.002
```

This doesn't contain advanced execution counters, just wall clock statistics.

Title: Perf stat equivalent for Mac OS?

Body:
I was disappointed by the lack of a CLI equivalent to perf stat -r, so I just wrote up https://github.com/cdr/timer.

Works like:

$ timer -n 4 -q sleep 1s
--- config
command        sleep 1s
iterations     4
parallelism    1
--- percentiles
0        (fastest)         1.004
25       (1st quantile)    1.004
50       (median)          1.006
75       (3rd quantile)    1.008
100th    (slowest)         1.008
--- summary
mean      1.006
stddev    0.002

This doesn't contain advanced execution counters, just wall clock statistics.


问:
How properly instantiate static field tat is another class object
If I have in my .h file

```<code>class A
{
 ...
protected:
static std::mutex someMutex;
}
</code>```

What is proper way to instantiate it in the cpp file?
Just to write

```<code>std::mutex A::someMutex;
</code>```

? It works, but just such syntax where I basically declare a field twice feels a bit confusing, so I decided to doublecheck asking here, also maybe there are some other(better?) ways?

答:
What you did is correct but these two notations are not exactly the same thing written twice.

Inside the braces of the class (in the .h file) this is a declaration.

It is a kind of promise saying "I swear this exists somewhere".

This can be seen in many translation units (i.e. .cpp files including this .h
file).

On the other hand, what you wrote in your .cpp file is the definition of
this variable; it must exist exactly once in your program.

An alternative exists since C++17: inline variables.

It offers the ability to skip the definition of the static variable
in the .cpp file (useful for header-only solutions).

Body:
If I have in my .h file

class A
{
 ...
protected:
static std::mutex someMutex;
}

What is proper way to instantiate it in the cpp file?
Just to write

std::mutex A::someMutex;

? It works, but just such syntax where I basically declare a field twice feels a bit confusing, so I decided to doublecheck asking here, also maybe there are some other(better?) ways?


问:
JavaScript compare strings such that letters come before other characters
How can you compare two strings in JavaScript such that letters will come before other characters? I'm specifically interested in letters coming before the underscore character, but would prefer a general solution.

For example, the code below will return -1, but I'd like it to return 1.

```<code>const a = "_";
const b = "A";
return a.localeCompare(b);
</code>```

答:
You could use this simple regex solution

const isLetter = x => /[A-Za-z]/.test(x)

const compare = (a, b) => {
  if (!isLetter(a) && isLetter(b)) return 1
  if (isLetter(a) && !isLetter(b)) return -1
  return a.localeCompare(b)
}

console.log(
  compare('_', 'A')
)```

Body:
How can you compare two strings in JavaScript such that letters will come before other characters? I'm specifically interested in letters coming before the underscore character, but would prefer a general solution.

For example, the code below will return -1, but I'd like it to return 1.

const a = "_";
const b = "A";
return a.localeCompare(b);


问:
My tkinter button only works half the time
Im trying to learn to code, but my button "BuyRobot" only works sometimes and i dont know why. I want to be able to press the button multiple times, and for the label that show how many i have to be updated (labelRobot) I think it has something to do with being in a loop, but i have tried putting it outside the loop but i cant seem to get it to work. Any help would be greatly apreciated!</p>

```<code>from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=n

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
while true:
    vindu.update()

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=80)
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1
    labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

    BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
    labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle).place(x=500, y=300)

    time.sleep(delay)

vindu.mainloop()
</code>```

答:
How about using StringVars for the labels textvariable?

```<code>from tkinter import *
import tkinter.font as tkFont
import time

n = 1
Robot = 0
def BuyRobotCommand():
    global n
    global Robot
    Robot += n

vindu = Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry(geo)

WoodCurrency = 99
WoodCurrencyLabel = StringVar(master=vindu,value="You have " + str(WoodCurrency) + " wood")
Money = 0
MoneyLabel = StringVar(master=vindu,value="You have " + str(Money) + " money")
WoodCutter = 0
RobotLabel = StringVar(master=vindu,value="You have " + str(Robot) + " wood cutter robots")

fontStyle=tkFont.Font(size=20)
labelWood=Label(vindu, textvariable=WoodCurrencyLabel, font=fontStyle).place(x=(1920/2)-100, y=100)
labelMoney=Label(vindu, textvariable=MoneyLabel, font=fontStyle).place(x=(1920/2)-100, y=130)
BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
labelRobot=Label(vindu, textvariable=RobotLabel, font=fontStyle).place(x=500, y=300)
delay=0.1

while True:
    vindu.update()
    #Fikser penger, og trær
    WoodCurrency += 1 * Robot
    if WoodCurrency>0:
        Money += 1
        WoodCurrency -= 1
    WoodCurrencyLabel.set("You have " + str(WoodCurrency) + " wood")
    MoneyLabel.set("You have " + str(Money) + " money")
    RobotLabel.set("You have " + str(Robot) + " wood cutter robots")
    time.sleep(delay)

vindu.mainloop()

</code>```

That way you can update your variables without needing to recreate the label widget to display it every time.

Body:
Im trying to learn to code, but my button "BuyRobot" only works sometimes and i dont know why. I want to be able to press the button multiple times, and for the label that show how many i have to be updated (labelRobot) I think it has something to do with being in a loop, but i have tried putting it outside the loop but i cant seem to get it to work. Any help would be greatly apreciated!

from tkinter import *
import tkinter.font as tkFont
import time

n=1
Robot=0
def BuyRobotCommand():
    global n
    global Robot
    Robot+=n

vindu=Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry("1920x1080")

WoodCurrency=99
Money=0
WoodCutter=0

fontStyle=tkFont.Font(size=20)
#labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=100)
#BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand(1)).place(x=300, y=300)

true=1
delay=0.1
while true:
    vindu.update()

    #Fikser penger, og trær
    WoodCurrency+=1*Robot
    labelWood=Label(vindu, text="You have "+str(WoodCurrency)+" wood", font=fontStyle).place(x=(1920/2)-100, y=80)
    if WoodCurrency>0:
        Money+=1
        WoodCurrency-=1
    labelMoney=Label(vindu, text="You have "+str(Money)+" money", font=fontStyle).place(x=(1920/2)-100, y=130)

    BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
    labelRobot=Label(vindu, text="You have "+str(Robot)+" wood cutter robots", font=fontStyle).place(x=500, y=300)

    time.sleep(delay)

vindu.mainloop()

Body:
How about using StringVars for the labels textvariable?

from tkinter import *
import tkinter.font as tkFont
import time

n = 1
Robot = 0
def BuyRobotCommand():
    global n
    global Robot
    Robot += n

vindu = Tk()
vindu.title("Robo Wood")
geo="1920x1080"
vindu.geometry(geo)

WoodCurrency = 99
WoodCurrencyLabel = StringVar(master=vindu,value="You have " + str(WoodCurrency) + " wood")
Money = 0
MoneyLabel = StringVar(master=vindu,value="You have " + str(Money) + " money")
WoodCutter = 0
RobotLabel = StringVar(master=vindu,value="You have " + str(Robot) + " wood cutter robots")

fontStyle=tkFont.Font(size=20)
labelWood=Label(vindu, textvariable=WoodCurrencyLabel, font=fontStyle).place(x=(1920/2)-100, y=100)
labelMoney=Label(vindu, textvariable=MoneyLabel, font=fontStyle).place(x=(1920/2)-100, y=130)
BuyRobot=Button(vindu, text="Kjøp en robot", font=fontStyle, command=BuyRobotCommand).place(x=300, y=300)
labelRobot=Label(vindu, textvariable=RobotLabel, font=fontStyle).place(x=500, y=300)
delay=0.1

while True:
    vindu.update()
    #Fikser penger, og trær
    WoodCurrency += 1 * Robot
    if WoodCurrency>0:
        Money += 1
        WoodCurrency -= 1
    WoodCurrencyLabel.set("You have " + str(WoodCurrency) + " wood")
    MoneyLabel.set("You have " + str(Money) + " money")
    RobotLabel.set("You have " + str(Robot) + " wood cutter robots")
    time.sleep(delay)

vindu.mainloop()

That way you can update your variables without needing to recreate the label widget to display it every time.


问:
Angular Material & Flex: How set max width for whole app?
I want to set the width of the app content so that when screen sizes changes, the content stays in the middle and there are whitespace on left and right side. I am using Angular Material & Angular Flex. I have observed this is a common design in various websites including stack overflow. Pardon me if this is a common question and I'm unable to find it.

Here is an example:
I want the app content to be within the lines.

答:
you can set the max-width for the app easily, you can do it in the style.css of your angular application like this

```<code>body {

  max-width: 200px;
  margin: 0 auto;
  border:1px solid black;
}
</code>```

what it will do is set the max-width for your app and will make the content in the center, you can also use flexbox to make the content center but its fine if you do it by margin below is the link for stackblitz. remember i have given border so that you can see the content is in the middle please remove it when you are done with test.
https://stackblitz.com/edit/angular-ivy-p9g262?file=src%2Fstyles.css

Body:
you can set the max-width for the app easily, you can do it in the style.css of your angular application like this

body {

  max-width: 200px;
  margin: 0 auto;
  border:1px solid black;
}

what it will do is set the max-width for your app and will make the content in the center, you can also use flexbox to make the content center but its fine if you do it by margin below is the link for stackblitz. remember i have given border so that you can see the content is in the middle please remove it when you are done with test.
https://stackblitz.com/edit/angular-ivy-p9g262?file=src%2Fstyles.css


问:
How can I make my string property nullable?
I want to make the Middle Name (CMName) of person optional. I have been using C#.net code first approach. For integer data type its easy just by using ? operator to make in nullable. I am looking for a way to make my sting variable nullable. I tried to search but could not find the way to make it nullable.

Below is my code. Please suggest me how to make it nullable.

```<code>public class ChildrenInfo
{
    [Key]
    public int ChidrenID { get; set; }

    [Required]
    [Display(Name ="First Name")]
    [StringLength(50,ErrorMessage ="First Name cannot exceed more than 50 characters")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Name cannot have special character,numbers or space")]
    [Column("FName")]
    public string CFName { get; set; }

    [Display(Name ="Middle Name")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Middle Name cannot have special character,numbers or space")]
    [StringLength(35,ErrorMessage ="Middle Name cannot have more than 35 characters")]
    [Column("MName")]
    public string CMName { get; set; }
}
</code>```

答: string is by default Nullable ,you don't need to do anything to make string Nullable</p>

Body:
I want to make the Middle Name (CMName) of person optional. I have been using C#.net code first approach. For integer data type its easy just by using ? operator to make in nullable. I am looking for a way to make my sting variable nullable. I tried to search but could not find the way to make it nullable.

Below is my code. Please suggest me how to make it nullable.

public class ChildrenInfo
{
    [Key]
    public int ChidrenID { get; set; }

    [Required]
    [Display(Name ="First Name")]
    [StringLength(50,ErrorMessage ="First Name cannot exceed more than 50 characters")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Name cannot have special character,numbers or space")]
    [Column("FName")]
    public string CFName { get; set; }

    [Display(Name ="Middle Name")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Middle Name cannot have special character,numbers or space")]
    [StringLength(35,ErrorMessage ="Middle Name cannot have more than 35 characters")]
    [Column("MName")]
    public string CMName { get; set; }
}