问:
Ability to exclude one page from https redirection in nginx ingress controller
I have an app in Kubernetes which is served over https. So now I would like to exclude one URL from that rule and use HTTP to serve it for performance reasons. I am struggling with that the whole day and it seems impossible.

These are my ingress YAML:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.11"],"port":443,"protocol":"HTTPS","serviceName":"myservice:myservice","ingressName":"myservice:myservice","hostname":"app.server.test.mycompany.com","path":"/","allNodes":true}]'
    kubernetes.io/ingress.class: nginx
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany
  namespace: mycompany
  resourceVersion: "565608"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany
  uid: c6b93108-a28f-4de6-a62b-487708b3f5d1
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /
  tls:
  - hosts:
    - app.server.test.mycompany.com
    secretName: mycompany-tls-secret
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11
</code>```

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.1"],"port":80,"protocol":"HTTP","serviceName":"mycompany:mycompany","ingressName":"mycompany:mycompany-particular-service","hostname":"app.server.test.mycompany.com","path":"/account_name/particular_service/","allNodes":true}]'
    nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
    nginx.ingress.kubernetes.io/use-regex: "true"
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany-particular-service
  namespace: mycompany
  resourceVersion: "565609"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany-particular-service
  uid: 88127a02-e0d1-4b2f-b226-5e8d160c1654
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /account_name/particular_service/
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11
</code>```

So as you can see from above I would like to server /particular_service/ over HTTP. Ingress, however, redirects to HTTPS as TLS is enabled for that host in the first ingress.

Is there any way to disable TLS just for that one specific path when the same host is being used for configuration?

In short summary I would like to have:

```<code>https://app.server.test.mycompany.com
but
http://app.server.test.mycompany.com/account_name/particular_service/
</code>```

答: Also add nginx.ingress.kubernetes.io/ssl-redirect ": "false". It had worked for me previously. You can give it a try.

Body:
I have an app in Kubernetes which is served over https. So now I would like to exclude one URL from that rule and use HTTP to serve it for performance reasons. I am struggling with that the whole day and it seems impossible.

These are my ingress YAML:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.11"],"port":443,"protocol":"HTTPS","serviceName":"myservice:myservice","ingressName":"myservice:myservice","hostname":"app.server.test.mycompany.com","path":"/","allNodes":true}]'
    kubernetes.io/ingress.class: nginx
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany
  namespace: mycompany
  resourceVersion: "565608"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany
  uid: c6b93108-a28f-4de6-a62b-487708b3f5d1
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /
  tls:
  - hosts:
    - app.server.test.mycompany.com
    secretName: mycompany-tls-secret
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    field.cattle.io/publicEndpoints: '[{"addresses":["172.31.1.1"],"port":80,"protocol":"HTTP","serviceName":"mycompany:mycompany","ingressName":"mycompany:mycompany-particular-service","hostname":"app.server.test.mycompany.com","path":"/account_name/particular_service/","allNodes":true}]'
    nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
    nginx.ingress.kubernetes.io/use-regex: "true"
  creationTimestamp: "2020-02-17T13:14:19Z"
  generation: 1
  labels:
    app-kubernetes-io/instance: mycompany
    app-kubernetes-io/managed-by: Tiller
    app-kubernetes-io/name: mycompany
    helm.sh/chart: mycompany-1.0.0
    io.cattle.field/appId: mycompany
  name: mycompany-particular-service
  namespace: mycompany
  resourceVersion: "565609"
  selfLink: /apis/extensions/v1beta1/namespaces/mycompany/ingresses/mycompany-particular-service
  uid: 88127a02-e0d1-4b2f-b226-5e8d160c1654
spec:
  rules:
  - host: app.server.test.mycompany.com
    http:
      paths:
      - backend:
          serviceName: mycompany
          servicePort: 80
        path: /account_name/particular_service/
status:
  loadBalancer:
    ingress:
    - ip: 172.31.1.11

So as you can see from above I would like to server /particular_service/ over HTTP. Ingress, however, redirects to HTTPS as TLS is enabled for that host in the first ingress.

Is there any way to disable TLS just for that one specific path when the same host is being used for configuration?

In short summary I would like to have:

https://app.server.test.mycompany.com
but
http://app.server.test.mycompany.com/account_name/particular_service/


来源: stackexchange

问:
error embedding input shape: expected embedding_1_input to have shape (25,) but got array with shape (1,)
I'm not sure why I keep getting this error. I've checked the length of my actual tokenised + encoded text data and it matches the input length I selected. The code is below:

```<code>from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

import numpy as np

training_samples = 6603
max_words = 10000  # We will only consider the top 10,000 words in the dataset

tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(X_train)
sequences = tokenizer.texts_to_sequences(X_train)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
print('Shape of data tensor:', X_train.shape)

max_length = 25
padded_s = pad_sequences(sequences, maxlen=max_length, padding='post')
print(padded_s)

print(padded_s.shape)

y_train = np.array(y_train)
y_test = np.array(y_test)
</code>```

From this - the output was:

```<code>Found 10759 unique tokens.
Shape of data tensor: (5942,)
[[  17  119  154 ...    0    0    0]
 [  31  116   40 ...    0    0    0]
 [1925 1711   15 ...  184    0    0]
 ...
 [   6 1915  375 ...    0    0    0]
 [ 693  190   24 ...    0    0    0]
 [   1  570    2 ...    0    0    0]]
**(5942, 25)**
</code>```

As you can see from above, it is 25 and not 1!

```<code> glove_dir = '/Users/xxx/Downloads/glove.6B'
embeddings_index = {}
f = open(os.path.join(glove_dir, 'glove.6B.100d.txt'))
for line in f:
    values = line.split()
    word = values[0]
    coefs = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))

embedding_dim = 100

embedding_matrix = np.zeros((max_words, embedding_dim))

for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if i < max_words:
        if embedding_vector is not None:
            # Words not found in embedding index will be all-zeros.
            embedding_matrix[i] = embedding_vector

from keras.models import Sequential
from keras.layers import Embedding, Flatten, Dense
model = Sequential()
model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_length, trainable=False))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['acc'])
history = model.fit(padded_s, y_train,
                    epochs=10,
                    batch_size=32,
                    validation_data=(X_val, y_val))
model.save_weights('pre_trained_glove_model.h5')
</code>```

This returns the error:

```<code>ValueError: Error when checking input: expected embedding_1_input to have shape (25,) but got array with shape (1,)
</code>```

Any help would be appreciated - thank you so much!

答: Fixed: I forgot to convert my validation set into sequences + pad the sequences.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm not sure why I keep getting this error. I've checked the length of my actual tokenised + encoded text data and it matches the input length I selected. The code is below:

from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

import numpy as np

training_samples = 6603
max_words = 10000  # We will only consider the top 10,000 words in the dataset

tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(X_train)
sequences = tokenizer.texts_to_sequences(X_train)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
print('Shape of data tensor:', X_train.shape)

max_length = 25
padded_s = pad_sequences(sequences, maxlen=max_length, padding='post')
print(padded_s)

print(padded_s.shape)

y_train = np.array(y_train)
y_test = np.array(y_test)

From this - the output was:

Found 10759 unique tokens.
Shape of data tensor: (5942,)
[[  17  119  154 ...    0    0    0]
 [  31  116   40 ...    0    0    0]
 [1925 1711   15 ...  184    0    0]
 ...
 [   6 1915  375 ...    0    0    0]
 [ 693  190   24 ...    0    0    0]
 [   1  570    2 ...    0    0    0]]
**(5942, 25)**

As you can see from above, it is 25 and not 1!

 glove_dir = '/Users/xxx/Downloads/glove.6B'
embeddings_index = {}
f = open(os.path.join(glove_dir, 'glove.6B.100d.txt'))
for line in f:
    values = line.split()
    word = values[0]
    coefs = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))

embedding_dim = 100

embedding_matrix = np.zeros((max_words, embedding_dim))

for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if i < max_words:
        if embedding_vector is not None:
            # Words not found in embedding index will be all-zeros.
            embedding_matrix[i] = embedding_vector

from keras.models import Sequential
from keras.layers import Embedding, Flatten, Dense
model = Sequential()
model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_length, trainable=False))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.summary()

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['acc'])
history = model.fit(padded_s, y_train,
                    epochs=10,
                    batch_size=32,
                    validation_data=(X_val, y_val))
model.save_weights('pre_trained_glove_model.h5')

This returns the error:

ValueError: Error when checking input: expected embedding_1_input to have shape (25,) but got array with shape (1,)

Any help would be appreciated - thank you so much!


问:
how can i find the minutes difference in this timeformat?
```<code>05-Dec-19 08.30.00.000000000
05-Dec-19 08.31.00.000000000
</code>```

i want do find the minutes difference between these two time formats in mysql(phpmyadmin 5.7.x)?

Body:
05-Dec-19 08.30.00.000000000
05-Dec-19 08.31.00.000000000

i want do find the minutes difference between these two time formats in mysql(phpmyadmin 5.7.x)?

Body:
You appear to be storing datetimes as strings. So you would first need to convert these strings to dates (for this, you can use STR_TO_DATE()); then you can use timestampdiff() to compute the difference in minutes:

timestampdiff(
    minute,
    str_to_date(mycol1, '%d-%b-%y %H.%i.%s.%f'),
    str_to_date(mycol2, '%d-%b-%y %H.%i.%s.%f')
)

Demo on DB Fiddle:

select
    str_to_date('05-Dec-19 08.30.00.000000000', '%d-%b-%y %H.%i.%s.%f') date1,
    str_to_date('05-Dec-19 08.31.00.000000000', '%d-%b-%y %H.%i.%s.%f') date2,
    timestampdiff(
        minute,
        str_to_date('05-Dec-19 08.30.00.000000000', '%d-%b-%y %H.%i.%s.%f'),
        str_to_date('05-Dec-19 08.31.00.000000000', '%d-%b-%y %H.%i.%s.%f')
    )minutes_diff

date1                      | date2                      | minutes_diff
:------------------------- | :------------------------- | -----------:
2019-12-05 08:30:00.000000 | 2019-12-05 08:31:00.000000 |            1


问:
Script worked on all sheest and stop working suddenly only on one sheet
I have written script for Google sheets with offset when a forms is submitted.
There are 2 sheets with 2 associated Gforms.

Previously, the following script was working well on both sheets.
Suddenly, the scripts were working only on one sheet. I have tried to launch manually the script on the active sheet I want (sheet activated obviously), the script is not running. However, the script is well running on the other sheet.

To sum-up:

The script is not running (manually neither with Gforms submission offset): sheetname "DemandeIntervention F-TEC-052"
The script is running (manually or with Gforms submission offset): sheetname "RapportIntervention F-QUA-052"

Hereafter the script:

```<code>function CopyFormatting() {

//Déclaration des variables
var SS = SpreadsheetApp.getActiveSheet(); //Sheet of forms response
var LastRow = SS.getLastRow(); //last row of sheet (n)
var RefRow = SS.getRange('3:3'); //Row n°3 considered as reference

//Copy formatting to last row from reference row
RefRow.copyTo(SS.getRange(LastRow,1), {formatOnly: true});

}
</code>```

Please, could you help me to run the script on both sheets?
Thank you

答:
The difference between your two sheets is that the nonworking one has a value in cell B104.

Thus SS.getLastRow(); retrieves 104 as the last row of the sheet, and consequently cell A104 is the one to be formatted during each script execution.

You can avoid this problem by deleting all rows below the row with the last form response.

If it is very important for you to have text i B104, then you have to replace getLastRow() through other methods, such as e.g. getNextDataCell(direction).

Body:
I have written script for Google sheets with offset when a forms is submitted.
There are 2 sheets with 2 associated Gforms.

Previously, the following script was working well on both sheets.
Suddenly, the scripts were working only on one sheet. I have tried to launch manually the script on the active sheet I want (sheet activated obviously), the script is not running. However, the script is well running on the other sheet.

To sum-up:

The script is not running (manually neither with Gforms submission offset): sheetname "DemandeIntervention F-TEC-052"
The script is running (manually or with Gforms submission offset): sheetname "RapportIntervention F-QUA-052"

Hereafter the script:

function CopyFormatting() {

//Déclaration des variables
var SS = SpreadsheetApp.getActiveSheet(); //Sheet of forms response
var LastRow = SS.getLastRow(); //last row of sheet (n)
var RefRow = SS.getRange('3:3'); //Row n°3 considered as reference

//Copy formatting to last row from reference row
RefRow.copyTo(SS.getRange(LastRow,1), {formatOnly: true});

}

Please, could you help me to run the script on both sheets?
Thank you


问:
Detecting length of overlap between two strings
```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}
</code>```

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

```<code>abcdefg
1234efg
</code>```

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

答:
Looks a little bit like homework to me, is it?

You'r while clause exits as soon as it discovers a difference between the strings. You will have to loop over the entire string, and for each index i count it if s1[i] == s2[i].

ContentLicense: CC BY-SA 3.0

Body:
int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

abcdefg
1234efg

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?


问:
C++ : undetectable change of variable, artificial "volatile" mutex not works
How it is possible, that is such a line just after if statement with unequal, variables are already equal in pull() method? I have already added Mutex variable, but it not helped.

```<code> int fQ::pull(void){ // pull element from the queue
  while(MutexF);
   MutexF = 1;
  if (last != first){
  fQueue[first++]();
  first%=lengthQ;
  MutexF = 0;
  return 0;
  }
  else{
      MutexF = 0;
        return 1;
  }
}
</code>```

STL containers are to heavy for me, I preparing it for a tiny MCU, that's why, I tried to avoid   all this complex staff like (std::mutex, std::atomic, std::mutex etc.). Those  multitheading is needed only for test purpose, instead of testing with the tiny MCU's interrupts, for a while. I supposed not use any stl/thread libraries at all

 photo of the error

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/main.cpp

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/nortos.h

答:
```<code>   #include <mutex>          // std::mutex

typedef void(*FunctionPointer)(void);

class fQ {
private:
    std::atomic<int> first;
    std::atomic<int> last;
    FunctionPointer * fQueue;
    int lengthQ;
    std::mutex mtx;
public:
    fQ(int sizeQ);
    ~fQ();
    int push(FunctionPointer);
    int pull(void);
};

fQ::fQ(int sizeQ){ // initialization of Queue
  fQueue = new FunctionPointer[sizeQ];
  last = 0;
  first = 0;
  lengthQ = sizeQ;
}

fQ::~fQ(){ // initialization of Queue
  delete [] fQueue;
}

int fQ::push(FunctionPointer pointerF){ // push element from the queue
 mtx.lock();
  if ((last+1)%lengthQ == first){
        mtx.unlock();
        return 1;
  }
  fQueue[last++] = pointerF;
  last = last%lengthQ;
  mtx.unlock();
  return 0;
}

int fQ::pull(void){ // pull element from the queue
 mtx.lock();
  if (last != first){
  fQueue[first++]();
  first = first%lengthQ;
   mtx.unlock();
  return 0;
  }
  else{
   mtx.unlock();
   return 1;
  }
}
</code>```

Body:
How it is possible, that is such a line just after if statement with unequal, variables are already equal in pull() method? I have already added Mutex variable, but it not helped.

 int fQ::pull(void){ // pull element from the queue
  while(MutexF);
   MutexF = 1;
  if (last != first){
  fQueue[first++]();
  first%=lengthQ;
  MutexF = 0;
  return 0;
  }
  else{
      MutexF = 0;
        return 1;
  }
}

STL containers are to heavy for me, I preparing it for a tiny MCU, that's why, I tried to avoid   all this complex staff like (std::mutex, std::atomic, std::mutex etc.). Those  multitheading is needed only for test purpose, instead of testing with the tiny MCU's interrupts, for a while. I supposed not use any stl/thread libraries at all

 photo of the error

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/main.cpp

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/nortos.h


问:
MYSQL - Update row number for each group
I am trying to update the column sip_count so that it counts the number of rows with the same sip_id as shown below. None of the things that I have tried are worth posting. How do I do this?

Table

```<code>sip_id | sip   | sip_count
---------------------------
 1      |  1    | 2
 1      |  1    | 2
 2      |  1    | 3
 2      |  1    | 3
 2      |  1    | 3
 4      |  1    | 2
 4      |  1    | 2
 3      |  1    | 3
 3      |  1    | 3
 3      |  1    | 3
</code>```

Desired result

```<code> sip_id | sip   | sip_count
---------------------------
 1      |  1    | 1
 1      |  1    | 2
 2      |  1    | 1
 2      |  1    | 2
 2      |  1    | 3
 4      |  1    | 1
 4      |  1    | 2
 3      |  1    | 1
 3      |  1    | 2
 3      |  1    | 3
</code>```

答:
UPDATE

Try to use variable:

```<code>SET @i:=0;
UPDATE
    table_name
INNER JOIN
    (
    SELECT
        table_name.primary_key,
        table_name.sip_id,
        @i:=IF(@i > b.count, 1, @i+1) AS count
    FROM table_name
    INNER JOIN
        (
          SELECT
            sip_id,
            COUNT(sip_count) AS count
          FROM table_name GROUP BY sip_id
        ) b
    ON table_name.sip_id = b.sip_id
      ) c
ON table_name.primary_key = c.primary_key
SET sip_count=c.count
</code>```

Body:
I am trying to update the column sip_count so that it counts the number of rows with the same sip_id as shown below. None of the things that I have tried are worth posting. How do I do this?

Table

sip_id | sip   | sip_count
---------------------------
 1      |  1    | 2
 1      |  1    | 2
 2      |  1    | 3
 2      |  1    | 3
 2      |  1    | 3
 4      |  1    | 2
 4      |  1    | 2
 3      |  1    | 3
 3      |  1    | 3
 3      |  1    | 3

Desired result

 sip_id | sip   | sip_count
---------------------------
 1      |  1    | 1
 1      |  1    | 2
 2      |  1    | 1
 2      |  1    | 2
 2      |  1    | 3
 4      |  1    | 1
 4      |  1    | 2
 3      |  1    | 1
 3      |  1    | 2
 3      |  1    | 3

Body:
UPDATE

Try to use variable:

SET @i:=0;
UPDATE
    table_name
INNER JOIN
    (
    SELECT
        table_name.primary_key,
        table_name.sip_id,
        @i:=IF(@i > b.count, 1, @i+1) AS count
    FROM table_name
    INNER JOIN
        (
          SELECT
            sip_id,
            COUNT(sip_count) AS count
          FROM table_name GROUP BY sip_id
        ) b
    ON table_name.sip_id = b.sip_id
      ) c
ON table_name.primary_key = c.primary_key
SET sip_count=c.count


问:
How to enable email verification link to expire after verification in laravel 6 API implemented using VerifiesEmail feature?
I have implemented Laravel 6 API and used Laravel's inbuilt Illuminate\Foundation\Auth\VerifiesEmails  based on tutorial here but the email verification link is not expired and still accessible after successful email verification. I have found many tutorials regarding laravel frontend but how to implement it on API.

VerificationApiController

class VerificationApiController extends Controller
{
    use VerifiesEmails;

    /**
     * Mark the authenticated user's email address as verified.
     * @param  Request  $request
     * @return JsonResponse
     */
    public function verify(Request $request): JsonResponse
    {
        $userID = $request['id'];
        $user = User::findOrFail($userID);
        $date = date('Y-m-d g:i:s');

        // to enable the “email_verified_at field of that
        // user be a current time stamp by mimicking the
        // must verify email feature
        $user->email_verified_at = $date;
        $user->save();

        return response()->json('Email verified!');
    }

    /**
     * Resend the email verification notification.
     * @param  Request  $request
     * @return JsonResponse|Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return response()->json('User already have verified email!', 422);

        }
        $request->user()->sendEmailVerificationNotification();

        return response()->json('The notification has been resubmitted');
        // return back()->with(‘resent’, true);
    }
}
```

<p><strong>User model</strong> </p>

<pre class="lang-php prettyprint-override"><code>class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'name', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Send email verification notification
     */
    public function sendApiEmailVerificationNotification()
    {
        $this->notify(new VerifyApiEmail); // my notification
    }
}
</code>```

Here are verification api routes

```<code>Route::get(‘email/verify/{id}’, ‘VerificationApiController@verify’)->name(‘verificationapi.verify’);
Route::get(‘email/resend’, ‘VerificationApiController@resend’)->name(‘verificationapi.resend’)
</code>```

Here is UsersApiController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Auth;
use Validator;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Auth\Events\Verified;
class UsersApiController extends Controller
{
use VerifiesEmails;
public $successStatus = 200;
/**
* login api
*
* @return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt([‘email’ => request(‘email’), ‘password’ => request(‘password’)])){
$user = Auth::user();
if($user->email_verified_at !== NULL){
$success[‘message’] = “Login successfull”;
return response()->json([‘success’ => $success], $this-> successStatus);
}else{
return response()->json([‘error’=>’Please Verify Email’], 401);
}
}
else{
return response()->json([‘error’=>’Unauthorised’], 401);
}
}
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
‘name’ => ‘required’,
‘email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’,
]);
if ($validator->fails()) {
return response()->json([‘error’=>$validator->errors()], 401);
}
$input = $request->all();
$input[‘password’] = Hash::make($input[‘password’]);
$user = User::create($input);
$user->sendApiEmailVerificationNotification();
$success[‘message’] = ‘Please confirm yourself by clicking on verify user button sent to you on your email’;
return response()->json([‘success’=>$success], $this-> successStatus);
}
/**
* details api
*
* @return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json([‘success’ => $user], $this-> successStatus);
}
}
```

<p>Here are user and auth routes</p>

```Route::post(‘login’, ‘UsersApiController@login’);
Route::post(‘register’, ‘UsersApiController@register’);
Route::group([‘middleware’ => ‘auth:api’], function(){
Route::post(‘details’, ‘UsersApiController@details’)->middleware(‘verified’);
}); // will work only when user has verified the email
```

so the problem is that when I click on verification link on email the user is verified but the link is not expired . I want the link to be expired as soon as user is verified. How to do that?

答:
Have you implemented the VerifyApiEmail class?

```<code>namespace App\Notifications;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyApiEmail extends VerifyEmailBase
{
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
        'api.auth.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );
    }
}
</code>```

Here you can add the expiration time in minutes, seconds or hours.

Body:
I have implemented Laravel 6 API and used Laravel's inbuilt Illuminate\Foundation\Auth\VerifiesEmails  based on tutorial here but the email verification link is not expired and still accessible after successful email verification. I have found many tutorials regarding laravel frontend but how to implement it on API.

VerificationApiController

class VerificationApiController extends Controller
{
    use VerifiesEmails;

    /**
     * Mark the authenticated user's email address as verified.
     * @param  Request  $request
     * @return JsonResponse
     */
    public function verify(Request $request): JsonResponse
    {
        $userID = $request['id'];
        $user = User::findOrFail($userID);
        $date = date('Y-m-d g:i:s');

        // to enable the “email_verified_at field of that
        // user be a current time stamp by mimicking the
        // must verify email feature
        $user->email_verified_at = $date;
        $user->save();

        return response()->json('Email verified!');
    }

    /**
     * Resend the email verification notification.
     * @param  Request  $request
     * @return JsonResponse|Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return response()->json('User already have verified email!', 422);

        }
        $request->user()->sendEmailVerificationNotification();

        return response()->json('The notification has been resubmitted');
        // return back()->with(‘resent’, true);
    }
}

User model

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'name', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Send email verification notification
     */
    public function sendApiEmailVerificationNotification()
    {
        $this->notify(new VerifyApiEmail); // my notification
    }
}

Here are verification api routes

Route::get(‘email/verify/{id}’, ‘VerificationApiController@verify’)->name(‘verificationapi.verify’);
Route::get(‘email/resend’, ‘VerificationApiController@resend’)->name(‘verificationapi.resend’)

Here is UsersApiController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Auth;
use Validator;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Auth\Events\Verified;
class UsersApiController extends Controller
{
use VerifiesEmails;
public $successStatus = 200;
/**
* login api
*
* @return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt([‘email’ => request(‘email’), ‘password’ => request(‘password’)])){
$user = Auth::user();
if($user->email_verified_at !== NULL){
$success[‘message’] = “Login successfull”;
return response()->json([‘success’ => $success], $this-> successStatus);
}else{
return response()->json([‘error’=>’Please Verify Email’], 401);
}
}
else{
return response()->json([‘error’=>’Unauthorised’], 401);
}
}
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
‘name’ => ‘required’,
‘email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’,
]);
if ($validator->fails()) {
return response()->json([‘error’=>$validator->errors()], 401);
}
$input = $request->all();
$input[‘password’] = Hash::make($input[‘password’]);
$user = User::create($input);
$user->sendApiEmailVerificationNotification();
$success[‘message’] = ‘Please confirm yourself by clicking on verify user button sent to you on your email’;
return response()->json([‘success’=>$success], $this-> successStatus);
}
/**
* details api
*
* @return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json([‘success’ => $user], $this-> successStatus);
}
}

Here are user and auth routes

Route::post(‘login’, ‘UsersApiController@login’);
Route::post(‘register’, ‘UsersApiController@register’);
Route::group([‘middleware’ => ‘auth:api’], function(){
Route::post(‘details’, ‘UsersApiController@details’)->middleware(‘verified’);
}); // will work only when user has verified the email

so the problem is that when I click on verification link on email the user is verified but the link is not expired . I want the link to be expired as soon as user is verified. How to do that?

Body:
Have you implemented the VerifyApiEmail class?

namespace App\Notifications;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyApiEmail extends VerifyEmailBase
{
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
        'api.auth.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );
    }
}

Here you can add the expiration time in minutes, seconds or hours.


问:
Linq-to-Entities match ID in list of integers in a compiled query
I'm trying to find a way to implement a Linq-to-Entities compiled query of the form:

```<code>Func<MyEntities, List<int>, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, List<int> IDs) => (
         (from au in entities.Mine where IDs.Any(x => x == au.ID) select au)
    ));
</code>```

Because only scalar parameters can be passed to CompiledQuery.Compile the above fails. I'm trying to find some clever way to pass a comma delimited list of integers as a string and use that in the L2E query along the lines of:

```<code>Func<MyEntities, string, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Split(',').Any(x => Convert.ToInt32(x) == au.ID) select au)
    ));
</code>```

But that doesn't work due to the unsupported Split function.

Any clever ideas about how this could be implemented?

答:
I ended up finding a way to do it but it's way too slow at around 3s.

```<code>string ids = "|" + String.Join("|", new List<int> { 4, 5, 6, 7, 8, 9, 10, 20, 23, 34 }) + "|";

Func<MyEntities, string, IQueryable<MyClass>> query =     System.Data.Objects.CompiledQuery.Compile(
(MyEntities entities, string IDs) => (
     (from au in entities.Mine where IDs.Contains("|" + SqlFunctions.StringConvert((decimal)au.ID).Trim() + "|")select au)
));
</code>```

Back to the drawing board.

Body:
I'm trying to find a way to implement a Linq-to-Entities compiled query of the form:

Func<MyEntities, List<int>, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, List<int> IDs) => (
         (from au in entities.Mine where IDs.Any(x => x == au.ID) select au)
    ));

Because only scalar parameters can be passed to CompiledQuery.Compile the above fails. I'm trying to find some clever way to pass a comma delimited list of integers as a string and use that in the L2E query along the lines of:

Func<MyEntities, string, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Split(',').Any(x => Convert.ToInt32(x) == au.ID) select au)
    ));

But that doesn't work due to the unsupported Split function.

Any clever ideas about how this could be implemented?

Body:
I ended up finding a way to do it but it's way too slow at around 3s.

string ids = "|" + String.Join("|", new List<int> { 4, 5, 6, 7, 8, 9, 10, 20, 23, 34 }) + "|";

Func<MyEntities, string, IQueryable<MyClass>> query =     System.Data.Objects.CompiledQuery.Compile(
(MyEntities entities, string IDs) => (
     (from au in entities.Mine where IDs.Contains("|" + SqlFunctions.StringConvert((decimal)au.ID).Trim() + "|")select au)
));

Back to the drawing board.


问:
E2E testing multiple posibilities with exception
i have a problem that i don't exactly know how to solve. I'm implementing an E2E test in which using selenium i need to click in a Link and check that is sending me to the right URL.

Here starts the problem...

There are 3 possibilities, mix of 2 types of links, just one type of link or the other type of link. No problems with the situations in which there are both types of links but when there is just one type when it searches for the identifier we use for the links that are not in page it gives me a timeoutException. This is not a failure because it's a posible situation but i will like to know if there is a way in which to check that if it finds no links it asserts that the exception is thrown.

I though using a runCatching (or try catch) wait for the link to appear and if it doesn't appear the test asserts that when i look for the element the timeout exception is thrown again.

It smells a bit for me this way of doing it and i don't know if it's correctly done.

EDIT: Im ussing AssertK and JUnit5 for testing.

EDIT 2: I've done this, i dont know if it a correct way of doing it

```<code>runCatching {
            driver.waitFor(numberOfWidgetsToBeMoreThan(BrowserSelector.cssSelector(OFFERS_WITH_PRICE_AND_DATE), 0), ofMillis(2000))
        }.onFailure {
            assertThrows<WaitTimeoutException> {
                findLink(OFFERS_WITH_PRICE_AND_DATE)
            }
        }.onSuccess {
            val widget = findLink(OFFERS_WITH_PRICE_AND_DATE)
            widget.click()
            assertThat(driver.url).contains(NO_DATE_TEXT)
        }
</code>```

答:
I'm not sure I understood your problem correctly, but you can use assertFails to assert that a piece of code throws an exception:</p>

```<code>
@Test
fun test() {
    val exception = assertFails {
        // some code that should throw
    }
    // some more assertions on the type of exception etc. may go here
}
</code>```

Body:
i have a problem that i don't exactly know how to solve. I'm implementing an E2E test in which using selenium i need to click in a Link and check that is sending me to the right URL.

Here starts the problem...

There are 3 possibilities, mix of 2 types of links, just one type of link or the other type of link. No problems with the situations in which there are both types of links but when there is just one type when it searches for the identifier we use for the links that are not in page it gives me a timeoutException. This is not a failure because it's a posible situation but i will like to know if there is a way in which to check that if it finds no links it asserts that the exception is thrown.

I though using a runCatching (or try catch) wait for the link to appear and if it doesn't appear the test asserts that when i look for the element the timeout exception is thrown again.

It smells a bit for me this way of doing it and i don't know if it's correctly done.

EDIT: Im ussing AssertK and JUnit5 for testing.

EDIT 2: I've done this, i dont know if it a correct way of doing it

runCatching {
            driver.waitFor(numberOfWidgetsToBeMoreThan(BrowserSelector.cssSelector(OFFERS_WITH_PRICE_AND_DATE), 0), ofMillis(2000))
        }.onFailure {
            assertThrows<WaitTimeoutException> {
                findLink(OFFERS_WITH_PRICE_AND_DATE)
            }
        }.onSuccess {
            val widget = findLink(OFFERS_WITH_PRICE_AND_DATE)
            widget.click()
            assertThat(driver.url).contains(NO_DATE_TEXT)
        }

Body:
I'm not sure I understood your problem correctly, but you can use assertFails to assert that a piece of code throws an exception:

@Test
fun test() {
    val exception = assertFails {
        // some code that should throw
    }
    // some more assertions on the type of exception etc. may go here
}


问:
How update orders by using woocommerce api in node js
```<code>exports.UpdateOrder = (req, res) => {
  const data = {
    status: "completed"
  };
  WooCommerce.put("orders/3217", data)
    .then((response) => {
      res.json(JSON.parse(response.body));
    })
    .catch((error) => {
      console.log(error.response.data);
    });
};
</code>```

getting error
TypeError: WooCommerce.put(...).then is not a function

答:
Perhaps try using promisified methods such as in this example https://www.npmjs.com/package/woocommerce-api#promified-methods

Promified Methods
  Every method can be used in a promified way just adding Async to the method name. Like in:

```<code>WooCommerce.getAsync('products').then(function(result) {
  return JSON.parse(result.toJSON().body);
});
</code>```

Body:
exports.UpdateOrder = (req, res) => {
  const data = {
    status: "completed"
  };
  WooCommerce.put("orders/3217", data)
    .then((response) => {
      res.json(JSON.parse(response.body));
    })
    .catch((error) => {
      console.log(error.response.data);
    });
};

getting error
TypeError: WooCommerce.put(...).then is not a function

Body:
Perhaps try using promisified methods such as in this example https://www.npmjs.com/package/woocommerce-api#promified-methods

Promified Methods
  Every method can be used in a promified way just adding Async to the method name. Like in:

WooCommerce.getAsync('products').then(function(result) {
  return JSON.parse(result.toJSON().body);
});


问:
How do you handle bad data when converting XLS to MySQL DB
I'm working on a project where I need to convert a Database inside an XLS file to MySQL. I have python code already working that can do this, but I'm not sure about the proper way to dynamically handle edge cases.

```<code>End Date
04/12/2006 10:00:00
04/12/2006 11:00:00
4/12/2006 13:00:00 PM
</code>```

For example I have one column of dates here. Obviously I can edit the cell here manually to match the other date format, but this isn't scalable if there are thousands of dates.

I can also write python code to handle this specific malformed date format, but it wouldn't work for other malformed dates.

```<code>  for c in range(0,col_names.ncols):
        #Ctype 3 means its a date. 1 is for Text
        if col_names.cell(r,c).ctype == 3:
            raw_time = xlrd.xldate_as_tuple(col_names.cell(r,c).value, book.datemode)
            rowData.append(str(datetime.datetime(*raw_time)))
        else:

            if col_names.cell(r,c).value == 'NULL':
                rowData.append(None)
            elif "PM" in col_names.cell(r,c).value:
                col_names.cell(r,c).value = col_names.cell(r,c).replace("PM","")

            elif "AM" in col_names.cell(r,c).value:
                col_names.cell(r,c).value = col_names.cell(r,c).replace("AM","")

            else:
                rowData.append(col_names.cell(r,c).value)
</code>```

I tried setting this column in Excel to be a Date format. All other cells except the last one converted fine.

Are there any programs or methods that will allow me override any date string in this column be the proper format?

Do other programs like SAS have a better ability to dynamically format input data?

答:
SAS does have a few different types of automated date reading functions.

Let's assume that your date is formatted exactly that way in Excel. Because this contains multiple datetime formats and the last format is being detected as a character, Excel converts some of the known dates into the number of days since Jan 1st 1900. SAS will read the raw values as characters.

```<code>End Date
38819.416666667
38819.458333333
4/12/2006 13:00:00 PM
</code>```

We can use the anydtdtm. format to read in a variety of different types of datetime formats. If you find /, :, -, or , assume that it is a date Excel could not recognize as a date. Otherwise, adjust the Excel datetime to a SAS datetime (number of seconds since Jan 1st 1960) by reducing the days by the date of  Dec 30th 1899 and converting from days to seconds using the DHMS() function.  The reason to use Dec 30th instead of Jan 1st is because SAS and Excel disagree on whether to count from zero or one and because Excel mistakenly thinks 1900 was a leap year.

```<code>data want;
    set have;

    if(findc('end date'n, '/:- ') ) then end_datetime = input('end date'n, anydtdtm.);
        else end_datetime = dhms('end date'n + '30dec1899'd,0,0,0);

    format end_datetime datetime32.;
run;
</code>```

This works for the three cases you gave. You'll need to test out other cases to see what happens. If Excel recognizes everything as a datetime, then you will not need to manually convert to a SAS datetime and proc import will handle everything.

Body:
I'm working on a project where I need to convert a Database inside an XLS file to MySQL. I have python code already working that can do this, but I'm not sure about the proper way to dynamically handle edge cases.

End Date
04/12/2006 10:00:00
04/12/2006 11:00:00
4/12/2006 13:00:00 PM

For example I have one column of dates here. Obviously I can edit the cell here manually to match the other date format, but this isn't scalable if there are thousands of dates.

I can also write python code to handle this specific malformed date format, but it wouldn't work for other malformed dates.

  for c in range(0,col_names.ncols):
        #Ctype 3 means its a date. 1 is for Text
        if col_names.cell(r,c).ctype == 3:
            raw_time = xlrd.xldate_as_tuple(col_names.cell(r,c).value, book.datemode)
            rowData.append(str(datetime.datetime(*raw_time)))
        else:

            if col_names.cell(r,c).value == 'NULL':
                rowData.append(None)
            elif "PM" in col_names.cell(r,c).value:
                col_names.cell(r,c).value = col_names.cell(r,c).replace("PM","")

            elif "AM" in col_names.cell(r,c).value:
                col_names.cell(r,c).value = col_names.cell(r,c).replace("AM","")

            else:
                rowData.append(col_names.cell(r,c).value)

I tried setting this column in Excel to be a Date format. All other cells except the last one converted fine.

Are there any programs or methods that will allow me override any date string in this column be the proper format?

Do other programs like SAS have a better ability to dynamically format input data?

Body:
SAS does have a few different types of automated date reading functions.

Let's assume that your date is formatted exactly that way in Excel. Because this contains multiple datetime formats and the last format is being detected as a character, Excel converts some of the known dates into the number of days since Jan 1st 1900. SAS will read the raw values as characters.

End Date
38819.416666667
38819.458333333
4/12/2006 13:00:00 PM

We can use the anydtdtm. format to read in a variety of different types of datetime formats. If you find /, :, -, or , assume that it is a date Excel could not recognize as a date. Otherwise, adjust the Excel datetime to a SAS datetime (number of seconds since Jan 1st 1960) by reducing the days by the date of  Dec 30th 1899 and converting from days to seconds using the DHMS() function.  The reason to use Dec 30th instead of Jan 1st is because SAS and Excel disagree on whether to count from zero or one and because Excel mistakenly thinks 1900 was a leap year.

data want;
    set have;

    if(findc('end date'n, '/:- ') ) then end_datetime = input('end date'n, anydtdtm.);
        else end_datetime = dhms('end date'n + '30dec1899'd,0,0,0);

    format end_datetime datetime32.;
run;

This works for the three cases you gave. You'll need to test out other cases to see what happens. If Excel recognizes everything as a datetime, then you will not need to manually convert to a SAS datetime and proc import will handle everything.


问:
bitwise join two if's into one
I have this,

```<code>public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;
</code>```

I'd like to convert this,

```<code>if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;
</code>```

Into something like,

```<code>if((someCondition & condition) == someCondition) return true;
</code>```

But it isn't working.  What am I forgetting?

答:
There is a special convenience method HasFlag in .NET4 expressly for this purpose:

```<code>if (condition.HasFlag(someCondition)) return true;
</code>```

Here's the docs:

Enum.HasFlag Method

Title: bitwise join two if's into one

Body:
I have this,

public enum Condition : uint // bitwise
{
    None = 0,
    NewLine = 1,
    Space = 2
}

Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;

I'd like to convert this,

if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;

Into something like,

if((someCondition & condition) == someCondition) return true;

But it isn't working.  What am I forgetting?

Body:
There is a special convenience method HasFlag in .NET4 expressly for this purpose:

if (condition.HasFlag(someCondition)) return true;

Here's the docs:

Enum.HasFlag Method


问:
save pandas df into several different CSV files
This is some code that will generate some random time series data. Ultimately I am trying to save each days, data into separate CSV files...

```<code>import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
</code>```

I can print each days data with this:

```<code>for idx, days in df.groupby(df.index.date):
    print(days)
</code>```

But how could I encorporate savings individual CSV files into a directory csv each file named with the first time stamp entry of month & day? (Code below does not work)

```<code>for idx, days in df.groupby(df.index.date):
    for day in days:
        df2 = pd.DataFrame(list(day))
        month_num = df.index.month[0]
        day_num = df.index.day[0]

        df2.to_csv('/csv/' + f'{month_num}' + '_' + f'{day_num}' + '.csv')
</code>```

答:
You could iterate over all available days, filter your dataframe and then save.</p>

```<code># iterate over all available days
for date in set(df.index.date):

    # filter your dataframe
    filtered_df = df.loc[df.index.date == date].copy()

    # save it
    filename = date.strftime('%m_%d')  # filename represented as 'month_day'
    filtered_df.to_csv(f"./csv/{filename}.csv")
</code>```

Body:
This is some code that will generate some random time series data. Ultimately I am trying to save each days, data into separate CSV files...

import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

I can print each days data with this:

for idx, days in df.groupby(df.index.date):
    print(days)

But how could I encorporate savings individual CSV files into a directory csv each file named with the first time stamp entry of month & day? (Code below does not work)

for idx, days in df.groupby(df.index.date):
    for day in days:
        df2 = pd.DataFrame(list(day))
        month_num = df.index.month[0]
        day_num = df.index.day[0]

        df2.to_csv('/csv/' + f'{month_num}' + '_' + f'{day_num}' + '.csv')

Body:
You could iterate over all available days, filter your dataframe and then save.

# iterate over all available days
for date in set(df.index.date):

    # filter your dataframe
    filtered_df = df.loc[df.index.date == date].copy()

    # save it
    filename = date.strftime('%m_%d')  # filename represented as 'month_day'
    filtered_df.to_csv(f"./csv/{filename}.csv")


问:
Cassandra Update Record : Non PRIMARY KEY columns found
I created table in Cassandra database name as information_tbl.
query:

```<code>CREATE TABLE IF NOT EXISTS Information_tbl (id uuid ,
                                      cam_id varchar,
                                      camzone varchar,
                                      msg varchar,
                                      fltr int,
                                      time_stamp int,
                                      PRIMARY KEY (fltr,time_stamp)
                                      )WITH CLUSTERING ORDER BY (time_stamp DESC);
</code>```

when I execute update query, it show error :

Query 1:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Some partition key parts are missing: fltr"
</code>```

Query 2:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Some clustering keys are missing: time_stamp"
</code>```

Query 3:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND time_stamp = 1581946832 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Non PRIMARY KEY columns found in where clause: id "
</code>```

Any suggestions.

答:
In the 3 queries provided, you are treating the column id as if it was part of the primary key; here is a succinct explanation of their characteristic. You may also visit the data model explanations in DS201 of DataStax Academy.

From the query example 2, it looks that fltr may have a low cardinality, which will also be troublesome, please refer to this explanation.

Body:
I created table in Cassandra database name as information_tbl.
query:

CREATE TABLE IF NOT EXISTS Information_tbl (id uuid ,
                                      cam_id varchar,
                                      camzone varchar,
                                      msg varchar,
                                      fltr int,
                                      time_stamp int,
                                      PRIMARY KEY (fltr,time_stamp)
                                      )WITH CLUSTERING ORDER BY (time_stamp DESC);

when I execute update query, it show error :

Query 1:

UPDATE information_tbl SET camzone = 'D' WHERE id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Some partition key parts are missing: fltr"

Query 2:

UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Some clustering keys are missing: time_stamp"

Query 3:

UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND time_stamp = 1581946832 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Non PRIMARY KEY columns found in where clause: id "

Any suggestions.


问:
Python saving file to Wrong path
My intention for the code bellow is to save a file inside a folder. But the file is beeing saved on the folder before the correct one.

How can i modify it so it saves the file to correct folder?

    #Make Selenium check the chatroom name
    chatroom = driver.find_element_by_class_name('_19vo_').text

    #Create a variable of a folder path with chatroom name
    chat_path = 'D:\Drive\Outros\Python\data_save\chats\ ' + chatroom

    #Verify if folder already exists, if not, create it
    Path(chat_path).mkdir(parents=True, exist_ok=True)

    #Save a df.csv to the chatroom folder
    df.to_csv(chat_path +chatroom+' in'+ timestr +' .csv', index=None, header=True, encoding='utf-8-sig')```

答:
Can you try using double \ in your path.</p>

```<code> chat_path = 'D:\\Drive\\Outros\\Python\\data_save\\chats\\ ' + chatroom
</code>```

Title: Python saving file to Wrong path

Body:
Can you try using double \ in your path.

 chat_path = 'D:\\Drive\\Outros\\Python\\data_save\\chats\\ ' + chatroom


问:
There is no option to build solution and open properties of project after retarget to net standard 2.0
Repro

I created new solution with project targeted net 4.6.1 and its test project.

Project was copied from solution created in VS 2017

I have changed <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFramework>netstandard2.0</TargetFramework> for both unit test and library project (<OutputType>Library</OutputType>).

Now I cannot build solution. When I open project properties window I see error:

```<code>An error occurred trying to load the project properties window.  Close the window and try again. Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))
</code>```

答:
Answer

I had to replace:

```<code><Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</code>```

to:

```<code><Project Sdk="Microsoft.NET.Sdk">
</code>```

In my csproj file

Source:
https://arminreiter.com/2017/05/port-net-framework-net-standard/

Body:
Repro

I created new solution with project targeted net 4.6.1 and its test project.

Project was copied from solution created in VS 2017

I have changed <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFramework>netstandard2.0</TargetFramework> for both unit test and library project (<OutputType>Library</OutputType>).

Now I cannot build solution. When I open project properties window I see error:

An error occurred trying to load the project properties window.  Close the window and try again. Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))

Body:
Answer

I had to replace:

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

to:

<Project Sdk="Microsoft.NET.Sdk">

In my csproj file

Source:
https://arminreiter.com/2017/05/port-net-framework-net-standard/


问:
'PBegin' object has no attribute 'windowing' while running beam pipeline
I'm getting the 'PBegin' object has no attribute 'windowing' while running the dataflow job.
I'm calling the connectclass class in pardo function.

I'm trying to connect NOSQL databases from Beam python SDK and running sql to extract data from the table. Then writing output into separate file using another pardo .

```<code>class Connector(beam.DoFn):
    def __init__(self,username,seeds,keyspace,password,datacenter=None):
    self.username = username
    self.password = password
    self.seeds = seeds
    self.keyspace = keyspace
    self.datacenter = datacenter
    super(self.__class__, self).__init__()

    def process(self, element):

    if datacenter:
        load_balancing_policy = DCAwareRoundRobinPolicy(local_dc=self.datacenter)
    auth_provider = PlainTextAuthProvider(username=self.username, password=self.password)
    cluster = Cluster(contact_points=self.seeds,
                      load_balancing_policy=load_balancing_policy,
                      auth_provider=auth_provider)
    session=cluster.connect(self.seeds,self.keyspace,self.username, self.password, self.datacenter)
    rows = session.execute(SQL Query)
    yield rows
</code>```

答:
Just stumbled upon the same issue. Tried to connect to a RDBMS source, but I guess with respect to implementation design, there is no difference between NoSQL and SQL databases.

Other then what Jayadeep Jayaraman suggests, this can imho be achieved by using a ParDo. Actually, using a ParDo for the connection is what beam documentation recommends if the restrictions of doing so is acceptable for your use case:

For bounded (batch) sources, there are currently two options for creating a Beam source:

Use ParDo and GroupByKey.

Use the Source interface and extend the BoundedSource abstract subclass.

ParDo is the recommended option, as implementing a Source can be tricky. See When to use > the Source interface for a list of some use cases where you might want to use a Source > > (such as dynamic work rebalancing).

You do not show how you use your DoFn. For me, it was helpful to keep in mind that a DoFn acts on elements of an already existing PCollection. It is not capable of creating your DoFn from scratch by itself. So to overcome the issue you are mentioning,you might want create a PCollection from memory, containing one element for the query that you use for retreiving data from your source. Then apply your ParDo which reads from your source to this PCollection.

BTW: I came up with one element per partition I want to read from my RDBMS in my Pcollection - so data can be read in parallel from my SQL database.

Solution might look like follows:

```<code>p | beam.Create(["Your Query / source object qualifier goes here"])
  | "Read from Database" >> beam.ParDo(YourConnector())
</code>```

Let me also mention it might be a good idea to use the start_bundle and finish_bundle methods of your DoFn for setting up / tearing down the connection.

Body:
I'm getting the 'PBegin' object has no attribute 'windowing' while running the dataflow job.
I'm calling the connectclass class in pardo function.

I'm trying to connect NOSQL databases from Beam python SDK and running sql to extract data from the table. Then writing output into separate file using another pardo .

class Connector(beam.DoFn):
    def __init__(self,username,seeds,keyspace,password,datacenter=None):
    self.username = username
    self.password = password
    self.seeds = seeds
    self.keyspace = keyspace
    self.datacenter = datacenter
    super(self.__class__, self).__init__()

    def process(self, element):

    if datacenter:
        load_balancing_policy = DCAwareRoundRobinPolicy(local_dc=self.datacenter)
    auth_provider = PlainTextAuthProvider(username=self.username, password=self.password)
    cluster = Cluster(contact_points=self.seeds,
                      load_balancing_policy=load_balancing_policy,
                      auth_provider=auth_provider)
    session=cluster.connect(self.seeds,self.keyspace,self.username, self.password, self.datacenter)
    rows = session.execute(SQL Query)
    yield rows

Body:
Just stumbled upon the same issue. Tried to connect to a RDBMS source, but I guess with respect to implementation design, there is no difference between NoSQL and SQL databases.

Other then what Jayadeep Jayaraman suggests, this can imho be achieved by using a ParDo. Actually, using a ParDo for the connection is what beam documentation recommends if the restrictions of doing so is acceptable for your use case:

For bounded (batch) sources, there are currently two options for creating a Beam source:

Use ParDo and GroupByKey.

Use the Source interface and extend the BoundedSource abstract subclass.

ParDo is the recommended option, as implementing a Source can be tricky. See When to use > the Source interface for a list of some use cases where you might want to use a Source > > (such as dynamic work rebalancing).

You do not show how you use your DoFn. For me, it was helpful to keep in mind that a DoFn acts on elements of an already existing PCollection. It is not capable of creating your DoFn from scratch by itself. So to overcome the issue you are mentioning,you might want create a PCollection from memory, containing one element for the query that you use for retreiving data from your source. Then apply your ParDo which reads from your source to this PCollection.

BTW: I came up with one element per partition I want to read from my RDBMS in my Pcollection - so data can be read in parallel from my SQL database.

Solution might look like follows:

p | beam.Create(["Your Query / source object qualifier goes here"])
  | "Read from Database" >> beam.ParDo(YourConnector())

Let me also mention it might be a good idea to use the start_bundle and finish_bundle methods of your DoFn for setting up / tearing down the connection.


问:
Bigquery: STRUCT (*) syntax
How can I automatically apply STRUCT to all fields in a table without specifying them by name?

Example that does not work:

```<code>WITH data as (
 SELECT 'Alex' as name, 14 as age, 'something else 1' other_field
UNION ALL
 SELECT 'Bert' as name, 14 as age, 'something else 2' other_field
UNION ALL
 SELECT 'Chiara' as name, 13 as age, 'something else 3' other_field
)

SELECT AS STRUCT(SELECT * except (other_field) from data) as student_data
</code>```

Returns: Error: Scalar subquery cannot have more than one column unless using SELECT AS STRUCT to build STRUCT values at [9:17]

This however works:

```<code>WITH data as (
 SELECT 'Alex' as name, 14 as age, 'something else 1' other_field
UNION ALL
 SELECT 'Bert' as name, 14 as age, 'something else 2' other_field
UNION ALL
 SELECT 'Chiara' as name, 13 as age, 'something else 3' other_field
)

SELECT STRUCT(name,age) as student_data

from data
</code>```

The problem is that once I have 100 columns where only 5 don't belong, it makes me crazy to write them out. Is there a simpler way to use some version of Select * Except()?

答:
Below for BigQuery Standard SQL    </p>

```<code>#standardSQL
WITH data AS (
  SELECT 'Alex' AS name, 14 AS age, 'something else 1' other_field UNION ALL
  SELECT 'Bert' AS name, 14 AS age, 'something else 2' other_field UNION ALL
  SELECT 'Chiara' AS name, 13 AS age, 'something else 3' other_field
)
SELECT (
  SELECT AS STRUCT * EXCEPT(other_field)
  FROM UNNEST([t])
  ) AS student_data
FROM data t
</code>```

<p>with output      </p>

```<code>Row student_data.name   student_data.age
1   Alex                14
2   Bert                14
3   Chiara              13
</code>```

Title: Bigquery: STRUCT (*) syntax

Body:
How can I automatically apply STRUCT to all fields in a table without specifying them by name?

Example that does not work:

WITH data as (
 SELECT 'Alex' as name, 14 as age, 'something else 1' other_field
UNION ALL
 SELECT 'Bert' as name, 14 as age, 'something else 2' other_field
UNION ALL
 SELECT 'Chiara' as name, 13 as age, 'something else 3' other_field
)

SELECT AS STRUCT(SELECT * except (other_field) from data) as student_data

Returns: Error: Scalar subquery cannot have more than one column unless using SELECT AS STRUCT to build STRUCT values at [9:17]

This however works:

WITH data as (
 SELECT 'Alex' as name, 14 as age, 'something else 1' other_field
UNION ALL
 SELECT 'Bert' as name, 14 as age, 'something else 2' other_field
UNION ALL
 SELECT 'Chiara' as name, 13 as age, 'something else 3' other_field
)

SELECT STRUCT(name,age) as student_data

from data

The problem is that once I have 100 columns where only 5 don't belong, it makes me crazy to write them out. Is there a simpler way to use some version of Select * Except()?

Body:
Below for BigQuery Standard SQL

#standardSQL
WITH data AS (
  SELECT 'Alex' AS name, 14 AS age, 'something else 1' other_field UNION ALL
  SELECT 'Bert' AS name, 14 AS age, 'something else 2' other_field UNION ALL
  SELECT 'Chiara' AS name, 13 AS age, 'something else 3' other_field
)
SELECT (
  SELECT AS STRUCT * EXCEPT(other_field)
  FROM UNNEST([t])
  ) AS student_data
FROM data t

with output

Row student_data.name   student_data.age
1   Alex                14
2   Bert                14
3   Chiara              13


问:
SQL query to calculate the sum of values in column, where column name has comma in it
How to calculate the sum of values in a column using SQL query, wherein the column name has comma in it?
Below is a sample table:

```<code>Saint Petersburg, Russia
7.34
29.35
4.4
</code>```

Output required== SUM(7.34+29.35+4.4)
Thanks

答:
Is this what you want?

```<code>select sum([Saint Petersburg, Russia])
from t;
</code>```

You need to escape the column name and the traditional escape method in SQL Server uses square braces.  Double quotes can also be used.

If the issue is that 'Saint Petersburg, Russia' is a potential value in a character column you want to sum, then use try_convert():

```<code>select sum(try_convert(numeric(20, 4), col)
from t;
</code>```

Body:
How to calculate the sum of values in a column using SQL query, wherein the column name has comma in it?
Below is a sample table:

Saint Petersburg, Russia
7.34
29.35
4.4

Output required== SUM(7.34+29.35+4.4)
Thanks

Body:
Is this what you want?

select sum([Saint Petersburg, Russia])
from t;

You need to escape the column name and the traditional escape method in SQL Server uses square braces.  Double quotes can also be used.

If the issue is that 'Saint Petersburg, Russia' is a potential value in a character column you want to sum, then use try_convert():

select sum(try_convert(numeric(20, 4), col)
from t;


问:
Javascript to remove an object from an array if one element in the object contains a string
I have an array of objects such as:

```<code>{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}
</code>```

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)

答:
You can use the filter method, which will keep each item where a specific condition results to true.

In your case, the condition can be a simple includes method to check for the presence of the "Contact request" string.

```<code>var d = {
  "value": [
    {
      "attachment_text": "Support: hello there! I need some help syncing records",
      "ticket_text": "Ticket 1537 from ronburgundy@news.com"
    },
    {
      "attachment_text": "Copied from original request - 401 unathorized",
      "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1173 from sophia@copolla.com"
    },
    {
      "attachment_text": "Hello, we need to troubleshoot some problems",
      "ticket_text": "Ticket 1591 from pat@pending.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1483 from bugs@bunny.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1393 from elmer@fudd.com"
    }
  ]
}

// result contains what you desires
var result = d.value.filter((d) => !d["attachment_text"].includes("Contact request"))
</code>```

Body:
I have an array of objects such as:

{
    "value": [
        {
            "attachment_text": "Support: hello there! I need some help syncing records",
            "ticket_text": "Ticket 1537 from ronburgundy@news.com"
        },
        {
            "attachment_text": "Copied from original request - 401 unathorized",
            "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1173 from sophia@copolla.com"
        },
        {
            "attachment_text": "Hello, we need to troubleshoot some problems",
            "ticket_text": "Ticket 1591 from pat@pending.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1483 from bugs@bunny.com"
        },
        {
            "attachment_text": "Contact request form received",
            "ticket_text": "Ticket 1393 from elmer@fudd.com"
        }
    ]
}

What javascript can I use to remove any objects where the attachment_text field contains the string "Contact request"?

Preferably pure javascript (i.e. not a library such as lodash)

Body:
You can use the filter method, which will keep each item where a specific condition results to true.

In your case, the condition can be a simple includes method to check for the presence of the "Contact request" string.

var d = {
  "value": [
    {
      "attachment_text": "Support: hello there! I need some help syncing records",
      "ticket_text": "Ticket 1537 from ronburgundy@news.com"
    },
    {
      "attachment_text": "Copied from original request - 401 unathorized",
      "ticket_text": "Ticket 1459 from klaus.kinsky@kinsky.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1173 from sophia@copolla.com"
    },
    {
      "attachment_text": "Hello, we need to troubleshoot some problems",
      "ticket_text": "Ticket 1591 from pat@pending.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1483 from bugs@bunny.com"
    },
    {
      "attachment_text": "Contact request form received",
      "ticket_text": "Ticket 1393 from elmer@fudd.com"
    }
  ]
}

// result contains what you desires
var result = d.value.filter((d) => !d["attachment_text"].includes("Contact request"))


问:
What should I replace deprecated Facebook InterstitialAd setAdListener?
As of v5.6.1 the interstitialAd.setAdListener is deprecated. What should I replace deprecated Facebook InterstitialAd setAdListener now ?</p>

答:
From https://developers.facebook.com/docs/audience-network/reference/android/com/facebook/ads/interstitialad.html/?version=v5.6.1 it says

Deprecated. since 5.6, use loadAd(InterstitialAd.InterstitialLoadAdConfig)

This config you can get by calling buildLoadAdConfig() and there you can do withAdListener(InterstitialAdListener adListener) on.


问:
getting segmentation fault(core dump)after typing all the value in a vector in c++
i have made this code to print a string and int.

```<code> vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);
</code>```

the programme runs and starts taking value but as i put anything other than int to stop the

```<code>for(int v;cin>>v;)
</code>```

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

```<code>void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}
</code>```

答:
In the loop

```<code>for(int i=0;i<y;i++) {
    cout<<a[i]<<" "<<b[i]<<"\n";
}
</code>```

if one of the indexes is out_of _range there will be an out_of_range exception thrown, witch is bound to happen since you use the size of vector b to print vector a, because you are not catching this exception, the program will crash.

Use foreach loops to avoid this:

Use foreach loop to avoid this, for instance:

```<code>vector<int> a;
for(int i : a){
  cout << a;
}
</code>```

Body:
i have made this code to print a string and int.

 vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);

the programme runs and starts taking value but as i put anything other than int to stop the

for(int v;cin>>v;)

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}

Body:
In the loop

for(int i=0;i<y;i++) {
    cout<<a[i]<<" "<<b[i]<<"\n";
}

if one of the indexes is out_of _range there will be an out_of_range exception thrown, witch is bound to happen since you use the size of vector b to print vector a, because you are not catching this exception, the program will crash.

Use foreach loops to avoid this:

Use foreach loop to avoid this, for instance:

vector<int> a;
for(int i : a){
  cout << a;
}


答:
You need an expression for the AS STRUCT expr

```<code>SELECT AS STRUCT data.* except (other_field) from data
</code>```

Title: Bigquery: STRUCT (*) syntax

Body:
You need an expression for the AS STRUCT expr

SELECT AS STRUCT data.* except (other_field) from data


问:
DataGridView Paint Event not drawing cell borders when scrolling from bottom to top
Using C# WinForms, I have a docked (Fill) a standard DataGridView control on my form.  The DataGridView columns and rows are created once, programaticallly, when the form is loads.  I paint some header and cell borders in the Paint event.  All is good.

The problem I have is scrolling.  When I scroll down, everything paints fine.  However, when I scroll back up, some of the borders are not painted.  When the unpainted area is displayed on screen, and I scroll back down again while still keeping the unpainted area on screen, it repaints fine.  I am battling to see anything strange when debugging because it happens completely random; one row could not be painted now, and next time round it could be a different border. "I know it paints fine" because when I scroll down right to the bottom, all the way down, everything is painted as it should.  It is only when I scroll back up that random rows are not painted, and it could be different rows each time.

As you will see in the code below, I am setting the borders that I don't want painted to transparent.  Even if I set the unpainted borders with to 0 and set the border style to none, it yields the same result.

Is this a GUI bug or a refresh bug or what?

As per example, I have scrolled down all the way, and on the way down I have seen that all the borders paint fine.  I can redo it over and over with the same result, as below.

Then when I scroll back up, some borders are not painted, randomly, as you can see on the grid line with text 20:00; the row "20:00" should look the same as row "21:00", as can be seen below.

The code I am using to paint is:

```<code>    /// <summary>data grid view cell painting event : to draw custom cell borders</summary>
    private void dgv_cell_painting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        try
        {
            int row = e.RowIndex;

            int column = e.ColumnIndex;

            int last_col = data_grid_appointments.ColumnCount - 1;

            int last_row = data_grid_appointments.RowCount - 1;

            string row_tag = ((DataGridView)sender).Rows[row].Tag.ToString();

            bool is_hour = (string.IsNullOrEmpty(row_tag) ? false : row_tag.EndsWith("00"));

            switch (row < last_row)
            {
                case true:  //not the last row

                    switch (row == 0
                            ||
                            is_hour)
                    {
                        case true:  //first row or row is on the hour

                            switch (column == -1)
                            {
                                case true:

                                    e.PaintBackground(e.CellBounds, true);
                                    e.PaintContent(e.CellBounds);

                                    ControlPaint.DrawBorder
                                    (
                                          e.Graphics
                                        , e.CellBounds
                                        , Color.Transparent, 1, ButtonBorderStyle.Solid
                                        , Color.Orange, 1, ButtonBorderStyle.Solid
                                        , Color.Orange, 1, ButtonBorderStyle.Solid
                                        , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    );

                                    e.Graphics.DrawString
                                    (
                                          row_tag.Substring(0, 2) + ":" + row_tag.Substring(2)
                                        , e.CellStyle.Font
                                        , new SolidBrush(Color.Black)
                                        , e.CellBounds
                                        , new StringFormat()
                                            {
                                                Alignment = StringAlignment.Center
                                                    ,
                                                FormatFlags = StringFormatFlags.NoWrap
                                                    ,
                                                LineAlignment = StringAlignment.Center
                                            }
                                    );

                                    e.Handled = true;

                                    break;

                                default:

                                    switch (column == data_grid_appointments.ColumnCount - 1)
                                    {
                                        case true:

                                            e.PaintBackground(e.CellBounds, true);
                                            e.PaintContent(e.CellBounds);

                                            ControlPaint.DrawBorder
                                            (
                                                  e.Graphics
                                                , e.CellBounds
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                            );

                                            e.Handled = true;

                                            break;

                                        default:

                                            e.PaintBackground(e.CellBounds, true);
                                            e.PaintContent(e.CellBounds);

                                            ControlPaint.DrawBorder
                                            (
                                                  e.Graphics
                                                , e.CellBounds
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                            );

                                            e.Handled = true;

                                            break;
                                    }

                                    break;
                            }

                            break;

                        default:    //not the first column

                            if (column == -1
                                ||
                                column == data_grid_appointments.ColumnCount - 1)
                            {
                                e.PaintBackground(e.CellBounds, true);
                                e.PaintContent(e.CellBounds);

                                ControlPaint.DrawBorder
                                (
                                      e.Graphics
                                    , e.CellBounds
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    , Color.Orange, 1, ButtonBorderStyle.Solid
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                );

                                e.Handled = true;
                            }

                            break;
                    }

                    break;

                default:    //last row

                    switch (column == -1
                            ||
                            column == last_col)
                    {
                        case true:    //row header column OR very last column in the very last row

                            e.PaintBackground(e.CellBounds, true);
                            e.PaintContent(e.CellBounds);

                            ControlPaint.DrawBorder
                            (
                                  e.Graphics
                                , e.CellBounds
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                            );

                            e.Handled = true;

                            break;

                        default:    //not the header column

                            e.PaintBackground(e.CellBounds, true);
                            e.PaintContent(e.CellBounds);

                            ControlPaint.DrawBorder
                            (
                                  e.Graphics
                                , e.CellBounds
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                            );

                            e.Handled = true;

                            break;
                    }

                    break;
            }
        }

        catch (Exception ex)
        {}
    }
</code>```

答:
So after many different approaches and playing around, I have managed to get the borders to draw consistently using the code I originally posted in my question. I noticed that, when scrolling using the scrollbar and not the mouse, I got the same result. I added the code below, and it works, all the lines are drawn and are consistently displayed.</p>

```<code>private void data_grid_appointments_scroll(object sender, ScrollEventArgs e)
{
    ((DataGridView)sender).Invalidate();
}
</code>```

Body:
Using C# WinForms, I have a docked (Fill) a standard DataGridView control on my form.  The DataGridView columns and rows are created once, programaticallly, when the form is loads.  I paint some header and cell borders in the Paint event.  All is good.

The problem I have is scrolling.  When I scroll down, everything paints fine.  However, when I scroll back up, some of the borders are not painted.  When the unpainted area is displayed on screen, and I scroll back down again while still keeping the unpainted area on screen, it repaints fine.  I am battling to see anything strange when debugging because it happens completely random; one row could not be painted now, and next time round it could be a different border. "I know it paints fine" because when I scroll down right to the bottom, all the way down, everything is painted as it should.  It is only when I scroll back up that random rows are not painted, and it could be different rows each time.

As you will see in the code below, I am setting the borders that I don't want painted to transparent.  Even if I set the unpainted borders with to 0 and set the border style to none, it yields the same result.

Is this a GUI bug or a refresh bug or what?

As per example, I have scrolled down all the way, and on the way down I have seen that all the borders paint fine.  I can redo it over and over with the same result, as below.

Then when I scroll back up, some borders are not painted, randomly, as you can see on the grid line with text 20:00; the row "20:00" should look the same as row "21:00", as can be seen below.

The code I am using to paint is:

    /// data grid view cell painting event : to draw custom cell borders
    private void dgv_cell_painting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        try
        {
            int row = e.RowIndex;

            int column = e.ColumnIndex;

            int last_col = data_grid_appointments.ColumnCount - 1;

            int last_row = data_grid_appointments.RowCount - 1;

            string row_tag = ((DataGridView)sender).Rows[row].Tag.ToString();

            bool is_hour = (string.IsNullOrEmpty(row_tag) ? false : row_tag.EndsWith("00"));

            switch (row < last_row)
            {
                case true:  //not the last row

                    switch (row == 0
                            ||
                            is_hour)
                    {
                        case true:  //first row or row is on the hour

                            switch (column == -1)
                            {
                                case true:

                                    e.PaintBackground(e.CellBounds, true);
                                    e.PaintContent(e.CellBounds);

                                    ControlPaint.DrawBorder
                                    (
                                          e.Graphics
                                        , e.CellBounds
                                        , Color.Transparent, 1, ButtonBorderStyle.Solid
                                        , Color.Orange, 1, ButtonBorderStyle.Solid
                                        , Color.Orange, 1, ButtonBorderStyle.Solid
                                        , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    );

                                    e.Graphics.DrawString
                                    (
                                          row_tag.Substring(0, 2) + ":" + row_tag.Substring(2)
                                        , e.CellStyle.Font
                                        , new SolidBrush(Color.Black)
                                        , e.CellBounds
                                        , new StringFormat()
                                            {
                                                Alignment = StringAlignment.Center
                                                    ,
                                                FormatFlags = StringFormatFlags.NoWrap
                                                    ,
                                                LineAlignment = StringAlignment.Center
                                            }
                                    );

                                    e.Handled = true;

                                    break;

                                default:

                                    switch (column == data_grid_appointments.ColumnCount - 1)
                                    {
                                        case true:

                                            e.PaintBackground(e.CellBounds, true);
                                            e.PaintContent(e.CellBounds);

                                            ControlPaint.DrawBorder
                                            (
                                                  e.Graphics
                                                , e.CellBounds
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                            );

                                            e.Handled = true;

                                            break;

                                        default:

                                            e.PaintBackground(e.CellBounds, true);
                                            e.PaintContent(e.CellBounds);

                                            ControlPaint.DrawBorder
                                            (
                                                  e.Graphics
                                                , e.CellBounds
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                            );

                                            e.Handled = true;

                                            break;
                                    }

                                    break;
                            }

                            break;

                        default:    //not the first column

                            if (column == -1
                                ||
                                column == data_grid_appointments.ColumnCount - 1)
                            {
                                e.PaintBackground(e.CellBounds, true);
                                e.PaintContent(e.CellBounds);

                                ControlPaint.DrawBorder
                                (
                                      e.Graphics
                                    , e.CellBounds
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                    , Color.Orange, 1, ButtonBorderStyle.Solid
                                    , Color.Transparent, 1, ButtonBorderStyle.Solid
                                );

                                e.Handled = true;
                            }

                            break;
                    }

                    break;

                default:    //last row

                    switch (column == -1
                            ||
                            column == last_col)
                    {
                        case true:    //row header column OR very last column in the very last row

                            e.PaintBackground(e.CellBounds, true);
                            e.PaintContent(e.CellBounds);

                            ControlPaint.DrawBorder
                            (
                                  e.Graphics
                                , e.CellBounds
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                            );

                            e.Handled = true;

                            break;

                        default:    //not the header column

                            e.PaintBackground(e.CellBounds, true);
                            e.PaintContent(e.CellBounds);

                            ControlPaint.DrawBorder
                            (
                                  e.Graphics
                                , e.CellBounds
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Transparent, 1, ButtonBorderStyle.Solid
                                , Color.Orange, 1, ButtonBorderStyle.Solid
                            );

                            e.Handled = true;

                            break;
                    }

                    break;
            }
        }

        catch (Exception ex)
        {}
    }

Body:
So after many different approaches and playing around, I have managed to get the borders to draw consistently using the code I originally posted in my question. I noticed that, when scrolling using the scrollbar and not the mouse, I got the same result. I added the code below, and it works, all the lines are drawn and are consistently displayed.

private void data_grid_appointments_scroll(object sender, ScrollEventArgs e)
{
    ((DataGridView)sender).Invalidate();
}


问:
list the file and its base directory
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

```<code>pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls
</code>```

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

```<code>/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls
</code>```

答:
Takes into account spaces in file names, potential case of extension

```<code>for a in {*.pdf,*.doc,*.xls}; do find /home/sample/ -type f -iname "$a" -exec basename {} \; ; done
</code>```

EDIT
Edited to take into account only files

Title: list the file and its base directory

Body:
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls

Body:
Takes into account spaces in file names, potential case of extension

for a in {*.pdf,*.doc,*.xls}; do find /home/sample/ -type f -iname "$a" -exec basename {} \; ; done

EDIT
Edited to take into account only files