问:
How do I run Flutter in multiple iOS Simulators
Environment:

```<code>[✓] Flutter (Channel master, 1.19.0-2.0.pre.214, on Mac OS X 10.15.4 19E287, locale en-PH)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.6)
[✓] VS Code (version 1.45.1)
[✓] Connected device (2 available)
</code>```

When I run flutter devices all I get are the following:

```<code>Web Server • web-server • web-javascript • Flutter Tools
Chrome     • chrome     • web-javascript • Google Chrome 83.0.4103.61
<and my physical devices which I ommited>
</code>```

Now when I run flutter emulators, I get the built-in apple_ios_simulator and the Android emulator which I created:

```<code>apple_ios_simulator • iOS Simulator • Apple  • ios
Pixel_API_R         • Pixel API R   • Google • android
</code>```

Creating an Android emulator is easy, I can just add as much AVDs I want using Android studio and they'll show up every time I call flutter emulators.

How do I do that for iOS simulators?

答:
Ok, apparently iOS Simulators are not regarded as flutter emulators. For the life of me, I could not find any documentation regarding this so here it goes.

The iOS Simulator can be run with flutter emulators --launch apple_ios_simulator

After launching this when you run flutter devices it will appear as a device.

```<code>3 connected devices:

iPhone 11                  • DCDA3304-2E80-4BCD-B0D5-968C2EBD2FA3 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
Web Server                 • web-server                           • web-javascript • Flutter Tools
Chrome                     • chrome                               • web-javascript • Google Chrome 83.0.4103.61
</code>```

Then just run another simulator via the Simulator app

Run flutter devices once again to check if another iOS Simulator device has showed up

```<code>4 connected devices:

iPhone 11                  • DCDA3304-2E80-4BCD-B0D5-968C2EBD2FA3 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
iPhone SE (2nd generation) • 59D9A787-E68B-4CE1-8CDB-2A5D3CBF0093 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
Web Server                 • web-server                           • web-javascript • Flutter Tools
Chrome                     • chrome                               • web-javascript • Google Chrome 83.0.4103.61
</code>```

And from there you can just run flutter run -d all.

Body:
Environment:

[✓] Flutter (Channel master, 1.19.0-2.0.pre.214, on Mac OS X 10.15.4 19E287, locale en-PH)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.6)
[✓] VS Code (version 1.45.1)
[✓] Connected device (2 available)

When I run flutter devices all I get are the following:

Web Server • web-server • web-javascript • Flutter Tools
Chrome     • chrome     • web-javascript • Google Chrome 83.0.4103.61
<and my physical devices which I ommited>

Now when I run flutter emulators, I get the built-in apple_ios_simulator and the Android emulator which I created:

apple_ios_simulator • iOS Simulator • Apple  • ios
Pixel_API_R         • Pixel API R   • Google • android

Creating an Android emulator is easy, I can just add as much AVDs I want using Android studio and they'll show up every time I call flutter emulators.

How do I do that for iOS simulators?

Body:
Ok, apparently iOS Simulators are not regarded as flutter emulators. For the life of me, I could not find any documentation regarding this so here it goes.

The iOS Simulator can be run with flutter emulators --launch apple_ios_simulator

After launching this when you run flutter devices it will appear as a device.

3 connected devices:

iPhone 11                  • DCDA3304-2E80-4BCD-B0D5-968C2EBD2FA3 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
Web Server                 • web-server                           • web-javascript • Flutter Tools
Chrome                     • chrome                               • web-javascript • Google Chrome 83.0.4103.61

Then just run another simulator via the Simulator app

Run flutter devices once again to check if another iOS Simulator device has showed up

4 connected devices:

iPhone 11                  • DCDA3304-2E80-4BCD-B0D5-968C2EBD2FA3 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
iPhone SE (2nd generation) • 59D9A787-E68B-4CE1-8CDB-2A5D3CBF0093 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-13-5 (simulator)
Web Server                 • web-server                           • web-javascript • Flutter Tools
Chrome                     • chrome                               • web-javascript • Google Chrome 83.0.4103.61

And from there you can just run flutter run -d all.


来源: stackexchange

问:
How to generate game pins
I am developing a game that requires a game PIN to join, similar to Kahoot in that regard I suppose. E.g. KA1PN2XR. I was thinking of making it 8 characters and alphanumeric, so I'm not worried about running out of combinations as there are 36^8 or about 2.8 trillion (capital letters) of them, and games will be removed once everyone has left.

However, I am wondering what is an efficient way to generate these pins? Should I use a while loop that generates one until it finds one that isn't in the database? Seems inefficient but I can't think of a much better method.

Thanks.

答:
You can do this with a simple function like this:</p>

```<code>import random
w_list = 'abcdefghijklmnopqrstuvwxyz1234567890' #characters you want in string
def generate_pin(length=8):
    tp = random.sample(w_list, length)
    pin = ''.join(tp)
    if pin not in prev_list: #list of already generated pins
       prev_list.appen(pin)
       return pin
    else:
       generate_pin()
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to generate game pins

Body:
You can do this with a simple function like this:

import random
w_list = 'abcdefghijklmnopqrstuvwxyz1234567890' #characters you want in string
def generate_pin(length=8):
    tp = random.sample(w_list, length)
    pin = ''.join(tp)
    if pin not in prev_list: #list of already generated pins
       prev_list.appen(pin)
       return pin
    else:
       generate_pin()


问:
SOAP service to retieve scope detailse from WSO2IS
Is there SOAP service which returns the SCOPE from WSO2IS 5.5.0 ? I have bearer token generated using Oauth grant_type 'password'.  Using this token,  i need to retrieve set of scope associated with token.

I tried introespection RESTfull API, but its returning  ' Could not resolve host: application' error message .

Any suggestion please ?

curl: (6) Could not resolve host: application
{"error": "Invalid input"}

thansk a lot

答:
EDIT : I missed the tailing 't' of the end point. Added that.
You are missing the protocol here.

```<code>curl -k -u admin:admin -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=a6998b8b-5fff-390d-abd6-b0c9170f3147' https://localhost:9443/oauth2/introspect -v
</code>```

You don't need to use the SOAP call therefore. In case you need it, here is the documentation.

Body:
EDIT : I missed the tailing 't' of the end point. Added that.
You are missing the protocol here.

curl -k -u admin:admin -H 'Content-Type: application/x-www-form-urlencoded' -X POST --data 'token=a6998b8b-5fff-390d-abd6-b0c9170f3147' https://localhost:9443/oauth2/introspect -v

You don't need to use the SOAP call therefore. In case you need it, here is the documentation.


问:
Upgrade to FontAwesome Pro in ASP.NET Zero (Angular) / fas far icons displaying as squares
I was asked to upgrade an ASP.NET Zero project with the Font Awesome Pro icons.

I followed the steps here Installing the Pro version of Font Awesome

After adding the below in the angular.json

"node_modules/@fortawesome/fontawesome-pro/css/all.min.css"

I found that some of the pro fonts did not want to display specifically some of the solid(fas) and regular (far) fonts.

答:
To fix the issue remove the vendor included Font Awesome Free css from the src\assets\metronic\vendors\global\vendors.bundle.css file

Be sure to remove the trailing comment on line 15 as well

After the above step be sure to replace all the instances of Font Awesome 5 Free with Font Awesome 5 Pro especially where they are referenced in .css files

Please Note that I found some SVG files that contains the phrase 'Font Awesome 5 Free' which I think should remain there


问:
componentWillReceiveProps to React hooks
I want to change class based component to functional component and i have

```<code>const initialState={

     displayName: "",
        email: "",
        password: "",
        confirmPassword: "",
        error: "",
    }

componentWillReceiveProps(nextProps,nextContext){
const userError=nextProps;
if(userError){
this.setState({error:userError.message});
}
}
</code>```

And i make selector

```<code>export const selectUserError = createSelector(
  [selectUser],
  (user) => user.error
);

 {this.state.error ? (
        <SweetAlert
          show={this.state.error}
          type="warning"
          title="Something went wrong"
          text={this.props.userError}
          onConfirm={() => this.setState({ error: "" })}
        />
      ) : null}
</code>```

and i pass into mapState to props.
Can anyone help with this?

答:
Thanks to @shubham-khatri help, i solved the problem.
I make RESET_ERROR type in my user.types, after that i make action reseterror.
Dispatched in my sign up component and after that i can use in onConfirm method.
It works fine.</p>

Body:
I want to change class based component to functional component and i have

const initialState={

     displayName: "",
        email: "",
        password: "",
        confirmPassword: "",
        error: "",
    }

componentWillReceiveProps(nextProps,nextContext){
const userError=nextProps;
if(userError){
this.setState({error:userError.message});
}
}

And i make selector

export const selectUserError = createSelector(
  [selectUser],
  (user) => user.error
);

 {this.state.error ? (
        <SweetAlert
          show={this.state.error}
          type="warning"
          title="Something went wrong"
          text={this.props.userError}
          onConfirm={() => this.setState({ error: "" })}
        />
      ) : null}

and i pass into mapState to props.
Can anyone help with this?


问:
Copy a column value from another dataframe based on a condition
Let us say I have two dataframes: df1 and df2. Assume the following initial values.

```<code>df1=pd.DataFrame({'ID':['ASX-112','YTR-789','ASX-124','UYT-908','TYE=456','ERW-234','UUI-675','GHV-805','NMB-653','WSX-123'],
'Costperlb':[4515,5856,3313,9909,8980,9088,6765,3456,9012,1237]})
df2=df1[df1['Costperlb']>4560]
</code>```

As you can see, df2 is a proper subset of df1 (it was created from df1 by imposing a condition on selection of rows).

I added a column to df2, which contains certain values based on a calculation. Let us call this df2['grade'].

```<code>df2['grade']=[1,4,3,5,1,1]
</code>```

df1 and df2 contain one column named 'ID' which is guaranteed to be unique in each dataframe.

I want to:

Create a new column in df1 and initialize it to 0. Easy. df1['grade']=0.

Copy df2['grade'] values over to df1['grade'], ensuring that df1['ID']=df2['ID'] for each such copy.

The result should be the grade values for the corresponding IDs copied over.

Step 2 is what is perplexing me a bit. A naive df1['grade']=df2['grade'].values does not work obviously as the lengths of the two dataframes is different.

Now, if I think hard enough, I could possibly come up with a monstrosity like:

df1['grade'].loc[(df1['ID'].isin(df2)) & ...] but I am uncomfortable with doing that.

I am a newbie with python, and furthermore, the indices of df1 are being used elsewhere after this assignment, and I do not want drop indices, reset indices as some of the solutions are suggested in some of the search results I found.

I just want to find out rows in df1 where the 'ID' row matches the 'ID' row in df2, and then copy the 'grade' column value in that specific row over. How do I do this?

答:
Your code:

```<code>df1=pd.DataFrame({'ID':['ASX-112','YTR-789','ASX-124','UYT-908','TYE=456','ERW-234','UUI-675','GHV-805','NMB-653','WSX-123'],
'Costperlb':[4515,5856,3313,9909,8980,9088,6765,3456,9012,1237]})
df2=df1[df1['Costperlb']>4560]
df2['grade']=[1,4,3,5,1,1]
</code>```

You can use merge with "left". In this way the indexing of df1 is preserved:

```<code>new_df = df1.merge(df2[["ID","grade"]], on="ID", how="left")
new_df["grade"] = new_df["grade"].fillna(0)
new_df
</code>```

Output:

```<code>    ID   Costperlb grade
0   ASX-112 4515    0.0
1   YTR-789 5856    1.0
2   ASX-124 3313    0.0
3   UYT-908 9909    4.0
4   TYE=456 8980    3.0
5   ERW-234 9088    5.0
6   UUI-675 6765    1.0
7   GHV-805 3456    0.0
8   NMB-653 9012    1.0
9   WSX-123 1237    0.0
</code>```

Here I called the merged dataframe new_df, but you can simply change it to df1.

EDIT

If instead of 0 you want to replace the NaN with a string, try this:

```<code>new_df = df1.merge(df2[["ID","grade"]], on="ID", how="left")
new_df["grade"] = new_df["grade"].fillna("No transaction possible")
new_df
</code>```

Output:

```<code>    ID    Costperlb       grade
0   ASX-112 4515    No transaction possible
1   YTR-789 5856    1
2   ASX-124 3313    No transaction possible
3   UYT-908 9909    4
4   TYE=456 8980    3
5   ERW-234 9088    5
6   UUI-675 6765    1
7   GHV-805 3456    No transaction possible
8   NMB-653 9012    1
9   WSX-123 1237    No transaction possible
</code>```

Body:
Let us say I have two dataframes: df1 and df2. Assume the following initial values.

df1=pd.DataFrame({'ID':['ASX-112','YTR-789','ASX-124','UYT-908','TYE=456','ERW-234','UUI-675','GHV-805','NMB-653','WSX-123'],
'Costperlb':[4515,5856,3313,9909,8980,9088,6765,3456,9012,1237]})
df2=df1[df1['Costperlb']>4560]

As you can see, df2 is a proper subset of df1 (it was created from df1 by imposing a condition on selection of rows).

I added a column to df2, which contains certain values based on a calculation. Let us call this df2['grade'].

df2['grade']=[1,4,3,5,1,1]

df1 and df2 contain one column named 'ID' which is guaranteed to be unique in each dataframe.

I want to:

Create a new column in df1 and initialize it to 0. Easy. df1['grade']=0.

Copy df2['grade'] values over to df1['grade'], ensuring that df1['ID']=df2['ID'] for each such copy.

The result should be the grade values for the corresponding IDs copied over.

Step 2 is what is perplexing me a bit. A naive df1['grade']=df2['grade'].values does not work obviously as the lengths of the two dataframes is different.

Now, if I think hard enough, I could possibly come up with a monstrosity like:

df1['grade'].loc[(df1['ID'].isin(df2)) & ...] but I am uncomfortable with doing that.

I am a newbie with python, and furthermore, the indices of df1 are being used elsewhere after this assignment, and I do not want drop indices, reset indices as some of the solutions are suggested in some of the search results I found.

I just want to find out rows in df1 where the 'ID' row matches the 'ID' row in df2, and then copy the 'grade' column value in that specific row over. How do I do this?

Body:
Your code:

df1=pd.DataFrame({'ID':['ASX-112','YTR-789','ASX-124','UYT-908','TYE=456','ERW-234','UUI-675','GHV-805','NMB-653','WSX-123'],
'Costperlb':[4515,5856,3313,9909,8980,9088,6765,3456,9012,1237]})
df2=df1[df1['Costperlb']>4560]
df2['grade']=[1,4,3,5,1,1]

You can use merge with "left". In this way the indexing of df1 is preserved:

new_df = df1.merge(df2[["ID","grade"]], on="ID", how="left")
new_df["grade"] = new_df["grade"].fillna(0)
new_df

Output:

    ID   Costperlb grade
0   ASX-112 4515    0.0
1   YTR-789 5856    1.0
2   ASX-124 3313    0.0
3   UYT-908 9909    4.0
4   TYE=456 8980    3.0
5   ERW-234 9088    5.0
6   UUI-675 6765    1.0
7   GHV-805 3456    0.0
8   NMB-653 9012    1.0
9   WSX-123 1237    0.0

Here I called the merged dataframe new_df, but you can simply change it to df1.

EDIT

If instead of 0 you want to replace the NaN with a string, try this:

new_df = df1.merge(df2[["ID","grade"]], on="ID", how="left")
new_df["grade"] = new_df["grade"].fillna("No transaction possible")
new_df

Output:

    ID    Costperlb       grade
0   ASX-112 4515    No transaction possible
1   YTR-789 5856    1
2   ASX-124 3313    No transaction possible
3   UYT-908 9909    4
4   TYE=456 8980    3
5   ERW-234 9088    5
6   UUI-675 6765    1
7   GHV-805 3456    No transaction possible
8   NMB-653 9012    1
9   WSX-123 1237    No transaction possible


问:
How to read Parquet "group"/list field in cpp?
I am new to cpp. I have some Parquet with part of its schema like this:

```<code>  optional binary one (UTF8);
  optional group two (LIST) {
    repeated group list {
      optional binary element (UTF8);
    }
  }
  optional binary three (UTF8);
</code>```

I'm using Arrow's parquet::StreamReader to read it like in this example.

It's clear to me how to read fields one and three, and one works fine, but not two, so I can't reach three. For two, I'm not sure what cpp type to use. I know the logical type is "list" and below is the output from assigning it into std::string just to get the inferred type from the error, but it shows me 'UNKNOWN':

```<code>libc++abi.dylib: terminating with uncaught exception of type parquet::ParquetException:
Column physical type mismatch.  Column 'two' has physical type 'UNKNOWN' not 'BYTE_ARRAY'
</code>```

I would just skip this column entirely (I don't require it) but am unclear how I can do that without parsing it.

答: It turns out it is not possible to use StreamReader except on primitive types. However, I was able to use StreamReader::SkipColumns to skip two and then parse three.

Body:
I am new to cpp. I have some Parquet with part of its schema like this:

  optional binary one (UTF8);
  optional group two (LIST) {
    repeated group list {
      optional binary element (UTF8);
    }
  }
  optional binary three (UTF8);

I'm using Arrow's parquet::StreamReader to read it like in this example.

It's clear to me how to read fields one and three, and one works fine, but not two, so I can't reach three. For two, I'm not sure what cpp type to use. I know the logical type is "list" and below is the output from assigning it into std::string just to get the inferred type from the error, but it shows me 'UNKNOWN':

libc++abi.dylib: terminating with uncaught exception of type parquet::ParquetException:
Column physical type mismatch.  Column 'two' has physical type 'UNKNOWN' not 'BYTE_ARRAY'

I would just skip this column entirely (I don't require it) but am unclear how I can do that without parsing it.


问:
How to save text of FCKEditor on database?
I am using FCKEditor on my page.

and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="
hello..
"). occur on my page..

what i am doing is here:-

aspx.cs:-

```<code>protected void btnadd_Click(object sender, EventArgs e)

{
    string _detail = Request["LongDescriptionVal"].ToString();
    string query = "insert into Description(description) values('" + _detail.Trim() + "')";
    SqlCommand cmd = new SqlCommand(query, con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}
</code>```

and aspx:-

```<code><strong>Full Description :</strong>
                <br />
                            <!--Editor Code comes here  -->

                            <script type="text/javascript">
                                <!--
                                var oFCKeditor = new FCKeditor( 'LongDescriptionVal') ;
                                oFCKeditor.BasePath = 'fckeditor/';
                                oFCKeditor.Height   = 300;
                                oFCKeditor.Value    = '<%=FullDescription%>';
                                oFCKeditor.Create() ;
                                //-->
                            </script>
                  <br />
                  <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
</code>```

anyone can tell me that how can i save data on database...

Thanks in advance..

答:
Have a look at this question:
A potentially dangerous Request.Form value was detected from the client

The gist of the answer is that you can suppress the warning by setting validateRequest="false" in the <@Page directive of your aspx file.

There is a reason for that warning however, by doing so you could in your case open yourself up to all sorts of attacks. Given the nature of your database access code can I suggest that you read up on using Parameterized Queries

ContentLicense: CC BY-SA 3.0

Body:
I am using FCKEditor on my page.

and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="
hello..
"). occur on my page..

what i am doing is here:-

aspx.cs:-

protected void btnadd_Click(object sender, EventArgs e)

{
    string _detail = Request["LongDescriptionVal"].ToString();
    string query = "insert into Description(description) values('" + _detail.Trim() + "')";
    SqlCommand cmd = new SqlCommand(query, con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

and aspx:-

Full Description :

                  <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />

anyone can tell me that how can i save data on database...

Thanks in advance..


问:
Is it possible to force a specific number of neurons to be fired at any one time in Tensorflow 2.0?
I am using Tensorflow 2.0. I am aware of dropout and regularization techniques, however I am wondering if there is a way to specifically control the number of fired neurons in a given layer at any one time?

For example, consider a layer with 4 neurons - A, B, C and D. ReLU is used as the activation for all of these neurons. For any training/testing sample, I only want exactly 3 neurons fired, no less and no more. Therefore, the possible patterns are:

```<code> 1) A,B,C fired, D not fired
 2) A,B,D fired, C not fired
 3) A,C,D fired, B not fired
 4) B,C,D fired, A not fired
</code>```

Is there any method to enforce such a constraint on a layer?

Note: I use the term "fired neuron" to denote that it has a non-zero output. A neuron not fired gives a 0 as output.

答:
This is one way to implement that, although it is more computationally expensive than regular dropout.

import tensorflow as tf

def dropout_by_num(inp, n, scale=True, axis=-1):
    # Get random value with the shape of input
    s = tf.shape(inp)
    r = tf.random.uniform(s)
    # Find sort indices
    idx = tf.argsort(r, axis=axis)
    # Mask indices greater or equal to n
    mask = tf.dtypes.cast(idx < n, inp.dtype)
    if scale:
        # Scale up to preserve expected value
        m = tf.dtypes.cast(s[axis], inp.dtype)
        scale = m / tf.dtypes.cast(n, inp.dtype)
        mask *= scale
    return inp * mask

# Test
tf.random.set_seed(0)
inp = tf.ones((3, 4))
out = dropout_by_num(inp, 3)
tf.print(out)
# [[1.33333337 1.33333337 1.33333337 0]
#  [1.33333337 1.33333337 1.33333337 0]
#  [1.33333337 0 1.33333337 1.33333337]]
```

Body:
I am using Tensorflow 2.0. I am aware of dropout and regularization techniques, however I am wondering if there is a way to specifically control the number of fired neurons in a given layer at any one time?

For example, consider a layer with 4 neurons - A, B, C and D. ReLU is used as the activation for all of these neurons. For any training/testing sample, I only want exactly 3 neurons fired, no less and no more. Therefore, the possible patterns are:

 1) A,B,C fired, D not fired
 2) A,B,D fired, C not fired
 3) A,C,D fired, B not fired
 4) B,C,D fired, A not fired

Is there any method to enforce such a constraint on a layer?

Note: I use the term "fired neuron" to denote that it has a non-zero output. A neuron not fired gives a 0 as output.


问:
create a dict of dict from a dataframe
i am trying to convert a data-frame to a dict in the below format:

```<code>df
    name   age country state  pincode
0  user1  10.0      in    tn      1.0
1  user2  11.0      us    tx      2.0
2  user3  12.0      eu    fr      3.0
</code>```

```<code>{
   'user1':{'age':10,'country':'in','state':'tn','pincode':1},
   'user2':{'age':11,'country':'us','state':'tx','pincode':2},
   'user3':{'age':12,'country':'eu','state':'fr','pincode':3}
}
</code>```

I am currently doing this by below statement:

```<code>op = {}
for i, row in df.iterrows():
    op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}
</code>```

I want a the solution to work if there are additional columns added to the df. for example telephone number. Since the statement I have written is static it won't give me the additional rows in my output.
Is there a built in method in pandas that does this?

答:
You want to set name as index first:

```<code>df.set_index('name').to_dict('index')
</code>```

Output:

```<code>{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}
</code>```

Title: create a dict of dict from a dataframe

Body:
i am trying to convert a data-frame to a dict in the below format:

df
    name   age country state  pincode
0  user1  10.0      in    tn      1.0
1  user2  11.0      us    tx      2.0
2  user3  12.0      eu    fr      3.0

{
   'user1':{'age':10,'country':'in','state':'tn','pincode':1},
   'user2':{'age':11,'country':'us','state':'tx','pincode':2},
   'user3':{'age':12,'country':'eu','state':'fr','pincode':3}
}

I am currently doing this by below statement:

op = {}
for i, row in df.iterrows():
    op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}

I want a the solution to work if there are additional columns added to the df. for example telephone number. Since the statement I have written is static it won't give me the additional rows in my output.
Is there a built in method in pandas that does this?

Body:
You want to set name as index first:

df.set_index('name').to_dict('index')

Output:

{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}


问:
SwiftUI binding boolean if statement (Cannot convert value of type 'Binding<Bool>' to expected condition type 'Bool')
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

```<code>struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}
</code>```

答:
Found a way around it. Embedded the NavigationView in a VStack and added the menuView to the end of it.

```<code>struct ContentView: View {
@State private var menuActivated  = false

        var body: some View {
            ZStack {

                NavigationView {
                ... // view code
                }
                if menuActivated {
                    menuView()
                }

            }

        }
    }
</code>```

Body:
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}

Body:
Found a way around it. Embedded the NavigationView in a VStack and added the menuView to the end of it.

struct ContentView: View {
@State private var menuActivated  = false

        var body: some View {
            ZStack {

                NavigationView {
                ... // view code
                }
                if menuActivated {
                    menuView()
                }

            }

        }
    }


问:
How to prevent adding of duplicate list items in sharepoint list
I need to add items to a sharepoint list through object model. Before doing this i want to check whether the current item is already exist in the list or not. how to do this? </p>

答:
There are multiple ways to achieve this.

Firstly, sharepoint allows you by default to add List items with exactly the same data.

Your best bet in this scenario, is to identify your column in the Listitem which is your Unique identifier (Usually Title). Then, in the list settings, click on the column name and select 'Yes' for Enforce Unique values.

Alternatively, as you are adding items using the Object Model, Iterate through existing items and see if a ListItem with that value exists.

Send some code example and I can help you out.

Cheers


答:
Use DataFrame.set_index with DataFrame.to_dict with orient='index':

```<code>d = df.set_index('name').to_dict(orient='index')
print (d)
{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}
</code>```

If possible another columns which should be omited is possible crop them before or selecting:

```<code>d = df.set_index('name')[['age','country','state','pincode']].to_dict(orient='index')
</code>```

Title: create a dict of dict from a dataframe

Body:
Use DataFrame.set_index with DataFrame.to_dict with orient='index':

d = df.set_index('name').to_dict(orient='index')
print (d)
{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}

If possible another columns which should be omited is possible crop them before or selecting:

d = df.set_index('name')[['age','country','state','pincode']].to_dict(orient='index')


问:
How to create an complex128 tensor using tf.range
The following lines work:

```<code>t1 = tf.constant([-2.0, -1.0, 0, 1.0, 2.0], dtype=tf.complex128)
tf.sqrt(t1)
print(t1)
</code>```

Now if I use

```<code>t1 = tf.range(-2.0, 3.0, 1, dtype=tf.complex128)
tf.sqrt(t1)
print(t1)
</code>```

I get the usual error :

Node:{{node Range}} All kernels registered for op Range :

  device='CPU'; Tidx in [DT_FLOAT]   device='CPU'; Tidx in [DT_DOUBLE]

  device='CPU'; Tidx in [DT_INT32]   device='CPU'; Tidx in [DT_INT64]

  device='GPU'; Tidx in [DT_FLOAT]   device='GPU'; Tidx in [DT_DOUBLE]

  device='GPU'; Tidx in [DT_INT32]   device='GPU'; Tidx in [DT_INT64]

  device='XLA_CPU_JIT'; Tidx in [DT_FLOAT, DT_DOUBLE, DT_INT32,
  DT_INT64, DT_BFLOAT16, DT_HALF]   device='XLA_GPU_JIT'; Tidx in
  [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]

  device='XLA_CPU'; Tidx in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64,
  DT_BFLOAT16, DT_HALF]   device='XLA_GPU'; Tidx in [DT_FLOAT,
  DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]  [Op:Range]

What am I doing wrong?

答:
According to this error, it is saying that input to the tf.range should be one of double, float, int are registered for op Range on device: CPU and GPU. But your input is complex128, hence it return NotFoundError.

If we haven't specified any dtype (i.e. dtype is None), it inferred dtype from dtype_hierarchy: dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64 as per as per arg.dtype.

Workaround to create complex128 tensor using tf.range is as below with the help of tf.cast

```<code>t1 = tf.range(-2.0, 3.0, 1)
# casts tensor to a complex128 dtype.
t2 = tf.cast(t1, dtype=tf.complex128)
# apply sqrt function
tf.sqrt(t2)
# print output
print(t1)
print(t2)
</code>```

Output:

```<code>tf.Tensor([-2. -1.  0.  1.  2.], shape=(5,), dtype=float32)
tf.Tensor([-2.+0.j -1.+0.j  0.+0.j  1.+0.j  2.+0.j], shape=(5,), dtype=complex128)
</code>```

Body:
The following lines work:

t1 = tf.constant([-2.0, -1.0, 0, 1.0, 2.0], dtype=tf.complex128)
tf.sqrt(t1)
print(t1)

Now if I use

t1 = tf.range(-2.0, 3.0, 1, dtype=tf.complex128)
tf.sqrt(t1)
print(t1)

I get the usual error :

Node:{{node Range}} All kernels registered for op Range :

  device='CPU'; Tidx in [DT_FLOAT]   device='CPU'; Tidx in [DT_DOUBLE]

  device='CPU'; Tidx in [DT_INT32]   device='CPU'; Tidx in [DT_INT64]

  device='GPU'; Tidx in [DT_FLOAT]   device='GPU'; Tidx in [DT_DOUBLE]

  device='GPU'; Tidx in [DT_INT32]   device='GPU'; Tidx in [DT_INT64]

  device='XLA_CPU_JIT'; Tidx in [DT_FLOAT, DT_DOUBLE, DT_INT32,
  DT_INT64, DT_BFLOAT16, DT_HALF]   device='XLA_GPU_JIT'; Tidx in
  [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]

  device='XLA_CPU'; Tidx in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64,
  DT_BFLOAT16, DT_HALF]   device='XLA_GPU'; Tidx in [DT_FLOAT,
  DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]  [Op:Range]

What am I doing wrong?

Body:
According to this error, it is saying that input to the tf.range should be one of double, float, int are registered for op Range on device: CPU and GPU. But your input is complex128, hence it return NotFoundError.

If we haven't specified any dtype (i.e. dtype is None), it inferred dtype from dtype_hierarchy: dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64 as per as per arg.dtype.

Workaround to create complex128 tensor using tf.range is as below with the help of tf.cast

t1 = tf.range(-2.0, 3.0, 1)
# casts tensor to a complex128 dtype.
t2 = tf.cast(t1, dtype=tf.complex128)
# apply sqrt function
tf.sqrt(t2)
# print output
print(t1)
print(t2)

Output:

tf.Tensor([-2. -1.  0.  1.  2.], shape=(5,), dtype=float32)
tf.Tensor([-2.+0.j -1.+0.j  0.+0.j  1.+0.j  2.+0.j], shape=(5,), dtype=complex128)


问:
Heroku app throwing Error: self signed certificate
I'm using free tier of heroku to deploy an app. I've managed to create the app with the build being successful on heroku. I pushed to heroku and tried heroku local and the app runs as it should. However if I try heroku open the browser opens to the heroku "Application error" page.

I tried running NODE_ENV=production heroku local as a troubleshooting step and that does cause the app to break. I get

```<code>Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1492:34)
at TLSSocket.emit (evens.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:935:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:693:12)
</code>```

The github repo is here: https://github.com/JoeCastr/budget_app

My package.json:

```<code>{
  "name": "budget_app_project",
  "version": "1.0.0",
  "description": "",
  "main": "budget.js",
  "scripts": {
    "start": "npx nodemon budget.js",
    "heroku-postbuild": "npm install --production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.1.0",
    "eslint-plugin-import": "^2.20.2",
    "nodemon": "^2.0.3"
  },
  "dependencies": {
    "bcrypt": "^4.0.1",
    "connect-loki": "^1.1.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "express-flash": "0.0.2",
    "express-session": "^1.17.1",
    "express-validator": "^6.5.0",
    "morgan": "^1.10.0",
    "pg": "^8.2.1",
    "pug": "^2.0.4"
  },
  "engines": {
    "node": "13.12.0",
    "npm": "6.14.4"
  }
}
</code>```

答:
The problem is with pg version 8.x it breaks heroku. the connection constant needs to be:</p>
```<code>const CONNECTION = {
    connectionString: process.env.DATABASE_URL,
    ssl: {
        rejectUnauthorized: false
    }
}
</code>```

Body:
I'm using free tier of heroku to deploy an app. I've managed to create the app with the build being successful on heroku. I pushed to heroku and tried heroku local and the app runs as it should. However if I try heroku open the browser opens to the heroku "Application error" page.

I tried running NODE_ENV=production heroku local as a troubleshooting step and that does cause the app to break. I get

Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1492:34)
at TLSSocket.emit (evens.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:935:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:693:12)

The github repo is here: https://github.com/JoeCastr/budget_app

My package.json:

{
  "name": "budget_app_project",
  "version": "1.0.0",
  "description": "",
  "main": "budget.js",
  "scripts": {
    "start": "npx nodemon budget.js",
    "heroku-postbuild": "npm install --production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.1.0",
    "eslint-plugin-import": "^2.20.2",
    "nodemon": "^2.0.3"
  },
  "dependencies": {
    "bcrypt": "^4.0.1",
    "connect-loki": "^1.1.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "express-flash": "0.0.2",
    "express-session": "^1.17.1",
    "express-validator": "^6.5.0",
    "morgan": "^1.10.0",
    "pg": "^8.2.1",
    "pug": "^2.0.4"
  },
  "engines": {
    "node": "13.12.0",
    "npm": "6.14.4"
  }
}

Body:
The problem is with pg version 8.x it breaks heroku. the connection constant needs to be:

const CONNECTION = {
    connectionString: process.env.DATABASE_URL,
    ssl: {
        rejectUnauthorized: false
    }
}


问:
Why does my script not find inactive GameObject when it should?
I have a script that should toggle active on my GameObject but when it disables it, it no longer finds the object.

Script:

```<code>GameObject cheet = GameObject.Find("base");

if (isOpen == true)
{
    cheet.SetActive(true);
}
else
{
    cheet.SetActive(false);
}
</code>```

答:
```<code>using UnityEngine;

public class Scriptname: MonoBehaviour
{
    GameObject cheet;
    Bool isOpen;

    void Start()
    {
        cheet = GameObject.Find("base");
        if(cheet == null)
            print("cheet does not exist");
    }

    public void toggle()
    {
        if(cheet != null)
            cheet.Setactive(isOpen);
        else
            print("cheet does not exist");
    }
}
</code>```

Body:
I have a script that should toggle active on my GameObject but when it disables it, it no longer finds the object.

Script:

GameObject cheet = GameObject.Find("base");

if (isOpen == true)
{
    cheet.SetActive(true);
}
else
{
    cheet.SetActive(false);
}


问:
making a list into dictionary
suppose you have a list

```<code>A = ["A: 1", "B: 2", "C: 3"]
</code>```

can you make this into a dictionary of

```<code>dict_A = {"A" : 1, "B": 2, "C": 3}
</code>```

I got stuck at making the list into a dictionary

答:
One nice way of doing this:

```<code>A = ["A: 1", "B: 2", "C: 3"]

A = [item.split(':') for item in A]
dict_A = dict([[key, int(val)] for key, val in A])

print(dict_A)
>>  {'A': 1, 'B': 2, 'C': 3}
</code>```

to break down each line and what it returns:

```<code>A = [item.split(':') for item in A]
>> [['A', ' 1'], ['B', ' 2'], ['C', ' 3']]
</code>```

After first splitting on :, each index in A now holds a list of two items. and each index of A can be unpacked. For example: first, second = A[1] is the same as first, second = A[1][0], A[1][1] ; in both cases  'B' would be assigned to first and '2' to second

Considering that all the numbers are still strings they need to be converted to int, but we only want to convert the second item in each of our nested lists; this is where unpacking can be useful, as we would only apply the int conversion to the second item.

This can be done nicely in a single list comprehension

```<code>[[key, int(val)] for key, val in A]
>> [['A', 1], ['B', 2], ['C', 3]]
</code>```

but, considering that you want a dictionary, we can just call dict() to convert into dictionary

```<code>dict([['A', 1], ['B', 2], ['C', 3]])
>> {'A': 1, 'B': 2, 'C': 3}
</code>```

Title: making a list into dictionary

Body:
suppose you have a list

A = ["A: 1", "B: 2", "C: 3"]

can you make this into a dictionary of

dict_A = {"A" : 1, "B": 2, "C": 3}

I got stuck at making the list into a dictionary

Body:
One nice way of doing this:

A = ["A: 1", "B: 2", "C: 3"]

A = [item.split(':') for item in A]
dict_A = dict([[key, int(val)] for key, val in A])

print(dict_A)
>>  {'A': 1, 'B': 2, 'C': 3}

to break down each line and what it returns:

A = [item.split(':') for item in A]
>> [['A', ' 1'], ['B', ' 2'], ['C', ' 3']]

After first splitting on :, each index in A now holds a list of two items. and each index of A can be unpacked. For example: first, second = A[1] is the same as first, second = A[1][0], A[1][1] ; in both cases  'B' would be assigned to first and '2' to second

Considering that all the numbers are still strings they need to be converted to int, but we only want to convert the second item in each of our nested lists; this is where unpacking can be useful, as we would only apply the int conversion to the second item.

This can be done nicely in a single list comprehension

[[key, int(val)] for key, val in A]
>> [['A', 1], ['B', 2], ['C', 3]]

but, considering that you want a dictionary, we can just call dict() to convert into dictionary

dict([['A', 1], ['B', 2], ['C', 3]])
>> {'A': 1, 'B': 2, 'C': 3}


问:
How to use vw and vh css with React Native
I'm creating a basic login using React Native with a logo and 2 inputs:

```<code>//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';

// create a component
class Login extends Component {
    render() {
        const imageURL = require('./images/CircleLogo.png');
        return (
            <View style={styles.container}>
                <View style={styles.loginContainer}>
                    <Image resizeMode="contain" style={styles.logo} source={imageURL} />
                </View>
                <View style={styles.formContainer}>
                    <LoginForm />
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'aliceblue',
    },
    loginContainer:{
        alignItems: 'center',
        flexGrow: 1,
        justifyContent: 'center'
    },
    logo: {
        position: 'absolute',
        width: '70vw',
        height: '70vw',
        maxWidth: 300
    }
});

//make this component available to the app
export default Login;
</code>```

As you can see i am using vw and vh css measurements.

This works on the web, but not on iOS or Android.

Does anyone have a good suggestion for handling vw and vh measurements?

Side Note: It appears react accepts percentages as seen here, which I may revert to. But my question pertains to specifically the vw and vh measurements.

答:
Instead of veiwport you can use Dimensions in react-native. PFB the link of react-native Dimensions.

https://reactnative.dev/docs/dimensions

Here is an example:

import { Dimensions } from 'react-native'

const halfWindowsWidth = Dimensions.get('window').width / 2
```

Body:
I'm creating a basic login using React Native with a logo and 2 inputs:

//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';

// create a component
class Login extends Component {
    render() {
        const imageURL = require('./images/CircleLogo.png');
        return (
            <View style={styles.container}>
                <View style={styles.loginContainer}>
                    <Image resizeMode="contain" style={styles.logo} source={imageURL} />
                </View>
                <View style={styles.formContainer}>
                    <LoginForm />
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'aliceblue',
    },
    loginContainer:{
        alignItems: 'center',
        flexGrow: 1,
        justifyContent: 'center'
    },
    logo: {
        position: 'absolute',
        width: '70vw',
        height: '70vw',
        maxWidth: 300
    }
});

//make this component available to the app
export default Login;

As you can see i am using vw and vh css measurements.

This works on the web, but not on iOS or Android.

Does anyone have a good suggestion for handling vw and vh measurements?

Side Note: It appears react accepts percentages as seen here, which I may revert to. But my question pertains to specifically the vw and vh measurements.


问:
java.lang.IllegalArgumentException: Couldn't find network parameters file and compatibility zone wasn't configured/isn't reachable
After run this command java -jar network-bootstrapper-4.1.jar --dir  it could generate the network parameter file.but it doesn't generate the network parameter file

And i attached the node.conf file.

```<code> myLegalName="O=Notary,L=Mumbai,C=IN"
        notary {
            validating=true
        }
        p2pAddress="localhost:9006"
        rpcUsers=[]
        devMode : true
</code>```

答:
We don't have more context around the question to determine how to solve your problem here, but I will say that in the latest version of corda; generally when running the bootstrapper you'll want to pass a directory of nodes.

java -jar network-bootstrapper-4.4.jar --dir

Each of the files in that folder should have a node.conf file that is unique so that the bootstrapper can generate the correct files.

However there are newer tools for running corda nodes / networks more easily. if you take a look at some of the developer samples they now provide gradle tasks for you to build and run your corda nodes.

link to other corda sample apps : https://github.com/corda/samples-java/tree/master/Basic/yo-cordapp

source docs: https://docs.corda.net/docs/corda-os/4.4/network-bootstrapper.html

Body:
After run this command java -jar network-bootstrapper-4.1.jar --dir  it could generate the network parameter file.but it doesn't generate the network parameter file

And i attached the node.conf file.

 myLegalName="O=Notary,L=Mumbai,C=IN"
        notary {
            validating=true
        }
        p2pAddress="localhost:9006"
        rpcUsers=[]
        devMode : true


问:
Using R to extract sums from a raster layer, in areas outside potentially overlapping buffers
I am very new to raster data and the use of R for spatial data analysis, so apologies if there's an obvious solution or process for this I've missed.

I have a raster file of population data from WorldPop, and a set of latitude / longitude location points that overlay onto that. I am trying to determine what portion of the population is (according to the WorldPop estimates) within a given distance of these points of interest, and also what portion is not.

I understand that using raster::extract, I should be able to get the sum of population values from (for example) a 1-kilometer buffer around each of these points. (Although my points and raster data are both in lat/lon projection, so I gather I need to first correct for this by changing the projection to utm as done here.)

However, because some number of these points will be less than 1 km apart, I am concerned that this total sum is double-counting the population of some cells where buffers overlap. Does buffering automatically correct for this, or is there an efficient way to ensure that this is not the case, and also to get the values from the inverse of the buffered point area selection?

答:
Here is a minimal self-contained reproducible example,

```<code>library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
d <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85,
   66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31,
   22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
p <- SpatialPoints(d, proj4string=crs(r))
</code>```

A simple workflow, with points p and raster r would be

```<code>b <- buffer(p, 10)
m <- mask(r, b)
ms <- cellStats(m, "sum")
rs <- cellStats(r, "sum")
ms/rs
#[1] 0.4965083
</code>```

Or you can use terra, to make this go faster, like this

```<code>library(terra)
r <- rast(system.file("ex/logo.tif", package="terra")) [[1]]
p <- vect(d, crs=crs(r))

b <- buffer(p, 10)
m <- mask(r, b)
ms <- global(m, "sum", na.rm=TRUE)
rs <- global(r, "sum")
ms/rs
</code>```

By the way, with the raster package your assertion about needing to transform lon/lat data is not correct for extract or buffer. In contrast, with terra you need to do that (to be fixed).

Body:
Here is a minimal self-contained reproducible example,

library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
d <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85,
   66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31,
   22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
p <- SpatialPoints(d, proj4string=crs(r))

A simple workflow, with points p and raster r would be

b <- buffer(p, 10)
m <- mask(r, b)
ms <- cellStats(m, "sum")
rs <- cellStats(r, "sum")
ms/rs
#[1] 0.4965083

Or you can use terra, to make this go faster, like this

library(terra)
r <- rast(system.file("ex/logo.tif", package="terra")) [[1]]
p <- vect(d, crs=crs(r))

b <- buffer(p, 10)
m <- mask(r, b)
ms <- global(m, "sum", na.rm=TRUE)
rs <- global(r, "sum")
ms/rs

By the way, with the raster package your assertion about needing to transform lon/lat data is not correct for extract or buffer. In contrast, with terra you need to do that (to be fixed).


问:
Behavior of after() method inside a for loop in Tkinter GUI
In my sample GUI code, I want to print two different string one after another multiple times. I want some time duration between each string print on the console. I used root.after() method for this and iterate inside 'for loop' to achieve multiple time print.
Here is my code.

```<code>import tkinter as tk
from tkinter import *

def display1():
    print('hello world!')

def display2():
    print('hello there!')

def print_it():
    for i in range(2):
        root.after(7000,display1)   #to print after seven second.
        root.after(7000+5000,display2)  #to print after five second of first sentence print.

root = tk.Tk()
root.title("testing")
root.geometry('100x100')

btn = tk.Button(root,text='click it',command=print_it)
btn.pack(side = TOP)
root.mainloop()
</code>```

The problem is in spite of printing one after another, both strings are printing together and not after a given time. I cannot understand the behavior of the after() method. What am I doing wrong?

Thank you.

答:
Let's look at this code:

```<code>def print_it():
    for i in range(2):
        root.after(7000,display1)
        root.after(7000+5000,display2)
</code>```

Let's assume that "now" is 12:00.000. When this code runs, the first iteration of the loop will schedule something for 12:07.000, and then another one at 12:12.000. This process maybe takes a millisecond or two. Let's assume it takes 10 milliseconds

The second time through the loop we're now at 12:00.010 since the first iteration took 10ms, so you then schedule something to run at 12:07.010, and then again at 12:12.010.

So now the "after" queue looks like this:

display1@12:07.000

display1:12:07.010

display2@12:12.000

display2@12:12.010

It's important to remember that after schedules a job in the future relative to the current moment, not relative to the previous time after was called.

Body:
In my sample GUI code, I want to print two different string one after another multiple times. I want some time duration between each string print on the console. I used root.after() method for this and iterate inside 'for loop' to achieve multiple time print.
Here is my code.

import tkinter as tk
from tkinter import *

def display1():
    print('hello world!')

def display2():
    print('hello there!')

def print_it():
    for i in range(2):
        root.after(7000,display1)   #to print after seven second.
        root.after(7000+5000,display2)  #to print after five second of first sentence print.

root = tk.Tk()
root.title("testing")
root.geometry('100x100')

btn = tk.Button(root,text='click it',command=print_it)
btn.pack(side = TOP)
root.mainloop()

The problem is in spite of printing one after another, both strings are printing together and not after a given time. I cannot understand the behavior of the after() method. What am I doing wrong?

Thank you.

Body:
Let's look at this code:

def print_it():
    for i in range(2):
        root.after(7000,display1)
        root.after(7000+5000,display2)

Let's assume that "now" is 12:00.000. When this code runs, the first iteration of the loop will schedule something for 12:07.000, and then another one at 12:12.000. This process maybe takes a millisecond or two. Let's assume it takes 10 milliseconds

The second time through the loop we're now at 12:00.010 since the first iteration took 10ms, so you then schedule something to run at 12:07.010, and then again at 12:12.010.

So now the "after" queue looks like this:

display1@12:07.000

display1:12:07.010

display2@12:12.000

display2@12:12.010

It's important to remember that after schedules a job in the future relative to the current moment, not relative to the previous time after was called.


问:
parse a byte string from a binary input using php
I'm very new to PHP.
I need some help parsing a byte string from a binary input.

```<code>For example : input= 020104020107020108020103.
</code>```

From the example, I need to extract any byte after 0201.

```<code> I mean --> 04, 07, 08, 03.
</code>```

Save every value to a variable and identify the last one.

答:
If you are certain that every byte will be prefixed with 0201 and that every byte will use up 2 characters, then you can use the following code:

```<code><?php

$input = "020104020107020108020103";
$bytes = [];

for ($i = 4; $i < strlen($input); ++$i) {
    $byte = substr($input, $i, 2);

    array_push($bytes, $byte);

    // 1 byte + 4 byte (0201 offset)
    $i += 5;
}

print_r($bytes);
</code>```

Body:
I'm very new to PHP.
I need some help parsing a byte string from a binary input.

For example : input= 020104020107020108020103.

From the example, I need to extract any byte after 0201.

 I mean --> 04, 07, 08, 03.

Save every value to a variable and identify the last one.

Body:
If you are certain that every byte will be prefixed with 0201 and that every byte will use up 2 characters, then you can use the following code:

<?php

$input = "020104020107020108020103";
$bytes = [];

for ($i = 4; $i < strlen($input); ++$i) {
    $byte = substr($input, $i, 2);

    array_push($bytes, $byte);

    // 1 byte + 4 byte (0201 offset)
    $i += 5;
}

print_r($bytes);


问:
ESP32 Doesn't see Wifi network while scanning?
I am trying to use ESP32 to scan networks. While my code running on ESP32-Wrover-kit works without problem and returns lots of networks, same code od ESP32 Wrover-IB doesn't do that, it only returns one.

What would be the reason that old ESP32 on kit works and new one doesn't.

New ESP32 datasheet: https://hr.mouser.com/datasheet/2/891/esp32-wrover-b_datasheet_en-1384674.pdf

ESP32 Wrover kit: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-wrover-kit.html

```<code>#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_event.h"
#include "nvs_flash.h"

/* UART */
#include "driver/uart.h"
#include "driver/gpio.h"
#define BUF_SIZE (1024)
/* UART */

#define DEFAULT_SCAN_LIST_SIZE CONFIG_EXAMPLE_SCAN_LIST_SIZE

#define ECHO_TEST_TXD  (GPIO_NUM_4)
#define ECHO_TEST_RXD  (GPIO_NUM_5)
#define ECHO_TEST_RTS  (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS  (UART_PIN_NO_CHANGE)

static const char *TAG = "scan";

void uart_init() {
    const uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };
    uart_param_config(UART_NUM_1, &uart_config);

    uart_set_pin(UART_NUM_1, GPIO_NUM_25, GPIO_NUM_27, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    uart_driver_install(UART_NUM_1, BUF_SIZE * 2, 0, 0, NULL, 0);
}

int sendData(const char* logName, const char* data)
{
    const int len = strlen(data);
    const int txBytes = uart_write_bytes(UART_NUM_1, data, len);
    //ESP_LOGI(logName, "Wrote %d bytes", txBytes);
    return txBytes;
}

/* Initialize Wi-Fi as sta and set scan method */
static void wifi_scan(void)
{

    char buffer[64];

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    uint16_t number = DEFAULT_SCAN_LIST_SIZE;
    wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
    uint16_t ap_count = 0;
    memset(ap_info, 0, sizeof(ap_info));

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());

    while(1){
        ESP_ERROR_CHECK(esp_wifi_scan_start(NULL, true));
        ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));
        ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));

        ESP_LOGI(TAG, "Total APs scanned = %u", ap_count);
        ESP_LOGI(TAG, "-------------------------------");
        for (int i = 0; (i < DEFAULT_SCAN_LIST_SIZE) && (i < ap_count); i++) {

            ESP_LOGI(TAG, "{\"macAddress\":\"%x:%x:%x:%x:%x:%x\",\"signalStrength\": %d}",ap_info[i].bssid[0],
                                                    ap_info[i].bssid[1],
                                                    ap_info[i].bssid[2],
                                                    ap_info[i].bssid[3],
                                                    ap_info[i].bssid[4],
                                                    ap_info[i].bssid[5],
                                                    ap_info[i].rssi);
        }
        ESP_LOGI(TAG, "-------------------------------");

        vTaskDelay(4000 / portTICK_PERIOD_MS);
    }

}

void app_main(void)
{

    // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK( ret );

    uart_init();
    wifi_scan();

}
</code>```

答: External antenna on this exact module is required, adding antenna fixed the problem.

Body:
I am trying to use ESP32 to scan networks. While my code running on ESP32-Wrover-kit works without problem and returns lots of networks, same code od ESP32 Wrover-IB doesn't do that, it only returns one.

What would be the reason that old ESP32 on kit works and new one doesn't.

New ESP32 datasheet: https://hr.mouser.com/datasheet/2/891/esp32-wrover-b_datasheet_en-1384674.pdf

ESP32 Wrover kit: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-wrover-kit.html

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_event.h"
#include "nvs_flash.h"

/* UART */
#include "driver/uart.h"
#include "driver/gpio.h"
#define BUF_SIZE (1024)
/* UART */

#define DEFAULT_SCAN_LIST_SIZE CONFIG_EXAMPLE_SCAN_LIST_SIZE

#define ECHO_TEST_TXD  (GPIO_NUM_4)
#define ECHO_TEST_RXD  (GPIO_NUM_5)
#define ECHO_TEST_RTS  (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS  (UART_PIN_NO_CHANGE)

static const char *TAG = "scan";

void uart_init() {
    const uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_APB,
    };
    uart_param_config(UART_NUM_1, &uart_config);

    uart_set_pin(UART_NUM_1, GPIO_NUM_25, GPIO_NUM_27, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    uart_driver_install(UART_NUM_1, BUF_SIZE * 2, 0, 0, NULL, 0);
}

int sendData(const char* logName, const char* data)
{
    const int len = strlen(data);
    const int txBytes = uart_write_bytes(UART_NUM_1, data, len);
    //ESP_LOGI(logName, "Wrote %d bytes", txBytes);
    return txBytes;
}

/* Initialize Wi-Fi as sta and set scan method */
static void wifi_scan(void)
{

    char buffer[64];

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    uint16_t number = DEFAULT_SCAN_LIST_SIZE;
    wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
    uint16_t ap_count = 0;
    memset(ap_info, 0, sizeof(ap_info));

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());

    while(1){
        ESP_ERROR_CHECK(esp_wifi_scan_start(NULL, true));
        ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));
        ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));

        ESP_LOGI(TAG, "Total APs scanned = %u", ap_count);
        ESP_LOGI(TAG, "-------------------------------");
        for (int i = 0; (i < DEFAULT_SCAN_LIST_SIZE) && (i < ap_count); i++) {

            ESP_LOGI(TAG, "{\"macAddress\":\"%x:%x:%x:%x:%x:%x\",\"signalStrength\": %d}",ap_info[i].bssid[0],
                                                    ap_info[i].bssid[1],
                                                    ap_info[i].bssid[2],
                                                    ap_info[i].bssid[3],
                                                    ap_info[i].bssid[4],
                                                    ap_info[i].bssid[5],
                                                    ap_info[i].rssi);
        }
        ESP_LOGI(TAG, "-------------------------------");

        vTaskDelay(4000 / portTICK_PERIOD_MS);
    }

}

void app_main(void)
{

    // Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK( ret );

    uart_init();
    wifi_scan();

}


问:
C - Printing null character using %c in nested printf statement
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:</p>

```<code>#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}
</code>```

答:
```<code>#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
</code>```

The inner call to printf() prints a null character (you don't see it) and returns 1 as the number of characters printed, which is then printed as the string 1 (you get a null plus a digit 1).

```<code>    // This line will print 1.

    printf("%d",printf("\0")) ;
</code>```

In this case, you supply a string literal ended in two consecutive null chars, which results on printing an empty string (literally "") and that results in passing to the second printf a 0 and the second printf prints it as the string 0.

```<code>    // This line will print 0.
   return 0;
}
</code>```

So, you are wrong, in the first case you got a null character printed (a true \0 befpre tje 1. But a null is ignored by the terminal you are using and it doesn't show in your screen, while the second doesn't print anything·)

NOTE

Every C language string related function, explores the string to know how long it is, or when to stop the task it is doing.  Putting more than the default string literal's last null char \0 does nothing but shorten the useful part of the string literal.  If you try to print "Se está quemando la serrería\0... Duduap!!" or operate on it with any of the string related functions, you'll get the same result as if you had stopped before the first \0 character.  So the string literal above is basically equivalent to just "Se está quemando la serrería"

Body:
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:

#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}

Body:
#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;

The inner call to printf() prints a null character (you don't see it) and returns 1 as the number of characters printed, which is then printed as the string 1 (you get a null plus a digit 1).

    // This line will print 1.

    printf("%d",printf("\0")) ;

In this case, you supply a string literal ended in two consecutive null chars, which results on printing an empty string (literally "") and that results in passing to the second printf a 0 and the second printf prints it as the string 0.

    // This line will print 0.
   return 0;
}

So, you are wrong, in the first case you got a null character printed (a true \0 befpre tje 1. But a null is ignored by the terminal you are using and it doesn't show in your screen, while the second doesn't print anything·)

NOTE

Every C language string related function, explores the string to know how long it is, or when to stop the task it is doing.  Putting more than the default string literal's last null char \0 does nothing but shorten the useful part of the string literal.  If you try to print "Se está quemando la serrería\0... Duduap!!" or operate on it with any of the string related functions, you'll get the same result as if you had stopped before the first \0 character.  So the string literal above is basically equivalent to just "Se está quemando la serrería"


问:
Calling INSERT statements in MS SQL (Azure) from Python results in errors, NO COUNT ON does not work
I am a newbie so please bear with me. I am trying to do a very simple insert from Python into a MS SQL database. I have tried pure pyodbc resulting in "pyodbc.ProgrammingError: No results.  Previous SQL was not a query.":

```<code>import pyodbc
server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

query = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1)  "

cursor.execute(query)

row = cursor.fetchone()
while row:
    print (row)
    row = cursor.fetchone()
</code>```

And I have tried a combination of sqlalchemy, pyodbc and pandas resulting in "sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically."

```<code>import sqlalchemy
import pyodbc
import urllib
import pandas as pd

server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'

params = urllib.parse.quote_plus('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

sql = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1)"
sql_df = pd.read_sql(sql=sql, con = engine)
</code>```

I have tried playing around with SET NOCOUNT ON, putting the code into a stored procedure and calling the procedure and all kinds of other combinations. Nothing seems to work.

I would greatly appreciate any help. Thank you.

答:
Why do you use the SET NOCOUNT ON?

Remove it and it will do the insert.

What do you expect to get with row = cursor.fetchone()?

You didn't wrote a select query you which results you expect to get?

Body:
I am a newbie so please bear with me. I am trying to do a very simple insert from Python into a MS SQL database. I have tried pure pyodbc resulting in "pyodbc.ProgrammingError: No results.  Previous SQL was not a query.":

import pyodbc
server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

query = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1)  "

cursor.execute(query)

row = cursor.fetchone()
while row:
    print (row)
    row = cursor.fetchone()

And I have tried a combination of sqlalchemy, pyodbc and pandas resulting in "sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically."

import sqlalchemy
import pyodbc
import urllib
import pandas as pd

server = 'server'
database = 'db'
username = 'user'
password = 'pswd'
driver= '{ODBC Driver 17 for SQL Server}'

params = urllib.parse.quote_plus('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

sql = "SET NOCOUNT ON INSERT INTO foo ([x],[y],[z]) VALUES(1,1,1)"
sql_df = pd.read_sql(sql=sql, con = engine)

I have tried playing around with SET NOCOUNT ON, putting the code into a stored procedure and calling the procedure and all kinds of other combinations. Nothing seems to work.

I would greatly appreciate any help. Thank you.


问:
If GridSearchCV gives a few estimators with rank 1, which one will it pick as the best estimator?
Using Scikit-learn's GridSearchCV, if GridSearchCV gives a few estimators with rank 1, which one will it pick as the best estimator best_estimator_? Will it pick the first estimator in the list that appears in cv_results_?

Unless if I am going blind, I can't seem to find this in the documentation here: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

Many thanks in advance.

答:
Yes, it (currently) picks the first one in cv_results_.  From the source, it just takes argmin, which according to the numpy docs picks the first index in case of ties.

(It doesn't seem like there's any reason to prefer that, so it seems relatively likely to change.  In particular, implementing a tie-breaker using lowest standard deviation or train score or time or ... seems worthwhile.)

As a quick experiment, use a meaningless (for performance) hyperparameter:

search = GridSearchCV(estimator=LogisticRegression(),
                      param_grid={'verbose': [0, 1, 2]})
search.fit(X, y)
print(search.cv_results_, search.best_params_)
```


问:
Label enabled issue
I set Label component enabled property to "false", it still can interactive,

```<code><mx:Label text="testEnable" click="handleEnable()" enabled="false"/>
</code>```

when I click the label, the handleEnable() can always be invoked, I want Label behaves like Button component(if set Button enabled, user can't interactive with it), so how can I do?

答: After setting the enabled property to false, some components still respond to mouse interactions such as mouseOver. As a result, to fully disable UIComponents, you should also set the value of the mouseEnabled property to false.

Title: Label enabled issue

Body:
I set Label component enabled property to "false", it still can interactive,

<mx:Label text="testEnable" click="handleEnable()" enabled="false"/>

when I click the label, the handleEnable() can always be invoked, I want Label behaves like Button component(if set Button enabled, user can't interactive with it), so how can I do?


问:
Custom methods for ggplot object
In {ggcharts} I created the diverging_bar_chat() function which rather than drawing a y axis uses geom_text() to directly annotate the bars.

data(mtcars)
mtcars_z <- dplyr::transmute(
  .data = mtcars[1:10, ],
  model = row.names(mtcars[1:10, ]),
  hpz = scale(hp)
)

(p <- ggcharts::diverging_bar_chart(mtcars_z, model, hpz))
```

<p><img src="https://i.stack.imgur.com/iUnNP.png" alt="enter image description here"></p>

<p>When I add any theme to this function the usual y axis pops up again.</p>

<pre class="lang-r prettyprint-override"><code>p + ggplot2::theme_bw()
</code>```

While this is to be expected, it's quite undesirable behavior from a user perspective. That's why I'm looking for ways to add a theme in the usual {ggplot2} manner but always remove the y axis, essentially like this function does:

add_theme <- function(diverging_chart, theme) {
  diverging_chart +
    theme +
    theme(
      axis.ticks.y = element_blank(),
      axis.title.y = element_blank(),
      axis.text.y = element_blank(),
      axis.line.y = element_blank()
    )
}
```

<p>I have tried to define a S3 class for the output of <code>diverging_bar_chart()</code> to be able to define custom methods. However <code>+</code> only works when both the left hand side and the right hand side inherit from the same class. That's why everything in <code>{ggplot2}</code> inherits from <code>gg</code>.</p>

<p>In the <code>{vctrs}</code> vignette I learned about the notion of double dispatch with S3 vectors. However, trying to implement it did not work for me.</p>

<pre class="lang-r prettyprint-override"><code>class(p) <- c("diverging_chart", class(p))
`+.diverging_chart.theme` <- function(chart, theme) {
  add_theme(chart, theme)
}
p + theme_bw()
</code>```

At this point I am stuck. My only remaining idea would be to create an S4 class but I'd like to avoid that if possible.

答:
I think there is a far simpler solution than trying to get the S3 double dispatch working for LHS objects in ggplot's + operator, and that is to simply set the y-axis guide to an empty guide.

As package developer it shouldn't be too difficult to implement this at the correct level.

Illustrated below:

library(ggplot2)
library(ggcharts)

data(mtcars)
mtcars_z <- dplyr::transmute(
  .data = mtcars[1:10, ],
  model = row.names(mtcars[1:10, ]),
  hpz = scale(hp)
)

div_bar_chart <- function(data, ...) {
  ggcharts::diverging_bar_chart(data, ...) +
    guides(y = guide_none())
}

(p <- div_bar_chart(mtcars_z, model, hpz))
```

<p><img src="https://i.imgur.com/rHzWTqU.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>p + theme_bw()
</code>```

Created on 2020-06-01 by the reprex package (v0.3.0)

As an aside, the developer of the 'ggally' package also proposed custom LHS methods for the + operator here.

Title: Custom methods for ggplot object

Body:
In {ggcharts} I created the diverging_bar_chat() function which rather than drawing a y axis uses geom_text() to directly annotate the bars.

data(mtcars)
mtcars_z <- dplyr::transmute(
  .data = mtcars[1:10, ],
  model = row.names(mtcars[1:10, ]),
  hpz = scale(hp)
)

(p <- ggcharts::diverging_bar_chart(mtcars_z, model, hpz))

When I add any theme to this function the usual y axis pops up again.

p + ggplot2::theme_bw()

While this is to be expected, it's quite undesirable behavior from a user perspective. That's why I'm looking for ways to add a theme in the usual {ggplot2} manner but always remove the y axis, essentially like this function does:

add_theme <- function(diverging_chart, theme) {
  diverging_chart +
    theme +
    theme(
      axis.ticks.y = element_blank(),
      axis.title.y = element_blank(),
      axis.text.y = element_blank(),
      axis.line.y = element_blank()
    )
}

I have tried to define a S3 class for the output of diverging_bar_chart() to be able to define custom methods. However + only works when both the left hand side and the right hand side inherit from the same class. That's why everything in {ggplot2} inherits from gg.

In the {vctrs} vignette I learned about the notion of double dispatch with S3 vectors. However, trying to implement it did not work for me.

class(p) <- c("diverging_chart", class(p))
`+.diverging_chart.theme` <- function(chart, theme) {
  add_theme(chart, theme)
}
p + theme_bw()

At this point I am stuck. My only remaining idea would be to create an S4 class but I'd like to avoid that if possible.

Body:
I think there is a far simpler solution than trying to get the S3 double dispatch working for LHS objects in ggplot's + operator, and that is to simply set the y-axis guide to an empty guide.

As package developer it shouldn't be too difficult to implement this at the correct level.

Illustrated below:

library(ggplot2)
library(ggcharts)

data(mtcars)
mtcars_z <- dplyr::transmute(
  .data = mtcars[1:10, ],
  model = row.names(mtcars[1:10, ]),
  hpz = scale(hp)
)

div_bar_chart <- function(data, ...) {
  ggcharts::diverging_bar_chart(data, ...) +
    guides(y = guide_none())
}

(p <- div_bar_chart(mtcars_z, model, hpz))

p + theme_bw()

Created on 2020-06-01 by the reprex package (v0.3.0)

As an aside, the developer of the 'ggally' package also proposed custom LHS methods for the + operator here.


问:
How to assign instances of a class as a property for the same class in the class body?
In class A, I want some 'special' values to be stored as class properties.  The following doesn't work for understandable reasons:

```<code>class A:

   def __init__(self, msg):
        self.s = msg

   X = A("special message")
</code>```

I could use:

```<code>class A:

   def __init__(self, msg):
        self.s = msg

A.X = A("special message")  # outside of the class
</code>```

But it seems untidy and easily forgotten (suppose class A was long).  Is there a neat way to initialize a class variable of A with an instance of A inside the class itself?

答:
Is there a neat way to initialize a class variable of A with an instance of A inside the class itself?

NO, you can't initialize a class property with an instance of same class inside the class ** because the body of your class is executed first and your class is not defined until the execution of body is completed. But maybe you can use a decorator. I'm not sure if you prefer it over A.X = A("special message") but here you go:

def add_class_property(name, arg):
    class ClassWrapper:
        def __init__(self, cls):
            self.other_class = cls
            setattr(self, name, cls(arg))

        def __call__(self, *cls_ars):
            return self.other_class(*cls_ars)

    return ClassWrapper

@add_class_property("X", "special message")
class A:
    def __init__(self, msg):
        self.s = msg

print(A.X.s)

# Output:
# special message

```
<p>If you want to assign multiple instances at once, you can do this:</p>
<pre class="lang-py prettyprint-override"><code>def add_class_properties(**kwargs):
    class ClassWrapper:
        def __init__(self, cls):
            self.other_class = cls
            for key, val in kwargs.items():
                setattr(self, key, cls(val))

        def __call__(self, *cls_ars):
            return self.other_class(*cls_ars)

    return ClassWrapper

@add_class_properties(X="special message", Y="another message")
class A:
    def __init__(self, msg):
        self.s = msg

print(A.X.s)
print(A.Y.s)
</code>```
```
special message
another message
```

**: You can do it inside the methods of your class, however that's a different thing.

Body:
In class A, I want some 'special' values to be stored as class properties.  The following doesn't work for understandable reasons:

class A:

   def __init__(self, msg):
        self.s = msg

   X = A("special message")

I could use:

class A:

   def __init__(self, msg):
        self.s = msg

A.X = A("special message")  # outside of the class

But it seems untidy and easily forgotten (suppose class A was long).  Is there a neat way to initialize a class variable of A with an instance of A inside the class itself?

Body:
Is there a neat way to initialize a class variable of A with an instance of A inside the class itself?

NO, you can't initialize a class property with an instance of same class inside the class ** because the body of your class is executed first and your class is not defined until the execution of body is completed. But maybe you can use a decorator. I'm not sure if you prefer it over A.X = A("special message") but here you go:

def add_class_property(name, arg):
    class ClassWrapper:
        def __init__(self, cls):
            self.other_class = cls
            setattr(self, name, cls(arg))

        def __call__(self, *cls_ars):
            return self.other_class(*cls_ars)

    return ClassWrapper

@add_class_property("X", "special message")
class A:
    def __init__(self, msg):
        self.s = msg

print(A.X.s)

# Output:
# special message

If you want to assign multiple instances at once, you can do this:

def add_class_properties(**kwargs):
    class ClassWrapper:
        def __init__(self, cls):
            self.other_class = cls
            for key, val in kwargs.items():
                setattr(self, key, cls(val))

        def __call__(self, *cls_ars):
            return self.other_class(*cls_ars)

    return ClassWrapper

@add_class_properties(X="special message", Y="another message")
class A:
    def __init__(self, msg):
        self.s = msg

print(A.X.s)
print(A.Y.s)

special message
another message

**: You can do it inside the methods of your class, however that's a different thing.


问:
Hide createBottomTabNavigator Tabbar in React Native
In React Native 0.62 is it possible to hide on scroll the tabbar created with createBottomTabNavigator from reactnavigation.org ?

I'm curious if it's possible in a similar way that LinkedIn has, when you scroll down the page the tabbar disappears and when you scroll back up it reappears. Or it's only possible with a custom tabbar?

答:
yes, it is possible to hide bottomtabbar.

it is possible with both custom and default tab bar

we can use tabBarVisible option to hide and show. we can use onScroll and inside on scroll we can use dispatch to show and hide

here is demo: https://snack.expo.io/@nomi9995/tab-navigation-%7C-bottom-tab-hide

```<code>const getTabBarVisible = (route) => {
  const params = route.params;
  if (params) {
    if (params.tabBarVisible === false) {
      return false;
    }
  }
  return true;
};
</code>```

```<code><Tab.Screen
          name="Home"
          component={HomeScreen}
          options={({ route }) => ({
            tabBarVisible: getTabBarVisible(route),
         })}
 />
</code>```

Full Code:

```<code>  import * as React from "react";
  import { Text, View, ScrollView, Dimensions } from "react-native";
  import { NavigationContainer } from "@react-navigation/native";
  import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
  import { CommonActions } from "@react-navigation/native";

  const height = Dimensions.get("window").height;
  const width = Dimensions.get("window").width;

  class HomeScreen extends React.Component {
    offset = 0;
    onScrollHandler = (e) => {
      const currentOffset = e.nativeEvent.contentOffset.y;
      var direction = currentOffset > this.offset ? "down" : "up";
      this.offset = currentOffset;
      if (direction === "down") {
        this.props.navigation.dispatch(
          CommonActions.setParams({
            tabBarVisible: false,
          })
        );
      } else {
        this.props.navigation.dispatch(
          CommonActions.setParams({
            tabBarVisible: true,
          })
        );
      }
    };
    render() {
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <ScrollView
            showsVerticalScrollIndicator={false}
            scrollEventThrottle={16}
            onScroll={this.onScrollHandler}
          >
            <View
              style={{
                alignItems: "center",
                height: height * 2,
                width: width,
                backgroundColor: "red",
              }}
            >
              <View
                style={{
                  backgroundColor: "blue",
                  width: 100,
                  height: height * 2,
                }}
              />
            </View>
          </ScrollView>
        </View>
      );
    }
  }

  function SettingsScreen() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Settings!</Text>
      </View>
    );
  }

  const Tab = createBottomTabNavigator();

  const getTabBarVisible = (route) => {
    const params = route.params;
    if (params) {
      if (params.tabBarVisible === false) {
        return false;
      }
    }
    return true;
  };

  class MyTabs extends React.Component {
    render() {
      return (
        <Tab.Navigator>
          <Tab.Screen
            name="Home"
            component={HomeScreen}
            options={({ route }) => ({
              tabBarVisible: getTabBarVisible(route),
            })}
          />
          <Tab.Screen name="Settings" component={SettingsScreen} />
        </Tab.Navigator>
      );
    }
  }

  export default function App() {
    return (
      <NavigationContainer>
        <MyTabs />
      </NavigationContainer>
    );
  }

</code>```

Body:
yes, it is possible to hide bottomtabbar.

it is possible with both custom and default tab bar

we can use tabBarVisible option to hide and show. we can use onScroll and inside on scroll we can use dispatch to show and hide

here is demo: https://snack.expo.io/@nomi9995/tab-navigation-%7C-bottom-tab-hide

const getTabBarVisible = (route) => {
  const params = route.params;
  if (params) {
    if (params.tabBarVisible === false) {
      return false;
    }
  }
  return true;
};

<Tab.Screen
          name="Home"
          component={HomeScreen}
          options={({ route }) => ({
            tabBarVisible: getTabBarVisible(route),
         })}
 />

Full Code:

  import * as React from "react";
  import { Text, View, ScrollView, Dimensions } from "react-native";
  import { NavigationContainer } from "@react-navigation/native";
  import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
  import { CommonActions } from "@react-navigation/native";

  const height = Dimensions.get("window").height;
  const width = Dimensions.get("window").width;

  class HomeScreen extends React.Component {
    offset = 0;
    onScrollHandler = (e) => {
      const currentOffset = e.nativeEvent.contentOffset.y;
      var direction = currentOffset > this.offset ? "down" : "up";
      this.offset = currentOffset;
      if (direction === "down") {
        this.props.navigation.dispatch(
          CommonActions.setParams({
            tabBarVisible: false,
          })
        );
      } else {
        this.props.navigation.dispatch(
          CommonActions.setParams({
            tabBarVisible: true,
          })
        );
      }
    };
    render() {
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <ScrollView
            showsVerticalScrollIndicator={false}
            scrollEventThrottle={16}
            onScroll={this.onScrollHandler}
          >
            <View
              style={{
                alignItems: "center",
                height: height * 2,
                width: width,
                backgroundColor: "red",
              }}
            >
              <View
                style={{
                  backgroundColor: "blue",
                  width: 100,
                  height: height * 2,
                }}
              />
            </View>
          </ScrollView>
        </View>
      );
    }
  }

  function SettingsScreen() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Settings!</Text>
      </View>
    );
  }

  const Tab = createBottomTabNavigator();

  const getTabBarVisible = (route) => {
    const params = route.params;
    if (params) {
      if (params.tabBarVisible === false) {
        return false;
      }
    }
    return true;
  };

  class MyTabs extends React.Component {
    render() {
      return (
        <Tab.Navigator>
          <Tab.Screen
            name="Home"
            component={HomeScreen}
            options={({ route }) => ({
              tabBarVisible: getTabBarVisible(route),
            })}
          />
          <Tab.Screen name="Settings" component={SettingsScreen} />
        </Tab.Navigator>
      );
    }
  }

  export default function App() {
    return (
      <NavigationContainer>
        <MyTabs />
      </NavigationContainer>
    );
  }


问:
how to get the inverse of a log10 value in python?
```<code>y=np.log10(train_set["SalePrice"])
</code>```

how do i find inverse of this ?? I want it to return back to the original value and not the scaled value

答:
y = np.log10(train_set["SalePrice"])

return back to the original value all of array elements

```<code>Z = np.array(10**y)
</code>```

Body:
y=np.log10(train_set["SalePrice"])

how do i find inverse of this ?? I want it to return back to the original value and not the scaled value

Body:
y = np.log10(train_set["SalePrice"])

return back to the original value all of array elements

Z = np.array(10**y)


问:
How to fit large text in AG-Grid Header?
I set .ag-header-cell-label .ag-header-cell-text {white-space:break-spaces !important;} in order to see the full text when width is not enough.But when text is very long like below

```<code>headerName: 'Age of Athlete and asdadfsdf fgdsfgdsfg sdfgsdfgsdfg',
</code>```

you can see that it doesn't fit.I increased the height of row but nothing changed.How can I fit long text doesnt matter how much long it is?

Plunker : https://plnkr.co/edit/UtfwvTOhpRDivBu5

答: You can add like this headerHeight : 150 inside gridOptions to increase the header height if the header text is too long. Because adding this line.ag-header-cell-label .ag-header-cell-text {white-space:break-spaces !important;} you will only get the text in multiple lines with the previous height. Try it and if it won't work comment here again.

Body:
I set .ag-header-cell-label .ag-header-cell-text {white-space:break-spaces !important;} in order to see the full text when width is not enough.But when text is very long like below

headerName: 'Age of Athlete and asdadfsdf fgdsfgdsfg sdfgsdfgsdfg',

you can see that it doesn't fit.I increased the height of row but nothing changed.How can I fit long text doesnt matter how much long it is?

Plunker : https://plnkr.co/edit/UtfwvTOhpRDivBu5


问:
Downloaded Selenium Webdriver Java zip, but it is missing the selenium JARs
I downloaded the latest Selenium Webdriver zip file for Java and after I extracted it, I get a bunch of JAR files but missing the needed selenium-java-x.xx.x.jar file.

Selenium Client & WebDriver Language Bindings

http://www.seleniumhq.org/download/

Am I not extracting it correctly? I tried on both Mac and windows machine and I get these bunch of JARs instead.

Why do I not get the selenium JAR?

答:
Before changing or adding new JARs. Please check if Eclipse is taking the correct Java-SE version for execution. This can be verified while creating a new Java project. Select the latest Java-SE version installed on your machine from the drop-down list during project creation.
enter image description here


问:
Can't get remote ssh stdout output in cron, but in my terminal it works
I run into an issue last week that drives me crazy. I wrote a BASH script which does a remote ssh connection to acamai and than performs a simple 'ls'. I want to redirect the 'ls' sdtout output to a given file.

While the script itself works like a charm when run manually, it does not while it runs via cron. The cronjob runs as root and each command works as expected expect the ssh command. My System is Gentoo Linux and cron is the old but gold vixie-cron.

To reduce the 200 LOC I put the basics herein which alone (as a single script) are enough to demonstrate the problem.

```<code>#!/bin/bash
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin'
#set -x
shopt -s lastpipe
exec 2>log.out
(ssh -i <path to key> -o HostKeyAlgorithms=+ssh-dss -o StrictHostKeyChecking=no <account@example.com> 'ls -r <path>') > '/root/listing.txt'
</code>```

Even in -vvv debug mode of ssh I can see, that everything works...just except that I get no stdout output.
Than I tried something else that I found in another posting on the internet:

```<code>#!/bin/bash
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin'
#set -x
shopt -s lastpipe
exec 2>log.out
(ssh -T -i <path to key> -o HostKeyAlgorithms=+ssh-dss -o StrictHostKeyChecking=no <account@example.com> 'ls -r <path>' </dev/zero) > '/root/listing.txt'
</code>```

Drawback here, I start a ssh session that I can't close and I guess its due to /dev/zero.
Another approach was to TEE Pipe the sub-shell of the ssh command...this worked for a short time ( and why not yet anymore ?!)

Now I'm clueless and need help. Cron has its PATH, uses BASH etc. Curious my boss did that with success with java (and he hates BASH...).

Any explanation and helpful tips are greatly welcome.

答:
I have same issue, I make script for CRON and it gets output from remote SSH host.
If i run script manually - it works as should. But when CRON runs it - i get just a part of remote output.

I cant realise why its happening.

#!/bin/sh
pass=123
filelist=$(sshpass -p "$pass" ssh -q -tt -o StrictHostKeyChecking=no user@"10.10.10.10" "list")

filestring=$(echo "$filelist" | grep -Po "(\S+\s\S+\s+\d+\s\d{2}:\d{2}:\d{2}\s\d{4})\slist0\.lst")
filedate=${filestring% list0.lst}
echo $filedate
filestamp=$(date -d "$filedate" +"%s")
echo $filestamp
```

<p>When i get echos in file via CRON - there are date from 0:00:00 - field with date (echo $filedate) is empty. But when i run manually - i get normal date with time...</p>

<p>It really bother me.</p>

<p>Help?</p>

<p>I found solution - add "-tt" to ssh command and all input goes to variable.</p>

<pre class="lang-bash prettyprint-override"><code>filelist=$(sshpass -p "$pass" ssh -q -tt -o StrictHostKeyChecking=no user@"10.10.10.10" "list")
</code>```

Body:
I run into an issue last week that drives me crazy. I wrote a BASH script which does a remote ssh connection to acamai and than performs a simple 'ls'. I want to redirect the 'ls' sdtout output to a given file.

While the script itself works like a charm when run manually, it does not while it runs via cron. The cronjob runs as root and each command works as expected expect the ssh command. My System is Gentoo Linux and cron is the old but gold vixie-cron.

To reduce the 200 LOC I put the basics herein which alone (as a single script) are enough to demonstrate the problem.

#!/bin/bash
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin'
#set -x
shopt -s lastpipe
exec 2>log.out
(ssh -i <path to key> -o HostKeyAlgorithms=+ssh-dss -o StrictHostKeyChecking=no <account@example.com> 'ls -r <path>') > '/root/listing.txt'

Even in -vvv debug mode of ssh I can see, that everything works...just except that I get no stdout output.
Than I tried something else that I found in another posting on the internet:

#!/bin/bash
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin'
#set -x
shopt -s lastpipe
exec 2>log.out
(ssh -T -i <path to key> -o HostKeyAlgorithms=+ssh-dss -o StrictHostKeyChecking=no <account@example.com> 'ls -r <path>' </dev/zero) > '/root/listing.txt'

Drawback here, I start a ssh session that I can't close and I guess its due to /dev/zero.
Another approach was to TEE Pipe the sub-shell of the ssh command...this worked for a short time ( and why not yet anymore ?!)

Now I'm clueless and need help. Cron has its PATH, uses BASH etc. Curious my boss did that with success with java (and he hates BASH...).

Any explanation and helpful tips are greatly welcome.

Body:
I have same issue, I make script for CRON and it gets output from remote SSH host.
If i run script manually - it works as should. But when CRON runs it - i get just a part of remote output.

I cant realise why its happening.

#!/bin/sh
pass=123
filelist=$(sshpass -p "$pass" ssh -q -tt -o StrictHostKeyChecking=no user@"10.10.10.10" "list")

filestring=$(echo "$filelist" | grep -Po "(\S+\s\S+\s+\d+\s\d{2}:\d{2}:\d{2}\s\d{4})\slist0\.lst")
filedate=${filestring% list0.lst}
echo $filedate
filestamp=$(date -d "$filedate" +"%s")
echo $filestamp

When i get echos in file via CRON - there are date from 0:00:00 - field with date (echo $filedate) is empty. But when i run manually - i get normal date with time...

It really bother me.

Help?

I found solution - add "-tt" to ssh command and all input goes to variable.

filelist=$(sshpass -p "$pass" ssh -q -tt -o StrictHostKeyChecking=no user@"10.10.10.10" "list")