问:
mySQL: Variable LIMIT
I'm using a SQL-statement to retrieve the top 5 entries in a list:

```<code>SELECT ... FROM table ORDER BY someColumn DESC LIMIT 5
</code>```

The result will look something like this:

```<code>Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4
</code>```

If there are more results with a value like the fifth entry in the list (4 in the example), I would like to show them too. Is there a way to achieve this with a single query?

So let's say the complete lists looks like this:

```<code>Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4
Person H   4
Person I   4
------------
Person G   3
Person F   1
Person J   1
</code>```

How can I modify my query to return the first seven results? Obviosuly I can't use LIMIT 7 or WHERE Count >= 4, as I don't know that in advance.

答:
You mean you want the fist five results but also all other results which are tied in 5th place, right? One solution is to get the 5th result first - using a subquery - and then get what you need:

```<code>SELECT ...
FROM table
WHERE someColumn >=
    ( SELECT someColumn
      FROM table
      ORDER BY someColumn DESC
      LIMIT 4, 1                      <-- only the 5th
    )
ORDER BY someColumn DESC
</code>```

Title: mySQL: Variable LIMIT

Body:
I'm using a SQL-statement to retrieve the top 5 entries in a list:

SELECT ... FROM table ORDER BY someColumn DESC LIMIT 5

The result will look something like this:

Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4

If there are more results with a value like the fifth entry in the list (4 in the example), I would like to show them too. Is there a way to achieve this with a single query?

So let's say the complete lists looks like this:

Name       Count
Person B   10
Person D   8
Person A   5
Person E   5
Person C   4
Person H   4
Person I   4
------------
Person G   3
Person F   1
Person J   1

How can I modify my query to return the first seven results? Obviosuly I can't use LIMIT 7 or WHERE Count >= 4, as I don't know that in advance.

Body:
You mean you want the fist five results but also all other results which are tied in 5th place, right? One solution is to get the 5th result first - using a subquery - and then get what you need:

SELECT ...
FROM table
WHERE someColumn >=
    ( SELECT someColumn
      FROM table
      ORDER BY someColumn DESC
      LIMIT 4, 1                      <-- only the 5th
    )
ORDER BY someColumn DESC


来源: stackexchange

问:
Translate ternary operator to if function
I tried to use if function inside the container to make the card is not showing when the data is null. However, it always give warning return an identifier.

I can make it using ternary operation, can someone help me to translate it into if function?

this is my code:

```<code>                        Container(
                            child: snapshot.data.notes == null
                                ? null
                                : Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                              )),
</code>```

答:
try using a function instead.

```<code>Widget _buildCard(snapshot){
    if(snapshot?.data?.notes == null){
      return null;
    }else{
      return Card(
        child: Padding(
          padding: EdgeInsets.symmetric(
              vertical: 0, horizontal: 8),
          child: Row(
            children: <Widget>[
              Icon(Icons.short_text),
              SizedBox(
                width: 8,
              ),
              Expanded(
                child: NotesDetail(
                  initialValue: snapshot.data.notes,
                  changeValue: (value) {
                    print(value);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    }
  }
</code>```

then call it in your container like this

```<code>Container(
  child: _buildCard(snapshot),
),
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to use if function inside the container to make the card is not showing when the data is null. However, it always give warning return an identifier.

I can make it using ternary operation, can someone help me to translate it into if function?

this is my code:

                        Container(
                            child: snapshot.data.notes == null
                                ? null
                                : Card(
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 0, horizontal: 8),
                                      child: Row(
                                        children: <Widget>[
                                          Icon(Icons.short_text),
                                          SizedBox(
                                            width: 8,
                                          ),
                                          Expanded(
                                            child: NotesDetail(
                                              initialValue: snapshot.data.notes,
                                              changeValue: (value) {
                                                print(value);
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                              )),

Body:
try using a function instead.

Widget _buildCard(snapshot){
    if(snapshot?.data?.notes == null){
      return null;
    }else{
      return Card(
        child: Padding(
          padding: EdgeInsets.symmetric(
              vertical: 0, horizontal: 8),
          child: Row(
            children: <Widget>[
              Icon(Icons.short_text),
              SizedBox(
                width: 8,
              ),
              Expanded(
                child: NotesDetail(
                  initialValue: snapshot.data.notes,
                  changeValue: (value) {
                    print(value);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

then call it in your container like this

Container(
  child: _buildCard(snapshot),
),


问:
how to specified color in plot from matplotlib
I have player data from fifa 19. It has Composure, Penalties ability, and Nationality. I would like to plot in a figure with X axis is Composure and Y axis is Penalties ability, but i would like to color it if the player from some nationality. I have this code:

```<code>import pandas
import math
import matplotlib.pyplot as plt

df= pandas.read_csv('fifa19.csv')

n= len(df)
x=[]
y=[]
fig, ax=plt.subplots()
j=0
for i in range(n):
   if(not math.isnan(df['Composure'][i])
       and not math.isnan(df['Penalties'][i])):
       x.append(df['Composure'][i])
       y.append(df['Penalties'][i])
   if(df['Nationality'][i]=='Brazil'): #it supposed to be blue if the nationality is brazil else is default(correct me if i'm wrong)
       ax.plot(x, y, 'o', color='blue')

ax.set_xlabel('Composure attribute')
ax.set_ylabel('Penalties attribute')
fig.show()
</code>```

But it all turned to blue.
I have tried to change the loop like this:

```<code>if(df['Nationality'][i]=='Brazil'):
        ax.plot(x[i], y[i], 'o', color='blue')
</code>```

But it says 'IndexError: list index out of range'. Any idea how to color it using plot? Thank you for your help.

答: Are you only drawing if they are from Brazil? Otherwise, you could write an else statement and select the desired color</p>

Body:
I have player data from fifa 19. It has Composure, Penalties ability, and Nationality. I would like to plot in a figure with X axis is Composure and Y axis is Penalties ability, but i would like to color it if the player from some nationality. I have this code:

import pandas
import math
import matplotlib.pyplot as plt

df= pandas.read_csv('fifa19.csv')

n= len(df)
x=[]
y=[]
fig, ax=plt.subplots()
j=0
for i in range(n):
   if(not math.isnan(df['Composure'][i])
       and not math.isnan(df['Penalties'][i])):
       x.append(df['Composure'][i])
       y.append(df['Penalties'][i])
   if(df['Nationality'][i]=='Brazil'): #it supposed to be blue if the nationality is brazil else is default(correct me if i'm wrong)
       ax.plot(x, y, 'o', color='blue')

ax.set_xlabel('Composure attribute')
ax.set_ylabel('Penalties attribute')
fig.show()

But it all turned to blue.
I have tried to change the loop like this:

if(df['Nationality'][i]=='Brazil'):
        ax.plot(x[i], y[i], 'o', color='blue')

But it says 'IndexError: list index out of range'. Any idea how to color it using plot? Thank you for your help.


问:
Is there any way to get the value of a key using the key in laravel eloquent (similar to getting value from key in array)
We can get the value of a key by $a['yourkey'] in PHP.

Is there any way to do this in laravel collection.

I just didn't want to use a loop so can i get the values under the key 340 without using a loop?

I want to code it this way in my view.

```<code>    @foreach($jobseeker[340] as $v){
        //Code here...
    }
</code>```

答:
The thing you are looking for is:</p>

```<code>$jobseeker->get(340);
</code>```

Body:
We can get the value of a key by $a['yourkey'] in PHP.

Is there any way to do this in laravel collection.

I just didn't want to use a loop so can i get the values under the key 340 without using a loop?

I want to code it this way in my view.

    @foreach($jobseeker[340] as $v){
        //Code here...
    }

Body:
The thing you are looking for is:

$jobseeker->get(340);


问:
findViewByID returns null
First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)

Most of them come with the advice to use android:id instead of just id in the XML file. I did.

From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.

In my location_layout.xml, I use:

```<code><FrameLayout .... >
    <some.package.MyCustomView ... />

    <LinearLayout ... >
        <TextView ...
            android:id="@+id/txtLat" />
        ...
    </LinearLayout>
</FrameLayout>
</code>```

In my Activity I do:

```<code>...
setContentView( R.layout.location_layout );
</code>```

and in my custom view class:

```<code>...
TextView tv = (TextView) findViewById( R.id.txtLat );
</code>```

which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:

```<code>...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );
</code>```

which also returned null.

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.

So what the heck am I doing wrong?

I'll appreciate any comments.

答:
Ways to debug and find the issue:

Comment out all findViewById in your activity.

Comment out everything except onCreate and setContentView

Run the project and see if any layout is set

In my case, I was using activity_main.xml in both my app module and also my library module. So when I performed the above steps, instead of the layout which I designed in the library, the layout inside app module was inflated.

So I changed the activity_main.xml file name to activity_main_lib.xml.

So make sure you do not have any duplicate layout names in your whole project.

ContentLicense: CC BY-SA 3.0

Title: findViewByID returns null

Body:
First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)

Most of them come with the advice to use android:id instead of just id in the XML file. I did.

From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.

In my location_layout.xml, I use:

<FrameLayout .... >
    <some.package.MyCustomView ... />

    <LinearLayout ... >
        <TextView ...
            android:id="@+id/txtLat" />
        ...
    </LinearLayout>
</FrameLayout>

In my Activity I do:

...
setContentView( R.layout.location_layout );

and in my custom view class:

...
TextView tv = (TextView) findViewById( R.id.txtLat );

which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:

...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );

which also returned null.

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.

So what the heck am I doing wrong?

I'll appreciate any comments.


问:
Check if Nullable Guid is empty in c#
Quoting from an answer from this question.

Guid is a value type, so a variable of type Guid can't be null to
  start with.

What then if I see this?

```<code>public Nullable<System.Guid> SomeProperty { get; set; }
</code>```

how should I check if this is null? Like this?

```<code>(SomeProperty == null)
</code>```

or like this?

```<code>(SomeProperty == Guid.Empty)
</code>```

答:
Beginning with C# 7.1, you can use default literal to produce the default value of a type when the compiler can infer the expression type.

```<code>Console.Writeline(default(Guid));
   // ouptut: 00000000-0000-0000-0000-000000000000

Console.WriteLine(default(int));  // output: 0

Console.WriteLine(default(object) is null);  // output: True
</code>```

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default

Title: Check if Nullable Guid is empty in c#

Body:
Quoting from an answer from this question.

Guid is a value type, so a variable of type Guid can't be null to
  start with.

What then if I see this?

public Nullable<System.Guid> SomeProperty { get; set; }

how should I check if this is null? Like this?

(SomeProperty == null)

or like this?

(SomeProperty == Guid.Empty)

Body:
Beginning with C# 7.1, you can use default literal to produce the default value of a type when the compiler can infer the expression type.

Console.Writeline(default(Guid));
   // ouptut: 00000000-0000-0000-0000-000000000000

Console.WriteLine(default(int));  // output: 0

Console.WriteLine(default(object) is null);  // output: True

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default


问:
AWS API Gateway {"message":"Missing Authentication Token"}
I am using API Gateway to build a REST API to communicate with a deployed  aws sagemaker model via aws lambda. When I test the Method (Method Test Results) my lambda function returns the required results. I've definitely deployed the API and I'm using the correct invoke URL with the resource name appended (Method Invoke URL). Finally I have checked all the auth settings for this method request (Method Auth Settings). When I input the invoke URL into the browser or try to call the REST API (from cloud9 IDE -- a web app I am developing) I get this error: {"message":"Missing Authentication Token"} (URL Response)

My API is very simple, only one POST request, it does not contain any other resources or methods. I tried also setting up the method under '/' but had the same issue.

There are a lot of people out there with this issue, and I've spent a while reading through similar posts - but the solutions boil down to the issues I've checked above. If anyone could help it would be greatly appreciated!

Iain

答:
You have configured the API Gateway resource with the POST method and when using the API Gateway console to test, the console handles setting the HTTP method to POST. However, when you directly hit the invoke URL from the browser, the GET method is used.

API Gateway by default returns the {"message":"Missing Authentication Token"} response for methods not defined or for paths not present, as given here

If API Gateway fails to process an incoming request, it returns to the client an error response without forwarding the request to the integration backend. By default, the error response contains a short descriptive error message. For example, if you attempt to call an operation on an undefined API resource, you receive an error response with the { "message": "Missing Authentication Token" } message.

Use the POST method to test your API. This can be done using the command-line (curl) or using Postman.


问:
How to get the selected date value while using Bootstrap Datepicker?
Using jquery and the Bootstrap Datepicker, how do I get the new date value I selected using the Bootstrap Datepicker?
FYI, I'm using Rails 3 and Coffescript.

I set up the datapicker using:

```<code><input id="startdate" class="span2 datepicker" type="text" value="" name="startdate" default="2013-05-21" data-date="2013-05-21" data-behavior="datepicker">
<%= submit_tag 'Get Data using date', :id => 'get_data' %>

$(".datepicker").datepicker
      endDate: new Date
      format: "yyyy-mm-dd"
      autoclose: true
      minViewMode: 1
      todayBtn: "linked"
</code>```

When a user clicks on the "get data using date" button next to it, I will use jQuery to get the new date value set by the datepicker, prevent the form from submitting and run an ajax request using that date value. All the ajax is running well, except for getting the correct new date value. I tried both of the following and it doesn't give me the new date, it only return the defaults I initially set.

```<code>sd1 = $('#startdate').attr('value')
console.log sd1

sd2 = $('#startdate').attr('data-date'))
console.log sd2
</code>```

I am feeling really stupid right now, but I can't find out how to get the new date value set by the bootstrap datepicker.

Body:
Using jquery and the Bootstrap Datepicker, how do I get the new date value I selected using the Bootstrap Datepicker?
FYI, I'm using Rails 3 and Coffescript.

I set up the datapicker using:

<input id="startdate" class="span2 datepicker" type="text" value="" name="startdate" default="2013-05-21" data-date="2013-05-21" data-behavior="datepicker">
<%= submit_tag 'Get Data using date', :id => 'get_data' %>

$(".datepicker").datepicker
      endDate: new Date
      format: "yyyy-mm-dd"
      autoclose: true
      minViewMode: 1
      todayBtn: "linked"

When a user clicks on the "get data using date" button next to it, I will use jQuery to get the new date value set by the datepicker, prevent the form from submitting and run an ajax request using that date value. All the ajax is running well, except for getting the correct new date value. I tried both of the following and it doesn't give me the new date, it only return the defaults I initially set.

sd1 = $('#startdate').attr('value')
console.log sd1

sd2 = $('#startdate').attr('data-date'))
console.log sd2

I am feeling really stupid right now, but I can't find out how to get the new date value set by the bootstrap datepicker.

Body: $("#startdate").data().datepicker.getFormattedDate('yyyy-mm-dd');


问:
query database for results within a certain time using the user's timezone
How can I query a set of results that belong to a specific time period according to the user's time.

For example: "select * from table where datestamp like ".date("Y-m-d",strtotime("-1 day"))."%"

would give me results within the past 24 hours based on the server time. How can I do this query to be based on the user's time rather than the server's time?

答:
You can do this in 3 steps:

1. Detect the client timezone

This is difficult:  Different browsers use different acronyms and conventions for representing names of timezones. You should use an existing implementation, like jsTimezoneDetect.

2. Pass the timezone information to PHP

If you need to use timezone dependent PHP functions (like date() in your exemple), you can set the timezone with:

```<code>date_default_timezone_set($TZ);
</code>```

Where $TZ is the variable where you stored the timezone from the client request.

3. Pass the timezone information to MySQL

If you need to use timezone dependent MySQL functions, you can set the timezone for the current MySQL session with:

```<code>mysql_query("SET time_zone = $TZ");
</code>```

Body:
You can do this in 3 steps:

1. Detect the client timezone

This is difficult:  Different browsers use different acronyms and conventions for representing names of timezones. You should use an existing implementation, like jsTimezoneDetect.

2. Pass the timezone information to PHP

If you need to use timezone dependent PHP functions (like date() in your exemple), you can set the timezone with:

date_default_timezone_set($TZ);

Where $TZ is the variable where you stored the timezone from the client request.

3. Pass the timezone information to MySQL

If you need to use timezone dependent MySQL functions, you can set the timezone for the current MySQL session with:

mysql_query("SET time_zone = $TZ");


问:
Unable to complete this question due to syntax error in the Python code for tensorflow?
The 'return' is outside the function. I have to return the values in tuples. Basically, there are two errors here. Firstly, the 'return' is outside of the function. Secondly, the result did not return as a tuple.</p>

```<code>def train_mnist():

class myCallback(tf.keras.callbacks.Callback):

    def on_epoch_end(self, epoch, logs={}):
        if logs.get('acc') > 0.99:
            print ('\nReached 99% accuracy so cancelling training!')
        self.model.stop_training = True

mnist = tf.keras.datasets.mnist

((x_train, y_train), (x_test, y_test)) = mnist.load_data(path=path)
(x_train, x_test) = (x_train / 255.0, x_test / 255.0)

callbacks = myCallback()

model = \
    tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,
                               28)), tf.keras.layers.Dense(512,
                               activation=tf.nn.relu),
                               tf.keras.layers.Dense(10,
                               activation=tf.nn.softmax)])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10,
                    callbacks=[callbacks])

return (history.epoch, history.history['acc'][-1])
</code>```

答:
The issue was with the indentation and getting the accuracy from the model log.

I have modified your code as below and got the intended output.

```<code>def train_mnist():

  class myCallback(tf.keras.callbacks.Callback):

      def on_epoch_end(self, epoch, logs):
          if logs["accuracy"] > 0.99:
              print ('\nReached 99% accuracy so cancelling training!')
              self.model.stop_training = True

  mnist = tf.keras.datasets.mnist

  ((x_train, y_train), (x_test, y_test)) = mnist.load_data()
  (x_train, x_test) = (x_train / 255.0, x_test / 255.0)

  callbacks = myCallback()

  model = \
      tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,
                                28)), tf.keras.layers.Dense(512,
                                activation=tf.nn.relu),
                                tf.keras.layers.Dense(10,
                                activation=tf.nn.softmax)])
  model.compile(optimizer='adam',
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])

  history = model.fit(x_train, y_train, epochs=10,
                      callbacks=[callbacks])

  return (history.epoch, history.history['accuracy'][-1])
</code>```

Output:

```<code>Epoch 1/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.2026 - accuracy: 0.9392
Epoch 2/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0799 - accuracy: 0.9755
Epoch 3/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0521 - accuracy: 0.9839
Epoch 4/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0353 - accuracy: 0.9894
Epoch 5/10
1867/1875 [============================>.] - ETA: 0s - loss: 0.0278 - accuracy: 0.9910
Reached 99% accuracy so cancelling training!
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0278 - accuracy: 0.9910
([0, 1, 2, 3, 4], 0.9909833073616028)
</code>```

Body:
The 'return' is outside the function. I have to return the values in tuples. Basically, there are two errors here. Firstly, the 'return' is outside of the function. Secondly, the result did not return as a tuple.

def train_mnist():

class myCallback(tf.keras.callbacks.Callback):

    def on_epoch_end(self, epoch, logs={}):
        if logs.get('acc') > 0.99:
            print ('\nReached 99% accuracy so cancelling training!')
        self.model.stop_training = True

mnist = tf.keras.datasets.mnist

((x_train, y_train), (x_test, y_test)) = mnist.load_data(path=path)
(x_train, x_test) = (x_train / 255.0, x_test / 255.0)

callbacks = myCallback()

model = \
    tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,
                               28)), tf.keras.layers.Dense(512,
                               activation=tf.nn.relu),
                               tf.keras.layers.Dense(10,
                               activation=tf.nn.softmax)])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=10,
                    callbacks=[callbacks])

return (history.epoch, history.history['acc'][-1])

Body:
The issue was with the indentation and getting the accuracy from the model log.

I have modified your code as below and got the intended output.

def train_mnist():

  class myCallback(tf.keras.callbacks.Callback):

      def on_epoch_end(self, epoch, logs):
          if logs["accuracy"] > 0.99:
              print ('\nReached 99% accuracy so cancelling training!')
              self.model.stop_training = True

  mnist = tf.keras.datasets.mnist

  ((x_train, y_train), (x_test, y_test)) = mnist.load_data()
  (x_train, x_test) = (x_train / 255.0, x_test / 255.0)

  callbacks = myCallback()

  model = \
      tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,
                                28)), tf.keras.layers.Dense(512,
                                activation=tf.nn.relu),
                                tf.keras.layers.Dense(10,
                                activation=tf.nn.softmax)])
  model.compile(optimizer='adam',
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])

  history = model.fit(x_train, y_train, epochs=10,
                      callbacks=[callbacks])

  return (history.epoch, history.history['accuracy'][-1])

Output:

Epoch 1/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.2026 - accuracy: 0.9392
Epoch 2/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0799 - accuracy: 0.9755
Epoch 3/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0521 - accuracy: 0.9839
Epoch 4/10
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0353 - accuracy: 0.9894
Epoch 5/10
1867/1875 [============================>.] - ETA: 0s - loss: 0.0278 - accuracy: 0.9910
Reached 99% accuracy so cancelling training!
1875/1875 [==============================] - 6s 3ms/step - loss: 0.0278 - accuracy: 0.9910
([0, 1, 2, 3, 4], 0.9909833073616028)


问:
Deselecting checkboxes
I have 2 check boxes, I save them using sharedPreferences, however, I need one check box to be deselected if the other one is selected.

My code:

```<code>public static CheckBox checkHolyPaiges, checkDefault;
public static boolean checkHolyPaiges2, checkDefault2;

checkDefault = (CheckBox) findViewById(R.id.checkDefault);
checkHolyPaiges = (CheckBox) findViewById(R.id.checkHolyPaiges);

final SharedPreferences prefs = getSharedPreferences("game", MODE_PRIVATE);

if (checkHolyPaiges.isChecked())
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("checkHolyPaiges", true);
    editor.apply();

    checkDefault.setChecked(false);
}

if (checkDefault.isChecked())
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("checkDefault", true);
    editor.apply();

    checkHolyPaiges.setChecked(false);
}

checkHolyPaiges2 = prefs.getBoolean("checkHolyPaiges", false);
checkDefault2 = prefs.getBoolean("checkDefault", true);
</code>```

答:
you should be use Radio Buttons on this issue.

I think,Radio Buttons is better than checkboxes to handle this

https://developer.android.com/guide/topics/ui/controls/radiobutton

Title: Deselecting checkboxes

Body:
I have 2 check boxes, I save them using sharedPreferences, however, I need one check box to be deselected if the other one is selected.

My code:

public static CheckBox checkHolyPaiges, checkDefault;
public static boolean checkHolyPaiges2, checkDefault2;

checkDefault = (CheckBox) findViewById(R.id.checkDefault);
checkHolyPaiges = (CheckBox) findViewById(R.id.checkHolyPaiges);

final SharedPreferences prefs = getSharedPreferences("game", MODE_PRIVATE);

if (checkHolyPaiges.isChecked())
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("checkHolyPaiges", true);
    editor.apply();

    checkDefault.setChecked(false);
}

if (checkDefault.isChecked())
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("checkDefault", true);
    editor.apply();

    checkHolyPaiges.setChecked(false);
}

checkHolyPaiges2 = prefs.getBoolean("checkHolyPaiges", false);
checkDefault2 = prefs.getBoolean("checkDefault", true);


问:
Callback on memory access?
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?

For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.

The platform I'm working on is x86 Linux and writing in C/C++.

答: I don't think there is such an API to do so, until you create a wrapper object around the allocated memory and then access to the memory is done through this wrapper object. Then this wrapper object will be able to see all access to the underlying memory.</p>

Title: Callback on memory access?


问:
R script with list.files function in OneDrive/Sharepoint
I have a script that's part of an R Project file that's saved in a folder in OneDrive. One piece of it lists all the .xlsx files in the OneDrive folder like this:

```<code>file_list <- list.files(path = "C:/Users/MyUsername/My Organization's OneDrive/Folder Creator's Name/Folder Name", pattern = "\\.xlsx$")
</code>```

Others in my organization who have access to the OneDrive folder aren't able to run this line without changing MyUsername to TheirUsername in the filepath. I'd like to make it so that anyone who has access to the OneDrive folder can just open the code and run it without changing things. The working directory should be already specified, because this script lives in a R Project file that's saved in the appropriate folder - how do I set the file path to be the current working directory?

答:
Use relative file paths:

file_list <- list.files(path = "<path/relative/to/Rscript/>", pattern = "\\.xlsx$")
```

<p>Another useful option is the here package. For example:</p>

<pre class="lang-r prettyprint-override"><code>library(here)
file_list <- list.files(path = here("<folder_with_Excel_files>"), pattern = "\\.xlsx$")
</code>```

This has the added benefit that it should be platform-agnostic.

Body:
I have a script that's part of an R Project file that's saved in a folder in OneDrive. One piece of it lists all the .xlsx files in the OneDrive folder like this:

file_list <- list.files(path = "C:/Users/MyUsername/My Organization's OneDrive/Folder Creator's Name/Folder Name", pattern = "\\.xlsx$")

Others in my organization who have access to the OneDrive folder aren't able to run this line without changing MyUsername to TheirUsername in the filepath. I'd like to make it so that anyone who has access to the OneDrive folder can just open the code and run it without changing things. The working directory should be already specified, because this script lives in a R Project file that's saved in the appropriate folder - how do I set the file path to be the current working directory?

Body:
Use relative file paths:

file_list <- list.files(path = "<path/relative/to/Rscript/>", pattern = "\\.xlsx$")

Another useful option is the here package. For example:

library(here)
file_list <- list.files(path = here("<folder_with_Excel_files>"), pattern = "\\.xlsx$")

This has the added benefit that it should be platform-agnostic.


问:
In Mongo-DB How to set Default Value for a field through node restify?
I have created a collection(table) named Group and I have fields such as Group name,Group Desc and Group Type but I need to set the Group type by default to 1 if it receives a null value. And I have the following code to insert.

```<code>function postNewGroups(req , res , next){

var Group = {};
Group._id = sequence;
Group.GROUP_NAME = req.params.GROUP_NAME;
Group.GROUP_DESC = req.params.GROUP_DESC;
Group.GROUP_TYPE = req.params.GROUP_TYPE;

Groups.save(Group , function(err , success){
        console.log('Response success '+success);
        console.log('Response error '+err);
        if(success){
            res.send(201 , Group);
            return next();
        }else{
            return next(err);
        }
    });
</code>```

But I have searched lot about how to set a default value but I couldn't able to find a solution.

答:
If you like to set default value while inserting data in MongoDb, Use mongoose.
It has functionality multiple functionality given below and many more.

for Ex.

```<code>{
organization:{
  type: string,
  default: "XYZ"
 }
}
</code>```

Body:
I have created a collection(table) named Group and I have fields such as Group name,Group Desc and Group Type but I need to set the Group type by default to 1 if it receives a null value. And I have the following code to insert.

function postNewGroups(req , res , next){

var Group = {};
Group._id = sequence;
Group.GROUP_NAME = req.params.GROUP_NAME;
Group.GROUP_DESC = req.params.GROUP_DESC;
Group.GROUP_TYPE = req.params.GROUP_TYPE;

Groups.save(Group , function(err , success){
        console.log('Response success '+success);
        console.log('Response error '+err);
        if(success){
            res.send(201 , Group);
            return next();
        }else{
            return next(err);
        }
    });

But I have searched lot about how to set a default value but I couldn't able to find a solution.

Body:
If you like to set default value while inserting data in MongoDb, Use mongoose.
It has functionality multiple functionality given below and many more.

for Ex.

{
organization:{
  type: string,
  default: "XYZ"
 }
}


问:
Marshal char* from double pointer Struct from C++ to C#
Goal: Retrieve the array of structs from c++, from the c++  side it's finalized to return pointer to struct  pointer (Double pointer)(Not in my control).

Sample c++ code :

```<code>struct Output
{
    char* Name;
};

extern "C"
{
__declspec(dllexport) Output** getoutput()
    {

        Output* items = (Output*)malloc(sizeof(Output) * 4);

        items->Name = "Hello World";

        return &items;
    }
}
</code>```

c# Side code :

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct Output
    {
        [MarshalAsAttribute(UnmanagedType.LPStr)]
        public string Name;
    };

 [DllImport(@"CPPInvokeExposed.dll",
       CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr getoutput();
static void Main(string[] args)
    {
       var output = Program.getoutput();
        Output[] outputs = new Output[1];
        MarshalUnmananagedArray2Struct<Output>(output, 1, out outputs);
        **outputs[0]// this has junk chars**

    }

 public static void MarshalUnmananagedArray2Struct<T>(IntPtr unmanagedArray, int length, out T[] mangagedArray)
    {
        var size = Marshal.SizeOf(typeof(T));
        mangagedArray = new T[length];

        for (int i = 0; i < length; i++)
        {
            IntPtr ins = new IntPtr(unmanagedArray.ToInt64() + i * size);

            mangagedArray[i] = Marshal.PtrToStructure<T>(ins);
        }
    }
</code>```

Is not clear whether the problem is in c++ or c# code. What should be the correct way get the Char* from c++ which exists in struct.

One strange thing is, for the same code if c++ code return single pointer(Output*) instead double pointer(Output**), there is no junk character, getting the correct assigned value. looks like something wrong while returning double pointer from c++.

答:
You C++ code causes undefined behaviour:

return &items;

This returns the address of an automatic variable.
That variable will not exist anymore when the function returns. Accessing that memory location is illegal and causes undefined behaviour.

A clean solution would be to return the pointer itself, not the address. But in your question you state that the return type is not under your control.

In that case you must create the second level of indirection by yourself:

```<code>__declspec(dllexport) Output** getoutput()
{
    Output* items = (Output*)malloc(sizeof(Output) * 4);
    items->Name = "Hello World";

    Output **retval = (Output**)malloc(sizeof(Output*))
    *retval = items;
    return retval;
}
</code>```

Of course you also need to take care about freeing both levels of memory allocation afterwards.

BTW:
You allocate memory for 4 structs but only assign a value to member of the first element.

Body:
Goal: Retrieve the array of structs from c++, from the c++  side it's finalized to return pointer to struct  pointer (Double pointer)(Not in my control).

Sample c++ code :

struct Output
{
    char* Name;
};

extern "C"
{
__declspec(dllexport) Output** getoutput()
    {

        Output* items = (Output*)malloc(sizeof(Output) * 4);

        items->Name = "Hello World";

        return &items;
    }
}

c# Side code :

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct Output
    {
        [MarshalAsAttribute(UnmanagedType.LPStr)]
        public string Name;
    };

 [DllImport(@"CPPInvokeExposed.dll",
       CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr getoutput();
static void Main(string[] args)
    {
       var output = Program.getoutput();
        Output[] outputs = new Output[1];
        MarshalUnmananagedArray2Struct<Output>(output, 1, out outputs);
        **outputs[0]// this has junk chars**

    }

 public static void MarshalUnmananagedArray2Struct<T>(IntPtr unmanagedArray, int length, out T[] mangagedArray)
    {
        var size = Marshal.SizeOf(typeof(T));
        mangagedArray = new T[length];

        for (int i = 0; i < length; i++)
        {
            IntPtr ins = new IntPtr(unmanagedArray.ToInt64() + i * size);

            mangagedArray[i] = Marshal.PtrToStructure<T>(ins);
        }
    }

Is not clear whether the problem is in c++ or c# code. What should be the correct way get the Char* from c++ which exists in struct.

One strange thing is, for the same code if c++ code return single pointer(Output*) instead double pointer(Output**), there is no junk character, getting the correct assigned value. looks like something wrong while returning double pointer from c++.

Body:
You C++ code causes undefined behaviour:

return &items;

This returns the address of an automatic variable.
That variable will not exist anymore when the function returns. Accessing that memory location is illegal and causes undefined behaviour.

A clean solution would be to return the pointer itself, not the address. But in your question you state that the return type is not under your control.

In that case you must create the second level of indirection by yourself:

__declspec(dllexport) Output** getoutput()
{
    Output* items = (Output*)malloc(sizeof(Output) * 4);
    items->Name = "Hello World";

    Output **retval = (Output**)malloc(sizeof(Output*))
    *retval = items;
    return retval;
}

Of course you also need to take care about freeing both levels of memory allocation afterwards.

BTW:
You allocate memory for 4 structs but only assign a value to member of the first element.


问:
android cardview showing border around card
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

```<code>         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>
</code>```

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.

答:
For me, it looks like that extra border is just the background of your RelativeLayout. I need to see the full code of the layout to confirm but if I'm right, this means somewhere maybe programmatically  your changing the transparent background of the RelativeLayout that you defined here

please share the full layout code. thanks

         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView...```

Body:
Android cardview is showing unnecessary border around the card. I have tried different things but I am not able to remove it.
It happens when I give the card a custom background color.
When I remove the cardBackgroundColor, and when default is used. Then unnecessary border is not visible.

I have to use shadow and tranparent color code.

Here is my layout CardView

         <RelativeLayout
            android:id="@+id/rlUserNamePassword"
            android:layout_width="match_parent"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin"
                android:background="@android:color/transparent"
                app:cardBackgroundColor="@color/form_card_bg_color"
                app:cardElevation="@dimen/margin"
                app:contentPadding="@dimen/margin_large"
                app:cardPreventCornerOverlap="false"
                app:cardUseCompatPadding="true" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/user" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilName"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etEmail"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/username"
                                android:singleLine="true"
                                android:maxLines="1"/>

                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/margin_large"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/password" />

                        <android.support.design.widget.TextInputLayout
                            android:id="@+id/tilPassword"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">

                            <com.yaashvi.placeandpeople.customviews.CustomEditText
                                android:id="@+id/etPassword"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:hint="@string/password"
                                android:singleLine="true"
                                android:maxLines="1"
                                android:inputType="textPassword"/>
                        </android.support.design.widget.TextInputLayout>

                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView >

            <LinearLayout
                android:id="@+id/llGo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:orientation="vertical"
                android:elevation="@dimen/margin_large"
                >

                <include layout="@layout/go_button" />

            </LinearLayout>

        </RelativeLayout>

And the view created is this

See the extra border on left, right and top of cardview and inside the card shadow.


问:
In GIMP (DBP), how can I batch-resize photos to a certain width and keep aspect ratio?
I have been using GIMP to resize photos one by one, to say 800px-width while keeping aspect ratio. I downloaded the David Batch Processor plugin and everything looks fine, except it isn't able to resize to a predetermined width or height whilst keeping the aspect ratio.

Relative: I can resize by % and keep aspect ratio, but the photos are of different sizes and orientation, so no one % works.

Absolute: There isn't an option to keep aspect ratio, and no one height works for all photos.

Can someone please advise if there is a way to batch-resize photos of different original sizes using GIMP's dbp or there is some other plugin that can work?

答: I realised that for whatever reason, that Dbp just doesn't have the function to keep the aspect ratio in absolute resizing, so either I write a script from scratch which is an overkill for my purpose or find another plugin for batch processing. I am now using one called Batch Image Manipulation. https://alessandrofrancesconi.it/projects/bimp/</p>


问:
Replace characters in all tables in Database Postgres
I'm using PostgreSQL with pgadmin.
I need to replace multiple characters in all fields of type string, and in all tables in my database.</p>

答:
This will list all columns that are "character" type in your database:

```<code>SELECT t.tablename, a.attname AS column_name
FROM pg_attribute a
JOIN pg_class c ON a.attrelid = c.oid
JOIN pg_tables t ON t.tablename = c.relname
JOIN pg_type on pg_type.oid = a.atttypid
WHERE t.schemaname not in ('information_schema', 'pg_catalog')
and pg_type.typname in ('varchar', 'text', 'char')
order by 1,2;
</code>```

Then you must go through and do the updates.

Body:
This will list all columns that are "character" type in your database:

SELECT t.tablename, a.attname AS column_name
FROM pg_attribute a
JOIN pg_class c ON a.attrelid = c.oid
JOIN pg_tables t ON t.tablename = c.relname
JOIN pg_type on pg_type.oid = a.atttypid
WHERE t.schemaname not in ('information_schema', 'pg_catalog')
and pg_type.typname in ('varchar', 'text', 'char')
order by 1,2;

Then you must go through and do the updates.


问:
Gravity forms conditions
I'm working on a form with specific values for one field, we are making a campaign with 20,000 codes and the user must enter the code he gets in a field in gravity form, so this field will have 20,000 values and restricted with these codes, so when the users enter any value they will get a message that this value is wrong and enter the right value, i need to add if statement for these 20,000 values to restrict the field with it using one statement not like the confirmation message in the plugin i have to add the value one by one. please help me with it.

please help me.

答:
I will assume that you are a non-coder but let me know if that is a bad assumption. Here's a customization-free technique for achieving this. We have a snippet that will allow you to required a reference number (or code) in order to submit a Gravity Form.

https://gravitywiz.com/require-existing-value-submission-gravity-forms/

The only problem for you is that it can only look for reference numbers in existing Gravity Forms entries. To get your codes converted to entries we can import them use GravityView Import Entries.

Once the codes are imported as entries, just configure the snippet to check for those codes in the newly imported form/entries. The user will not be able to submit the form unless they enter a valid code.

Title: Gravity forms conditions


问:
Modify innerHTML using Selenium
I have this element:

```<code>WebElement element = ...
string val = element.getAttribute("innerHTML");
</code>```

All I want to do is to change this innerHTML on my web page.

Is it possible?

答:
in python use this :

```<code>element = driver.find_element_by_id("some_id")
driver.execute_script("arguments[0].innerText = 'what_you_want_to_show'", element)
</code>```

Title: Modify innerHTML using Selenium

Body:
I have this element:

WebElement element = ...
string val = element.getAttribute("innerHTML");

All I want to do is to change this innerHTML on my web page.

Is it possible?

Body:
in python use this :

element = driver.find_element_by_id("some_id")
driver.execute_script("arguments[0].innerText = 'what_you_want_to_show'", element)


问:
system exception using try-catch
So I have a problem with making an exception. I am making a hangman game where the user needs to input a letter (box with guess) but I only want that they can give in letters from A-Z and no numbers.

In the code that I wrote, I give the box with guess the name choosed_lettre and convert it to "letter".

Question:

- How can I make the exception that it only takes letters and no numbers?

Code:

```<code> private void Choosed_lettre_KeyDown_1(object sender, KeyEventArgs e)
        {
            char letter = ' ';
            bool validation = false;
            if (e.Key == Key.Enter && choosed_lettre.Text != "")
            {
                do
                {
                    try //trycatch
                    {
                        string input = Convert.ToString(choosed_lettre.Text);
                        input = input.ToLower();
                        letter = Convert.ToChar(input[0]);
                        validation = true;
                    }
                    catch (SystemException)
                    {
                        choosed_lettre.Text = "";
                        return;
                    }
                } while (validation == false && !((letter >= 'a' && letter <= 'z') && (letter >= 0 && letter <= 9)));
            }
</code>```

wpfscreen:

答:
Sidenote: use string.IsNullOrEmpty(choosed_lettre.Text) instead of comparing to empty string.

string input = Convert.ToString(choosed_lettre.Text); is unnecessary, as Text porerty is already a string. Use
string input = choosed_lettre.Text;

Also, avoid exceptions that can be handled by programmer. So, check if input is of length one and is a letter. Even better, you can use great method TryParse! Doing this will greatly simplify the code:

```<code>if (e.Key == Key.Enter)
{
    if(! char.TryParse(choosed_lettre.Text, out char letter))
        choosed_lettre.Text = "";
    if(! char.IsLetter(letter))
        choosed_lettre.Text = "";
}
</code>```

Title: system exception using try-catch

Body:
So I have a problem with making an exception. I am making a hangman game where the user needs to input a letter (box with guess) but I only want that they can give in letters from A-Z and no numbers.

In the code that I wrote, I give the box with guess the name choosed_lettre and convert it to "letter".

Question:

- How can I make the exception that it only takes letters and no numbers?

Code:

 private void Choosed_lettre_KeyDown_1(object sender, KeyEventArgs e)
        {
            char letter = ' ';
            bool validation = false;
            if (e.Key == Key.Enter && choosed_lettre.Text != "")
            {
                do
                {
                    try //trycatch
                    {
                        string input = Convert.ToString(choosed_lettre.Text);
                        input = input.ToLower();
                        letter = Convert.ToChar(input[0]);
                        validation = true;
                    }
                    catch (SystemException)
                    {
                        choosed_lettre.Text = "";
                        return;
                    }
                } while (validation == false && !((letter >= 'a' && letter <= 'z') && (letter >= 0 && letter <= 9)));
            }

wpfscreen:

Body:
Sidenote: use string.IsNullOrEmpty(choosed_lettre.Text) instead of comparing to empty string.

string input = Convert.ToString(choosed_lettre.Text); is unnecessary, as Text porerty is already a string. Use
string input = choosed_lettre.Text;

Also, avoid exceptions that can be handled by programmer. So, check if input is of length one and is a letter. Even better, you can use great method TryParse! Doing this will greatly simplify the code:

if (e.Key == Key.Enter)
{
    if(! char.TryParse(choosed_lettre.Text, out char letter))
        choosed_lettre.Text = "";
    if(! char.IsLetter(letter))
        choosed_lettre.Text = "";
}


问:
Keeping only one column after join
For the following code

```<code>d = {'col1': [33,34], 'col2': [1,2]}
d1 = {'col3': [33,34], 'col4': [3,4]}
df = pd.DataFrame(data=d)
df1 = pd.DataFrame(data=d1)
myDF=pd.merge(df, df1, how='inner', left_on=['col1'], right_on=['col3'])
</code>```

in myDF, it kept two columns (col1 and col3), is there a way to keep either one column (col1 or col3) with merge function? (of course I can drop a column by applying drop later on after merge, just want to see is it possible to simplify the step.)

答:
Use rename column, so output is only one column and also is not necessary use left_on and right_on parameters, because on is enough:

```<code>myDF=pd.merge(df.rename(columns={'col1':'col3'}), df1, on='col3')
print (myDF)
   col3  col2  col4
0    33     1     3
1    34     2     4
</code>```

```<code>myDF=pd.merge(df, df1.rename(columns={'col3':'col1'}), on='col1')
print (myDF)
   col1  col2  col4
0    33     1     3
1    34     2     4
</code>```

Title: Keeping only one column after join

Body:
For the following code

d = {'col1': [33,34], 'col2': [1,2]}
d1 = {'col3': [33,34], 'col4': [3,4]}
df = pd.DataFrame(data=d)
df1 = pd.DataFrame(data=d1)
myDF=pd.merge(df, df1, how='inner', left_on=['col1'], right_on=['col3'])

in myDF, it kept two columns (col1 and col3), is there a way to keep either one column (col1 or col3) with merge function? (of course I can drop a column by applying drop later on after merge, just want to see is it possible to simplify the step.)

Body:
Use rename column, so output is only one column and also is not necessary use left_on and right_on parameters, because on is enough:

myDF=pd.merge(df.rename(columns={'col1':'col3'}), df1, on='col3')
print (myDF)
   col3  col2  col4
0    33     1     3
1    34     2     4

myDF=pd.merge(df, df1.rename(columns={'col3':'col1'}), on='col1')
print (myDF)
   col1  col2  col4
0    33     1     3
1    34     2     4


问:
Different encryption Android vs pure Java - RSA/ECB/OAEPWithMD5AndMGF1Padding
I encrypt a string in Android by the public key. However, I get an exception "Decryption error" when I try to decrypt the encrypted string by the private key in pure Java code. Can anyone help to find the problem?

Android code to encrypt

```<code>import android.util.Base64;
public static String encryptMessage(final String plainText, final PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encodeToString(cipher.doFinal(plainText.getBytes()), Base64.NO_WRAP);
}
</code>```

Pure Java code to decrypt

```<code>import java.util.Base64;
public static String decryptMessage(final String encryptedText, final PrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] byteArray = decoder.decode(encryptedText);
    byte[] decryptedArray = cipher.doFinal(byteArray);  // throw exception here
    String plainText = new String(decryptedArray);
    return plainText;
}
</code>```

You may notice I have to use different Base64 APIs in Android and pure Java. I tried "RSA/ECB/PKCS1Padding", and it can decrypt correctly without the exception. Tried "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" too but got the same exception.

答:
OAEP uses two digests, one for the OAEP label and a second as the basis for MGF1, see RFC 8017, 7.1. RSAES-OAEP, B.1. Hash Functions and B.2. Mask Generation Functions.

The issue is caused because the providers used on both sides of the OP code (Android / API Level 28 and Java 8) apply different MGF1 digests for OAEPWithMD5AndMGF1Padding.

On both sides the relevant parameters (provider, OAEP digest, MGF, MGF1 digest) can be determined after the initialization of the cipher e.g. with:

```<code>OAEPParameterSpec parameterSpec = cipher.getParameters().getParameterSpec(OAEPParameterSpec.class);
System.out.println("Provider: " + cipher.getProvider().getName());
System.out.println("OAEP digest: " + parameterSpec.getDigestAlgorithm());
System.out.println("OAEP MGF : " + parameterSpec.getMGFAlgorithm());
System.out.println("OAEP MGF1 digest: " + ((MGF1ParameterSpec)parameterSpec.getMGFParameters()).getDigestAlgorithm());
</code>```

With this, MD5 is determined as MGF1 digest on the Android side and SHA-1 on the Java side. On both sides MD5 is used as OAEP digest. The issue can be fixed if the digests are explicitly set with OAEPParameterSpec so that the same digests are used on both sides.

For example, the following code on the Java side ensures that MD5 is used as OAEP and MGF1 digest, analogous to the Android side.

```<code>OAEPParameterSpec oaepParameterSpecDec = new OAEPParameterSpec("MD5", "MGF1", new MGF1ParameterSpec("MD5"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpecDec);
</code>```

The same applies to OAEPWithSHA-256AndMGF1Padding.

Note also that RFC 8017 in B.1. Hash Functions recommends SHA-1 and SHA-2 for RSAES-OAEP, but not MD5.

Body:
I encrypt a string in Android by the public key. However, I get an exception "Decryption error" when I try to decrypt the encrypted string by the private key in pure Java code. Can anyone help to find the problem?

Android code to encrypt

import android.util.Base64;
public static String encryptMessage(final String plainText, final PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encodeToString(cipher.doFinal(plainText.getBytes()), Base64.NO_WRAP);
}

Pure Java code to decrypt

import java.util.Base64;
public static String decryptMessage(final String encryptedText, final PrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] byteArray = decoder.decode(encryptedText);
    byte[] decryptedArray = cipher.doFinal(byteArray);  // throw exception here
    String plainText = new String(decryptedArray);
    return plainText;
}

You may notice I have to use different Base64 APIs in Android and pure Java. I tried "RSA/ECB/PKCS1Padding", and it can decrypt correctly without the exception. Tried "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" too but got the same exception.

Body:
OAEP uses two digests, one for the OAEP label and a second as the basis for MGF1, see RFC 8017, 7.1. RSAES-OAEP, B.1. Hash Functions and B.2. Mask Generation Functions.

The issue is caused because the providers used on both sides of the OP code (Android / API Level 28 and Java 8) apply different MGF1 digests for OAEPWithMD5AndMGF1Padding.

On both sides the relevant parameters (provider, OAEP digest, MGF, MGF1 digest) can be determined after the initialization of the cipher e.g. with:

OAEPParameterSpec parameterSpec = cipher.getParameters().getParameterSpec(OAEPParameterSpec.class);
System.out.println("Provider: " + cipher.getProvider().getName());
System.out.println("OAEP digest: " + parameterSpec.getDigestAlgorithm());
System.out.println("OAEP MGF : " + parameterSpec.getMGFAlgorithm());
System.out.println("OAEP MGF1 digest: " + ((MGF1ParameterSpec)parameterSpec.getMGFParameters()).getDigestAlgorithm());

With this, MD5 is determined as MGF1 digest on the Android side and SHA-1 on the Java side. On both sides MD5 is used as OAEP digest. The issue can be fixed if the digests are explicitly set with OAEPParameterSpec so that the same digests are used on both sides.

For example, the following code on the Java side ensures that MD5 is used as OAEP and MGF1 digest, analogous to the Android side.

OAEPParameterSpec oaepParameterSpecDec = new OAEPParameterSpec("MD5", "MGF1", new MGF1ParameterSpec("MD5"), PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpecDec);

The same applies to OAEPWithSHA-256AndMGF1Padding.

Note also that RFC 8017 in B.1. Hash Functions recommends SHA-1 and SHA-2 for RSAES-OAEP, but not MD5.


答:
Well....you could set up a buffer. You could even just set up an array with the allocation. Then set up an if statement that if anything tampers with that array section, for instance if the array was defaulted to have a value of 0 at an index, and now its not, call whatever you want to do.

If you want a lot to happen, and then the program break and respond to that allocation being tampered with, set a boolean and when the value is changed, the boolean goes to true, and have a function posted to check that boolean.

Title: Callback on memory access?

Body:
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?

For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.

The platform I'm working on is x86 Linux and writing in C/C++.


问:
R: source multiple files with chdir = TRUE using safely
I want to run multiple R scripts that are located in different sub-folders in the "path_source".

```<code>files <- list.files(path = path_source, full.names = T, recursive = T)
</code>```

Scripts that don't run correctly should not stop the program, therefore I use safely()

```<code>safesource <- safely(source)
map_chr(files, safesource)
</code>```

However, in the source() function, I need to pass the additional argument "chdir = T" to change directories accordingly. How would I go about this?

答:
You can use this safesource

```<code>safesource <- function(file) purrr::safely(source(file, chdir = TRUE))
</code>```

Body:
I want to run multiple R scripts that are located in different sub-folders in the "path_source".

files <- list.files(path = path_source, full.names = T, recursive = T)

Scripts that don't run correctly should not stop the program, therefore I use safely()

safesource <- safely(source)
map_chr(files, safesource)

However, in the source() function, I need to pass the additional argument "chdir = T" to change directories accordingly. How would I go about this?

Body:
You can use this safesource

safesource <- function(file) purrr::safely(source(file, chdir = TRUE))


问:
Selecting data from multiple tables based on PK - ASP.NET
I am looking to select data from multiple tables and insert into respective text boxes. I can have one table that hold all the data, but as I want to apply normalization to the data sets, I will have to split the data.

I already know that I can use :

```<code>SELECT *
FROM users
WHERE Username = UserNametxt.Text.Trim()
</code>```

and then addWithValue etc.

How would I do this using a PK from one table linked to other tables as a FK?

Table users:

```<code>    id (pk)
    email
    password
    last_login
</code>```

Table address:

```<code>    id (fk to users.id)
    houseNumber
    StreetName
    City
</code>```

Table postcode:

```<code>    id (fk to users.id)
    PostCode
</code>```

The above is a rough sample of what the data tables will be.

答:
First of all, you should change the structure of your tables. In order to properly normalize DB, tables address and postcode should have their own id (PK), which does not depend on data from other tables.
If you leave it that way, you won't get rid of data duplication (which is one of the main reasons to normalize DB)

So it would look like that:

Table addresses:

```<code>id (PK)
userId (FK)
houseNumber
streetName
city
</code>```

Table postcodes:

```<code>id (PK)
userId (FK)
postCode
</code>```

And then you need to get information. You need to use JOIN to somehow connect tables and get information you need

```<code>SELECT * FROM users
LEFT JOIN addresses ON adresses.UserId=users.Id
LEFT JOIN postcodes ON postcodes.UserId=users.Id
WHERE ...
</code>```

Body:
I am looking to select data from multiple tables and insert into respective text boxes. I can have one table that hold all the data, but as I want to apply normalization to the data sets, I will have to split the data.

I already know that I can use :

SELECT *
FROM users
WHERE Username = UserNametxt.Text.Trim()

and then addWithValue etc.

How would I do this using a PK from one table linked to other tables as a FK?

Table users:

    id (pk)
    email
    password
    last_login

Table address:

    id (fk to users.id)
    houseNumber
    StreetName
    City

Table postcode:

    id (fk to users.id)
    PostCode

The above is a rough sample of what the data tables will be.

Body:
First of all, you should change the structure of your tables. In order to properly normalize DB, tables address and postcode should have their own id (PK), which does not depend on data from other tables.
If you leave it that way, you won't get rid of data duplication (which is one of the main reasons to normalize DB)

So it would look like that:

Table addresses:

id (PK)
userId (FK)
houseNumber
streetName
city

Table postcodes:

id (PK)
userId (FK)
postCode

And then you need to get information. You need to use JOIN to somehow connect tables and get information you need

SELECT * FROM users
LEFT JOIN addresses ON adresses.UserId=users.Id
LEFT JOIN postcodes ON postcodes.UserId=users.Id
WHERE ...


问:
How do I get the commands for PyPDF2 in Python
If I enter from the command line...

python -m pip
  I get a list of the pip commands.

If however I enter

```<code>python -m pypdf2
</code>```

I get "...no modules named pypdf2...".

From the shell, if I enter

```<code>>>>help("pypdf2")
</code>```

I get "No documentation found for pypdf2".

If I get a list of the modules with help("modules"), pypdf2 is the first module listed, not in alphabetical order like the rest of the modules.

I can download the documentation on line, but I am curious does this just mean that there is no documentation for pypdf2 in python?

答:
How did you install it? Assuming you've done python -m pip install pypdf2, you should note that the actual package name is PyPDF2. So even though the install works lower/mixed case, you have to use the actual name to import it or access its help docs: PyPDF2 vs pypdf2:

```<code>>>> import pypdf2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pypdf2'
>>> import PyPDF2
>>> help(PyPDF2)
Help on package PyPDF2:

...
>>> help("pypdf2")
No Python documentation found for 'pypdf2'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

>>> help("PyPDF2")
Help on package PyPDF2:

...
</code>```

PS. I didn't know that help() also accepts the object's name as strings rather than the object itself. Was going to point that out as an error, but tried it myself and saw that it works. Thanks!

PS2. So that allows providing the object name (as a string) to read the help docs without needing to import it first. Nice.

```<code>Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> # no import here
>>> help(PyPDF2)    # won't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'PyPDF2' is not defined
>>> help("PyPDF2")  # works, still not imported
Help on package PyPDF2:
```
```

Body:
If I enter from the command line...

python -m pip
  I get a list of the pip commands.

If however I enter

python -m pypdf2

I get "...no modules named pypdf2...".

From the shell, if I enter

>>>help("pypdf2")

I get "No documentation found for pypdf2".

If I get a list of the modules with help("modules"), pypdf2 is the first module listed, not in alphabetical order like the rest of the modules.

I can download the documentation on line, but I am curious does this just mean that there is no documentation for pypdf2 in python?

Body:
How did you install it? Assuming you've done python -m pip install pypdf2, you should note that the actual package name is PyPDF2. So even though the install works lower/mixed case, you have to use the actual name to import it or access its help docs: PyPDF2 vs pypdf2:

>>> import pypdf2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pypdf2'
>>> import PyPDF2
>>> help(PyPDF2)
Help on package PyPDF2:

...
>>> help("pypdf2")
No Python documentation found for 'pypdf2'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

>>> help("PyPDF2")
Help on package PyPDF2:

...

PS. I didn't know that help() also accepts the object's name as strings rather than the object itself. Was going to point that out as an error, but tried it myself and saw that it works. Thanks!

PS2. So that allows providing the object name (as a string) to read the help docs without needing to import it first. Nice.

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> # no import here
>>> help(PyPDF2)    # won't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'PyPDF2' is not defined
>>> help("PyPDF2")  # works, still not imported
Help on package PyPDF2:
```


问:
ld: library not found for -lRCTGeolocation error after upgrading to 60.5
I upgrade my react native project to 60.5 and after that I get this error building iOS
XcodeSpace </p>

```<code>ld: library not found for -lRCTGeolocation
</code>```

答: Try pod install --repo-update in your iOS folder.

Body:
I upgrade my react native project to 60.5 and after that I get this error building iOS
XcodeSpace

ld: library not found for -lRCTGeolocation