问:
Multi Level drop-down in ReactJS
I'm trying to implement multilevel nested drop-down. I have made use of "react-dropdown". A new dropdown that appears so be displayed just below. But I'm unable to implement nested dropdown.

what to achieve something like this

this is my output

```<code>import React from "react";
import Dropdown from "react-dropdown";
import 'react-dropdown/style.css';

const object = [
    {value: 'course',
    lable: "course" ,
    submenu: [
        { value: "PCF8883US/7EA/1Y", lable: "PCF8883US/7EA/1Y"},
        { value: "AT42QT1050-UUR", lable: "AT42QT1050-UUR" },
        { value: "PCF8883", lable: "PCF8883"}
        ]
    },
    {value: "code",
    lable:"code",
    submenu: [
        { value: "MC3672", lable: "MC3672"},
        { value: "MXC400XXC", lable: "MXC400XXC"}
        ]
    }
]

const course = [
    { value: "PCF8883US/7EA/1Y", lable: "PCF8883US/7EA/1Y"},
    { value: "AT42QT1050-UUR", lable: "AT42QT1050-UUR" },
    { value: "PCF8883", lable: "PCF8883"}
]

const code = [
    { value: "MC3672", lable: "MC3672"},
    { value: "MXC400XXC", lable: "MXC400XXC"}
]

export class WorkSpace extends React.Component {
    render() {
        return (
            <div className="base_container">
                <div className="left">
                    <h3>Select Component</h3>
                    <div>
                    <Dropdown options={object} placeholder="Name">
                        <Dropdown options={course} onChange={this._onSelect} placeholder="course" />
                        <Dropdown options={code} onChange={this._onSelect} placeholder="code"/>
                    </Dropdown>
                    </div>
                </div>
            </div>
        );
    }
}
</code>```

答: You could try the library React Treebeard. It gives a UI almost exactly like your example.

Title: Multi Level drop-down in ReactJS

Body:
I'm trying to implement multilevel nested drop-down. I have made use of "react-dropdown". A new dropdown that appears so be displayed just below. But I'm unable to implement nested dropdown.

what to achieve something like this

this is my output

import React from "react";
import Dropdown from "react-dropdown";
import 'react-dropdown/style.css';

const object = [
    {value: 'course',
    lable: "course" ,
    submenu: [
        { value: "PCF8883US/7EA/1Y", lable: "PCF8883US/7EA/1Y"},
        { value: "AT42QT1050-UUR", lable: "AT42QT1050-UUR" },
        { value: "PCF8883", lable: "PCF8883"}
        ]
    },
    {value: "code",
    lable:"code",
    submenu: [
        { value: "MC3672", lable: "MC3672"},
        { value: "MXC400XXC", lable: "MXC400XXC"}
        ]
    }
]

const course = [
    { value: "PCF8883US/7EA/1Y", lable: "PCF8883US/7EA/1Y"},
    { value: "AT42QT1050-UUR", lable: "AT42QT1050-UUR" },
    { value: "PCF8883", lable: "PCF8883"}
]

const code = [
    { value: "MC3672", lable: "MC3672"},
    { value: "MXC400XXC", lable: "MXC400XXC"}
]

export class WorkSpace extends React.Component {
    render() {
        return (

Select Component

                    <Dropdown options={object} placeholder="Name">
                        <Dropdown options={course} onChange={this._onSelect} placeholder="course" />
                        <Dropdown options={code} onChange={this._onSelect} placeholder="code"/>
                    </Dropdown>

        );
    }
}


来源: stackexchange

问:
how to revert my app to a specific commit I made to github
I have done some stuff to my git repo and I think I am digging the hole deeper.

Right now I just want to be able to get all my current files in the state they were when I last pushed to github.  However, I do not have internet connection on that machine.  So what do I do? I do have git internally and git log shows that the commit I want starts with
c3e535f8cb.....

I just want to revert my whole directory to that commit. is this doable with git?

right now I have nothing to commit

git status shows

```<code># on branch master
# your branch is ahead of 'origin/master' by 3 commits
#  nothing to commit (working directory clean)
</code>```

答:
I strongly recommend that you do a dry-run with the --soft option to make sure that you get the desired results.

If you don't have pushed the new changes upstream, you could easily fetch the upstream changes again, and then do a reset which suits better.

I hope that you made it through successfully with the goals that you set out to accomplish :)

ContentLicense: CC BY-SA 3.0

Body:
I have done some stuff to my git repo and I think I am digging the hole deeper.

Right now I just want to be able to get all my current files in the state they were when I last pushed to github.  However, I do not have internet connection on that machine.  So what do I do? I do have git internally and git log shows that the commit I want starts with
c3e535f8cb.....

I just want to revert my whole directory to that commit. is this doable with git?

right now I have nothing to commit

git status shows

# on branch master
# your branch is ahead of 'origin/master' by 3 commits
#  nothing to commit (working directory clean)


问:
type parameter t has incompatible upper bounds: view and fragment
I like to get my fragment of my Activity, but i got the error:

type parameter t has incompatible upper bounds: view and fragment

by findViewById(R.id.f_instruction) in my MainActivity.
I hope you can help me.

My Activity:

```<code>public class MainActivity extends AppCompatActivity {
Fragment f_instruction;
public static void closeFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f_instruction = findViewById(R.id.f_instruction);
}
</code>```

}

XML of Activity:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/f_instruction"
        android:name="e.marco.gymdiary.first_fragment"
        android:layout_width="410dp"
        android:layout_height="732dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

答:
I had the same problem. this helped me fix the problem:

Go to your "activity_main.xml"

Right-click -> Refactor -> Rename (or use SHIFT + F6)

Rename your layout to "activity_main2.xml" for example

Rename this file back to the original "activity_main.xml"

ContentLicense: CC BY-SA 4.0

Body:
I like to get my fragment of my Activity, but i got the error:

type parameter t has incompatible upper bounds: view and fragment

by findViewById(R.id.f_instruction) in my MainActivity.
I hope you can help me.

My Activity:

public class MainActivity extends AppCompatActivity {
Fragment f_instruction;
public static void closeFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f_instruction = findViewById(R.id.f_instruction);
}

}

XML of Activity:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/f_instruction"
        android:name="e.marco.gymdiary.first_fragment"
        android:layout_width="410dp"
        android:layout_height="732dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Regex Match containing string between 2 characters
I'm trying to match a string in an HTTP page between ><.

I'm having trouble with the first > as it also matches subsequent chars. eg. in this example

```<code><a href="https://stackoverflow.com" class="-logo js-gps-track"
                        data-gps-track="top_nav.click({is_current:false, location:3, destination:8})">
                        <span class="-img _glyph">Stack Overflow</span>
                    </a>
</code>```

I would only want to match Stack Overflow. I've currently got \>([^\>].*Stack Overflow.*)\<
but that matches everything after the first > ie

```<code>><span class="-img _glyph">Stack Overflow<
</code>```

Any help would be great

答:
It'd probably be more elegant to use DOMParser, and take the textContent of .-img._glyph:

const str = `
                        Stack Overflow
                    `;
console.log(
  new DOMParser().parseFromString(str, 'text/html').querySelector('.-img._glyph').textContent
);```

If you had to use regex, instead of repeating . (which matches anything), repeat [^<>] (which matches anything which isn't a < or >) on either side of the Stack Overflow part, while looking ahead and behind for < and >:

(?<=>)[^<>]*Stack Overflow[^<>]*(?=<)

(If you can't use lookbehind, match the initial > and capture everything afterwards, then extract the capture group)

Body:
I'm trying to match a string in an HTTP page between ><.

I'm having trouble with the first > as it also matches subsequent chars. eg. in this example

                        Stack Overflow

I would only want to match Stack Overflow. I've currently got \>([^\>].*Stack Overflow.*)\<
but that matches everything after the first > ie

>Stack Overflow<

Any help would be great

Body:
It'd probably be more elegant to use DOMParser, and take the textContent of .-img._glyph:

const str = `<a href="https://stackoverflow.com" class="-logo js-gps-track"
                        data-gps-track="top_nav.click({is_current:false, location:3, destination:8})">
                        <span class="-img _glyph">Stack Overflow</span>
                    </a>`;
console.log(
  new DOMParser().parseFromString(str, 'text/html').querySelector('.-img._glyph').textContent
);

If you had to use regex, instead of repeating . (which matches anything), repeat [^<>] (which matches anything which isn't a < or >) on either side of the Stack Overflow part, while looking ahead and behind for < and >:

(?<=>)[^<>]*Stack Overflow[^<>]*(?=<)

(If you can't use lookbehind, match the initial > and capture everything afterwards, then extract the capture group)


问:
Is it possible to access/update the child thread's resource from parent thread?
I'm doing a socket programming in C and I'm completely new to Multithreading.

This is my scenario, I need a parent thread which reads the data from socket(lets say..) and enqueue the same to the queue of its child thread.The problem here is, how can I update the queue which is child thread-specific from the parent thread.

答:
Thread-safe queue that supports multiple producers and consumers.

MtQueue.h:

#ifndef MtQueue_H
#define MtQueue_H

#include <pthread.h>
#include <stdlib.h>

// A fixed-size circular buffer.
typedef struct {
   pthread_mutex_t mutex;
   pthread_cond_t cond;
   int done;
   int empty;
   int full;
   size_t max;
   size_t next_insert;
   size_t next_read;
   void** buf;
} MtQueue;

// Returns NULL and sets errno on error.
// Free the queue with MtQueue_delete when done.
MtQueue* MtQueue_new(size_t max);

// Returns 0 and sets errno on error.
// Destroy the queue with MtQueue_destroy when done.
int MtQueue_init(MtQueue* q, size_t max);

// Inverse of MtQueue_new.
// Only call when the queue is no longer in use.
void MtQueue_delete(MtQueue* q);

// Inverse of MtQueue_init.
// Only call when the queue is no longer in use.
void MtQueue_destroy(MtQueue* q);

// Initiates shutdown of the queue.
// You must ensure that no there are no pending call to enqueue before this is called.
// You must ensure not to call enqueue once this is called.
void MtQueue_done(MtQueue* q);

// Returns the oldest item from the queue (via a parameter) and returns 1.
// If the queue is empty and done, returns 0.
// If the queue is empty and not done, waits until that changes.
int MtQueue_dequeue(MtQueue* q, void** pp);

// Adds the argument to the queue.
// If the queue is full, waits until that changes.
void MtQueue_enqueue(MtQueue* q, void* p);

#endif
```
<p><code>MtQueue.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>

#include "MtQueue.h"

MtQueue* MtQueue_new(size_t max) {
   MtQueue* q = malloc(sizeof(MtQueue));
   if (!q)
      goto Error1;

   if (!MtQueue_init(q, max))
      goto Error2;

   return q;

Error2:
   free(q);
Error1:
   return NULL;
}

int MtQueue_init(MtQueue* q, size_t max) {
   void** buf = malloc(sizeof(void*) * max);
   if (!buf)
      goto Error1;

   errno = pthread_mutex_init(&(q->mutex), NULL);
   if (errno)
      goto Error2;

   errno = pthread_cond_init(&(q->cond), NULL);
   if (errno)
      goto Error3;

   q->done = 0;
   q->empty = 1;
   q->full = 0;
   q->max = max;
   q->next_insert = 0;
   q->next_read = 0;
   q->buf = buf;
   return 1;

Error3:
   pthread_mutex_destroy(&(q->mutex));
Error2:
   free(buf);
Error1:
   return 0;
}

void MtQueue_delete(MtQueue* q) {
   MtQueue_destroy(q);
   free(q);
}

void MtQueue_destroy(MtQueue* q) {
   assert(q->empty);
   free(q->buf);
   pthread_cond_destroy(&(q->cond));
   pthread_mutex_destroy(&(q->mutex));
}

void MtQueue_done(MtQueue* q) {
   pthread_mutex_lock(&(q->mutex));
   q->done = 1;
   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
}

int MtQueue_dequeue(MtQueue* q, void** pp) {
   pthread_mutex_lock(&(q->mutex));
   while (q->empty && !q->done)
      pthread_cond_wait(&(q->cond), &(q->mutex));

   int dequeued;
   if (q->empty) {
      // q->done && q->empty is true.
      // We are completely done.
      dequeued = 0;
   } else {
      *pp = q->buf[ q->next_read ];
      q->next_read = ( q->next_read + 1 ) % q->max;
      q->empty = q->next_read == q->next_insert;
      q->full = 0;
      dequeued = 1;
   }

   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
   return dequeued;
}

void MtQueue_enqueue(MtQueue* q, void* p) {
   pthread_mutex_lock(&(q->mutex));
   while (q->full)
      pthread_cond_wait(&(q->cond), &(q->mutex));

   assert(!q->done);

   q->buf[q->next_insert] = p;
   q->next_insert = ( q->next_insert + 1 ) % q->max;
   q->empty = 0;
   q->full = q->next_insert == q->next_read;

   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
}
</code>```

a.c (Example user):

#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "MtQueue.h"

// Producers will block if there are this many items in the queue.
#ifndef QUEUE_SIZE
#define QUEUE_SIZE 10
#endif

// The number of consumers (worker threads) to create.
#ifndef NUM_WORKERS
#define NUM_WORKERS 4
#endif

// The amount of work to generate for this test.
#ifndef NUM_JOBS
#define NUM_JOBS 40
#endif

// Simulate work using a sleep.
#ifndef SIM_WORK
#define SIM_WORK 0
#endif

#if SIM_WORK
static int msleep(long msec) {
   struct timespec ts;
   int res;

   if (msec < 0) {
       errno = EINVAL;
       return -1;
   }

   ts.tv_sec = msec / 1000;
   ts.tv_nsec = (msec % 1000) * 1000000;

    do {
       res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}
#endif

// Shared variables.
static MtQueue q;

static void* worker_func(void* worker_id_) {
   uintptr_t worker_id = (uintptr_t)worker_id_;

#if SIM_WORK
   unsigned int seed = worker_id;  // Whatever.
#endif

   uintptr_t j;
   while (MtQueue_dequeue(&q, (void**)&j)) {
      printf("[%" PRIuPTR "] Dequeued %" PRIuPTR "\n", worker_id, j);
#if SIM_WORK
      msleep( rand_r(&seed) % 1000 + 1000 );  // Simulate a 1 to 2s load.
#endif
      printf("[%" PRIuPTR "]    Finished processing %" PRIuPTR "\n", worker_id, j);
   }

   return NULL;
}

int main(void) {
   MtQueue_init(&q, QUEUE_SIZE);

   pthread_t workers[NUM_WORKERS];
   for (uintptr_t w=0; w<NUM_WORKERS; ++w) {
      if (errno = pthread_create(&(workers[w]), NULL, worker_func, (void*)w)) {
         perror(NULL);
         exit(1);
      }
   }

   for (uintptr_t j=0; j<NUM_JOBS; ++j) {
      printf("[x] Enqueuing %" PRIuPTR "...\n", j);
      MtQueue_enqueue(&q, (void*)j);
      printf("[x]    Enqueued %" PRIuPTR ".\n", j);
   }

   MtQueue_done(&q);
   printf("[x] Called done.\n");

   for (uintptr_t w=0; w<NUM_WORKERS; ++w)
      pthread_join(workers[w], NULL);

   MtQueue_destroy(&q);
   return 0;
}
```
<p>How to run example user:</p>
<pre class="lang-sh prettyprint-override"><code>gcc -Wall -Wextra -pedantic a.c MtQueue.c -o a -lpthread && ./a
</code>```

gcc -D SIM_WORK=1 -D NUM_JOBS=20 -Wall -Wextra -pedantic a.c MtQueue.c -o a -pthread && ./a
```

Body:
Thread-safe queue that supports multiple producers and consumers.

MtQueue.h:

#ifndef MtQueue_H
#define MtQueue_H

#include <pthread.h>
#include <stdlib.h>

// A fixed-size circular buffer.
typedef struct {
   pthread_mutex_t mutex;
   pthread_cond_t cond;
   int done;
   int empty;
   int full;
   size_t max;
   size_t next_insert;
   size_t next_read;
   void** buf;
} MtQueue;

// Returns NULL and sets errno on error.
// Free the queue with MtQueue_delete when done.
MtQueue* MtQueue_new(size_t max);

// Returns 0 and sets errno on error.
// Destroy the queue with MtQueue_destroy when done.
int MtQueue_init(MtQueue* q, size_t max);

// Inverse of MtQueue_new.
// Only call when the queue is no longer in use.
void MtQueue_delete(MtQueue* q);

// Inverse of MtQueue_init.
// Only call when the queue is no longer in use.
void MtQueue_destroy(MtQueue* q);

// Initiates shutdown of the queue.
// You must ensure that no there are no pending call to enqueue before this is called.
// You must ensure not to call enqueue once this is called.
void MtQueue_done(MtQueue* q);

// Returns the oldest item from the queue (via a parameter) and returns 1.
// If the queue is empty and done, returns 0.
// If the queue is empty and not done, waits until that changes.
int MtQueue_dequeue(MtQueue* q, void** pp);

// Adds the argument to the queue.
// If the queue is full, waits until that changes.
void MtQueue_enqueue(MtQueue* q, void* p);

#endif

MtQueue.c:

#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>

#include "MtQueue.h"

MtQueue* MtQueue_new(size_t max) {
   MtQueue* q = malloc(sizeof(MtQueue));
   if (!q)
      goto Error1;

   if (!MtQueue_init(q, max))
      goto Error2;

   return q;

Error2:
   free(q);
Error1:
   return NULL;
}

int MtQueue_init(MtQueue* q, size_t max) {
   void** buf = malloc(sizeof(void*) * max);
   if (!buf)
      goto Error1;

   errno = pthread_mutex_init(&(q->mutex), NULL);
   if (errno)
      goto Error2;

   errno = pthread_cond_init(&(q->cond), NULL);
   if (errno)
      goto Error3;

   q->done = 0;
   q->empty = 1;
   q->full = 0;
   q->max = max;
   q->next_insert = 0;
   q->next_read = 0;
   q->buf = buf;
   return 1;

Error3:
   pthread_mutex_destroy(&(q->mutex));
Error2:
   free(buf);
Error1:
   return 0;
}

void MtQueue_delete(MtQueue* q) {
   MtQueue_destroy(q);
   free(q);
}

void MtQueue_destroy(MtQueue* q) {
   assert(q->empty);
   free(q->buf);
   pthread_cond_destroy(&(q->cond));
   pthread_mutex_destroy(&(q->mutex));
}

void MtQueue_done(MtQueue* q) {
   pthread_mutex_lock(&(q->mutex));
   q->done = 1;
   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
}

int MtQueue_dequeue(MtQueue* q, void** pp) {
   pthread_mutex_lock(&(q->mutex));
   while (q->empty && !q->done)
      pthread_cond_wait(&(q->cond), &(q->mutex));

   int dequeued;
   if (q->empty) {
      // q->done && q->empty is true.
      // We are completely done.
      dequeued = 0;
   } else {
      *pp = q->buf[ q->next_read ];
      q->next_read = ( q->next_read + 1 ) % q->max;
      q->empty = q->next_read == q->next_insert;
      q->full = 0;
      dequeued = 1;
   }

   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
   return dequeued;
}

void MtQueue_enqueue(MtQueue* q, void* p) {
   pthread_mutex_lock(&(q->mutex));
   while (q->full)
      pthread_cond_wait(&(q->cond), &(q->mutex));

   assert(!q->done);

   q->buf[q->next_insert] = p;
   q->next_insert = ( q->next_insert + 1 ) % q->max;
   q->empty = 0;
   q->full = q->next_insert == q->next_read;

   pthread_cond_signal(&(q->cond));
   pthread_mutex_unlock(&(q->mutex));
}

a.c (Example user):

#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "MtQueue.h"

// Producers will block if there are this many items in the queue.
#ifndef QUEUE_SIZE
#define QUEUE_SIZE 10
#endif

// The number of consumers (worker threads) to create.
#ifndef NUM_WORKERS
#define NUM_WORKERS 4
#endif

// The amount of work to generate for this test.
#ifndef NUM_JOBS
#define NUM_JOBS 40
#endif

// Simulate work using a sleep.
#ifndef SIM_WORK
#define SIM_WORK 0
#endif

#if SIM_WORK
static int msleep(long msec) {
   struct timespec ts;
   int res;

   if (msec < 0) {
       errno = EINVAL;
       return -1;
   }

   ts.tv_sec = msec / 1000;
   ts.tv_nsec = (msec % 1000) * 1000000;

    do {
       res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}
#endif

// Shared variables.
static MtQueue q;

static void* worker_func(void* worker_id_) {
   uintptr_t worker_id = (uintptr_t)worker_id_;

#if SIM_WORK
   unsigned int seed = worker_id;  // Whatever.
#endif

   uintptr_t j;
   while (MtQueue_dequeue(&q, (void**)&j)) {
      printf("[%" PRIuPTR "] Dequeued %" PRIuPTR "\n", worker_id, j);
#if SIM_WORK
      msleep( rand_r(&seed) % 1000 + 1000 );  // Simulate a 1 to 2s load.
#endif
      printf("[%" PRIuPTR "]    Finished processing %" PRIuPTR "\n", worker_id, j);
   }

   return NULL;
}

int main(void) {
   MtQueue_init(&q, QUEUE_SIZE);

   pthread_t workers[NUM_WORKERS];
   for (uintptr_t w=0; w<NUM_WORKERS; ++w) {
      if (errno = pthread_create(&(workers[w]), NULL, worker_func, (void*)w)) {
         perror(NULL);
         exit(1);
      }
   }

   for (uintptr_t j=0; j<NUM_JOBS; ++j) {
      printf("[x] Enqueuing %" PRIuPTR "...\n", j);
      MtQueue_enqueue(&q, (void*)j);
      printf("[x]    Enqueued %" PRIuPTR ".\n", j);
   }

   MtQueue_done(&q);
   printf("[x] Called done.\n");

   for (uintptr_t w=0; w<NUM_WORKERS; ++w)
      pthread_join(workers[w], NULL);

   MtQueue_destroy(&q);
   return 0;
}

How to run example user:

gcc -Wall -Wextra -pedantic a.c MtQueue.c -o a -lpthread && ./a

gcc -D SIM_WORK=1 -D NUM_JOBS=20 -Wall -Wextra -pedantic a.c MtQueue.c -o a -pthread && ./a


问:
If 'C' inherits from 'B' publicly, B inherits from 'A' privately, Why can't I create an object of 'A' inside 'C'?
I'm using Visual C++, If I compile this code:

```<code>class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        A a{};
    }
};
</code>```

I get this error:

error C2247: 'A' not accessible because 'B' uses 'private' to inherit
  from 'A'

I know that if I use private inheritance, Then the members of the class 'A' would be private in 'B', And inaccessible in 'C', But why can't I create an object of 'A' inside 'C'?

答:
The problem is that the name A inside the scope of the class C is a private name.

It is a so-called injected class name.

From the C++ Standard (6.3.2 Point of declaration)

8 The point of declaration for an injected-class-name (Clause 12) is
  immediately following the opening brace of the class definition.

Use the following approach that is use the qualified name

```<code>class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        ::A a{};
      //^^^^^^
    }
};
</code>```

Body:
I'm using Visual C++, If I compile this code:

class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        A a{};
    }
};

I get this error:

error C2247: 'A' not accessible because 'B' uses 'private' to inherit
  from 'A'

I know that if I use private inheritance, Then the members of the class 'A' would be private in 'B', And inaccessible in 'C', But why can't I create an object of 'A' inside 'C'?

Body:
The problem is that the name A inside the scope of the class C is a private name.

It is a so-called injected class name.

From the C++ Standard (6.3.2 Point of declaration)

8 The point of declaration for an injected-class-name (Clause 12) is
  immediately following the opening brace of the class definition.

Use the following approach that is use the qualified name

class A {};
class B : private A {};
class C : public B
{
    void func()
    {
        ::A a{};
      //^^^^^^
    }
};


问:
How can I create a class without defining it in JavaScript?
I have a class at server-side like this:

```<code>public class Address
{
    public Address(string countryCode)
    {
        this._CountryCode = countryCode;
    }

    private string _CountryCode = string.Empty;
    public string CountryCode
    {
        get { return _CountryCode; }
        set { _CountryCode = value; }
    }

}
</code>```

and I have a method that called by Ajax methods :

```<code>[AjaxMethod]
public static Address ValidateAddress(Address address)
{
   // Some logic here...
   return address;
}
</code>```

And I want to call this method in client side, but how can I instantiate the Address class in client side? I do not want to define a class named Address in JavaScript file.

```<code><script>

function valaddress(){

  var address = new Address(); // I'm asking here ??
  address.CountryCode = 90;

  // This part is ok, no problem in here :
  var validatedAddress = AddressControlDataHelper.ValidateAddress(address).value;

}

</script>
</code>```

Is there a way to do this? Or do I need to write my Address class in JavaScript?

答: You are going to have to serialize the object first.  One way to do this is with JSON (Javascript Object Notation) - here is a tutorial on how that works. EDIT: (Actually that tutorial is quite confusing and a bit outdated - try this one for a more direct, up-to-date approach.)

OwnerDisplayName: ScarletGarden

Body:
I have a class at server-side like this:

public class Address
{
    public Address(string countryCode)
    {
        this._CountryCode = countryCode;
    }

    private string _CountryCode = string.Empty;
    public string CountryCode
    {
        get { return _CountryCode; }
        set { _CountryCode = value; }
    }

}

and I have a method that called by Ajax methods :

[AjaxMethod]
public static Address ValidateAddress(Address address)
{
   // Some logic here...
   return address;
}

And I want to call this method in client side, but how can I instantiate the Address class in client side? I do not want to define a class named Address in JavaScript file.

Is there a way to do this? Or do I need to write my Address class in JavaScript?

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andrew Hare


问:
Java wildcard strange behaviour when class is generic
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

```<code>package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}
</code>```

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

```<code>public class Test<T> {
...
}
</code>```

,

```<code>Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog
</code>```

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

答:
The expression new Test() is of raw type. The Java Language Specification defines the types of members of raw types as follows:

The type of a constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to C. The type of a static member of a raw type C is the same as its type in the generic declaration corresponding to C.

The erasure of List<? super Animal> is List.

The rationale behind this definition is probably that raw types are intended as a means to use generic types from non-generic legacy code, where type parameters are never present. They were not designed, and less than optimal for, leaving a type parameter unspecified; that's what wildcard types are for, i.e. if you code for a compiler compliance level greater than 1.5 you should write

```<code>    Test<?> test = makeTest();
    test.test(animalList);
    test.test(mammalList);
    test.test(dogList);
</code>```

and rejoice (or curse, as the matter may be) on seing the compilation errors again.

Body:
I thought that i have some good understanding of Java generics.

This code DOES NOT COMPILE and I know why.

We can pass to test method only List of type Animal or its super type (like List of Objects)

package scjp.examples.generics.wildcards;

import java.util.ArrayList;
import java.util.List;

class Animal {}
class Mammal extends Animal {}
class Dog extends Mammal {}

public class Test {

    public void test(List<? super Animal> col) {
        col.add(new Animal());
        col.add(new Mammal());
        col.add(new Dog());
    }

    public static void main(String[] args) {
        List<Animal> animalList = new ArrayList<Animal>();
        List<Mammal> mammalList = new ArrayList<Mammal>();
        List<Dog> dogList = new ArrayList<Dog>();

        new Test().test(animalList);
        new Test().test(mammalList); // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Mammal>)
        new Test().test(dogList);    // Error: The method test(List<? super Animal>) in the type Test is not applicable for the arguments (List<Dog>)

        Dog dog = dogList.get(0);
    }
}

But here comes the strange part (at least for me).

If we declare class Test as generic by only adding <T>, then it COMPILES! and throws java.lang.ClassCastException:

public class Test<T> {
...
}

,

Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog

My question is why adding generic class type <T> (which is not used anywhere) caused class to compile and changed wildcard behaviour?

Body:
The expression new Test() is of raw type. The Java Language Specification defines the types of members of raw types as follows:

The type of a constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to C. The type of a static member of a raw type C is the same as its type in the generic declaration corresponding to C.

The erasure of List<? super Animal> is List.

The rationale behind this definition is probably that raw types are intended as a means to use generic types from non-generic legacy code, where type parameters are never present. They were not designed, and less than optimal for, leaving a type parameter unspecified; that's what wildcard types are for, i.e. if you code for a compiler compliance level greater than 1.5 you should write

    Test<?> test = makeTest();
    test.test(animalList);
    test.test(mammalList);
    test.test(dogList);

and rejoice (or curse, as the matter may be) on seing the compilation errors again.


问:
When creating multiple API Gateway instances in template.yaml, how do you control which Gateway is imitated when running 'sam local start-api'?
I've created a SAM template.yaml file that contains two API Gateway instances - one for production and one for staging. Each has its own stage called Production and Staging respectively and each of these stages have their own Stage Variables which are specific to the environment.

The application I'm building locally has been created using the AWS SAM CLI and I've been using the command 'sam local start-api' to run local instances of an API Gateway to test calling endpoints in postman - which has been working fine. Unfortunately, I now need to start testing endpoints that require stage variables and I can't see any way of telling SAM CLI which of the two API Gateway instances in the template file to imitate. Obviously I don't want it to use Production as that will have data that connects to live services.

I'm aware that I could have created one API Gateway instance that contains two Stages and so, in the event that there isn't a way to do the above, is there a way to get SAM to use a particular stage within an API Gateway instance instead? Below is a snippet from my template file.

```<code>ApiProduction:
    Type: AWS::Serverless::Api
    Properties:
      Name: service-layer-production-v1
      StageName: Production
      OpenApiVersion: 3.0.1
      Auth:
        ApiKeyRequired: true
      Variables:
        IS_STAGING: false
        VARIABLE2: value-a
        VARIABLE3: value-a
      Models:
        Error:
          $schema: http://json-schema.org/draft-04/schema#
          title: Error Schema
          type: object
          properties:
            message:
              type: string
        Empty:
          $schema: http://json-schema.org/draft-04/schema#
          title: Empty Schema
          type: object
          properties:
            message:
              type: string

  ApiStaging:
    Type: AWS::Serverless::Api
    Properties:
      Name: service-layer-staging-vnull
      StageName: Staging
      OpenApiVersion: 3.0.1
      Auth:
        ApiKeyRequired: true
      Variables:
        IS_STAGING: true
        VARIABLE2: value-b
        VARIABLE3: value-b
      Models:
        Error:
          $schema: http://json-schema.org/draft-04/schema#
          title: Error Schema
          type: object
          properties:
            message:
              type: string
        Empty:
          $schema: http://json-schema.org/draft-04/schema#
          title: Empty Schema
          type: object
          properties:
            message:
              type: string
</code>```

答:
You can use cloud formation if condition https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if to achieve that.

Here is a quick example:

# Set expected parameter to be passed to sam local
Parameters:
  Stage:
    Type: String
    Default: staging
    Description: Parameter for getting the deployment stage

# Create a condition based on the parameter
Conditions:
  isStagingEnvironment: !Equals
    - Ref: Stage
    - staging

Resources:

  MyFunction:
    Type: "AWS::Serverless::Function"
    Properties:
      Events:
        CatchAll:
          Type: Api
          Properties:
            Method: GET
            Path: /my-sample-function
            # If condition to switch which API to use for this event while invoking the function
            RestApiId: !If
              - isStagingEnvironment
              - !Ref ApiStaging
              - !Ref ApiProduction
```

<p>Then you can run your sam locally this way:</p>

<pre class="lang-bash prettyprint-override"><code>sam local start-api --parameter-overrides Stage=staging
</code>```

The same technique can be used if you have multiple stages per single API Gateway.

Body:
I've created a SAM template.yaml file that contains two API Gateway instances - one for production and one for staging. Each has its own stage called Production and Staging respectively and each of these stages have their own Stage Variables which are specific to the environment.

The application I'm building locally has been created using the AWS SAM CLI and I've been using the command 'sam local start-api' to run local instances of an API Gateway to test calling endpoints in postman - which has been working fine. Unfortunately, I now need to start testing endpoints that require stage variables and I can't see any way of telling SAM CLI which of the two API Gateway instances in the template file to imitate. Obviously I don't want it to use Production as that will have data that connects to live services.

I'm aware that I could have created one API Gateway instance that contains two Stages and so, in the event that there isn't a way to do the above, is there a way to get SAM to use a particular stage within an API Gateway instance instead? Below is a snippet from my template file.

ApiProduction:
    Type: AWS::Serverless::Api
    Properties:
      Name: service-layer-production-v1
      StageName: Production
      OpenApiVersion: 3.0.1
      Auth:
        ApiKeyRequired: true
      Variables:
        IS_STAGING: false
        VARIABLE2: value-a
        VARIABLE3: value-a
      Models:
        Error:
          $schema: http://json-schema.org/draft-04/schema#
          title: Error Schema
          type: object
          properties:
            message:
              type: string
        Empty:
          $schema: http://json-schema.org/draft-04/schema#
          title: Empty Schema
          type: object
          properties:
            message:
              type: string

  ApiStaging:
    Type: AWS::Serverless::Api
    Properties:
      Name: service-layer-staging-vnull
      StageName: Staging
      OpenApiVersion: 3.0.1
      Auth:
        ApiKeyRequired: true
      Variables:
        IS_STAGING: true
        VARIABLE2: value-b
        VARIABLE3: value-b
      Models:
        Error:
          $schema: http://json-schema.org/draft-04/schema#
          title: Error Schema
          type: object
          properties:
            message:
              type: string
        Empty:
          $schema: http://json-schema.org/draft-04/schema#
          title: Empty Schema
          type: object
          properties:
            message:
              type: string

Body:
You can use cloud formation if condition https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if to achieve that.

Here is a quick example:

# Set expected parameter to be passed to sam local
Parameters:
  Stage:
    Type: String
    Default: staging
    Description: Parameter for getting the deployment stage

# Create a condition based on the parameter
Conditions:
  isStagingEnvironment: !Equals
    - Ref: Stage
    - staging

Resources:

  MyFunction:
    Type: "AWS::Serverless::Function"
    Properties:
      Events:
        CatchAll:
          Type: Api
          Properties:
            Method: GET
            Path: /my-sample-function
            # If condition to switch which API to use for this event while invoking the function
            RestApiId: !If
              - isStagingEnvironment
              - !Ref ApiStaging
              - !Ref ApiProduction

Then you can run your sam locally this way:

sam local start-api --parameter-overrides Stage=staging

The same technique can be used if you have multiple stages per single API Gateway.


问:
Running Thread Groups for Different Actions
I want to create test plan for 100 users with different action as:

Thread group 1 with 40 users as a. launch website b. search

Thread group 1 with 30 users as a. launch website b. login c. logout

Thread group 1 with 30 users as a. launch website b. Search c. add to cart

How can I create this test plan?

答:
You can create this test plan in many ways by using different elements. The simplest way to do this:

Add three thread group elements in your test plan and then define them accordingly.

Under each thread group, you can add your user-specific requests/sampler (login, search, logout)

Your test plan should be like:

If you want to run those thread groups one at a time, check the "Run Thread Groups consecutively" settings in the Test Plan element.


问:
React - Dealing with undefined state when mapping over an array of objects from API
API data is fetched when component mounts, and state is set in the form

```<code>sectionData: {
  course: null,
  section_id: null,
  semester: null,
  number: null,
  seats: null,
  meetings: [],
  open_seats: null,
  waitlist: null,
  instructors: []
},
</code>```

For reference the relevant API data looks like this

```<code>"meetings": [
 {
  "days": "TuTh",
  "room": "0324",
  "building": "IRB",
  "classtype": "",
  "start_time": "11:00am",
  "end_time": "12:15pm"
 },
 {
  "days": "MW",
  "room": "3120",
  "building": "CSI",
  "classtype": "Discussion",
  "start_time": "9:00am",
  "end_time": "9:50am"
 }
],
</code>```

Using keys like course and section_id is fine, since they are predefined with null. However, if I am to map over each meeting object in meetings, and say access "days" or "room", each meeting is obviously undefined.

```<code>{this.state.sectionData.meetings.map(meeting => this.renderMeetings())}

    renderMeetings(meeting) {
        return (<div key={meeting}>
            {meeting.days}
        </div>)
    }
</code>```

Any easy fixes without having to make an entirely new Meeting component to predefine said keys? Merely checking for an undefined prevents React from crashing, but doesn't help with actually displaying the data.

答:
There is a problem with your below code

```<code>renderMeetings(meeting) {
    return (<div key={meeting}>
        {meeting.days}
    </div>)
}
</code>```

meeting is an object so the key will always be converted to a string which is [object Object]. Keys can not be same

Body:
API data is fetched when component mounts, and state is set in the form

sectionData: {
  course: null,
  section_id: null,
  semester: null,
  number: null,
  seats: null,
  meetings: [],
  open_seats: null,
  waitlist: null,
  instructors: []
},

For reference the relevant API data looks like this

"meetings": [
 {
  "days": "TuTh",
  "room": "0324",
  "building": "IRB",
  "classtype": "",
  "start_time": "11:00am",
  "end_time": "12:15pm"
 },
 {
  "days": "MW",
  "room": "3120",
  "building": "CSI",
  "classtype": "Discussion",
  "start_time": "9:00am",
  "end_time": "9:50am"
 }
],

Using keys like course and section_id is fine, since they are predefined with null. However, if I am to map over each meeting object in meetings, and say access "days" or "room", each meeting is obviously undefined.

{this.state.sectionData.meetings.map(meeting => this.renderMeetings())}

    renderMeetings(meeting) {
        return (

            {meeting.days}

)
    }

Any easy fixes without having to make an entirely new Meeting component to predefine said keys? Merely checking for an undefined prevents React from crashing, but doesn't help with actually displaying the data.

Body:
There is a problem with your below code

renderMeetings(meeting) {
    return (<div key={meeting}>
        {meeting.days}
    </div>)
}

meeting is an object so the key will always be converted to a string which is [object Object]. Keys can not be same


问:
Perl angle brackets in regex substitution
I have encountered the following code:

```<code>my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;
</code>```

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

```<code>$string =~ s/(\d+)/$1\./g;
</code>```

What do angle brackets mean?

答:
I'd like to add (to the numerous answers) that there can be two different pairs of delimiters in a s/// statement.

@choroba had an example on s()[] in their answer but didn't draw any particular attention to it, so I want to add this for emphasis.

Consider the regex replacement expression in the form s{aaa}{bbb}.

It's only if the first delimiter is non-paired that it will dictate the delimiter for the entire expression. Then the end-of-match and start-of-replacement delimiters in the middle bleed together (they're the same character), and instead of s#aaa##bbb# you get

```<code>s#aaa#bbb#
</code>```

On the other hand, if you lead with paired delimiters for the match part, you're free to choose again for the replacement:

```<code># not only
s{aaa}{bbb}

# but also
s{aaa}[bbb]

# and even
s{aaa}#bbb#
s{aaa}/bbb/
</code>```

This is mostly useful for things like:

```<code>s{aaa}'$literalstring'
</code>```

to avoid interpolation and escaping in the replacement part, while allowing interpolation in the match.

While this usually makes the code harder to take in (and is therefore not advisable), I'm making a note of it here for completeness's sake - you may come across it in code.

Body:
I have encountered the following code:

my $string = "fo2345obar";
$string =~ s<(\d+)><$1\.>g;

I cannot understand what angle brackets mean in this context; all substitutions I saw before were of form:

$string =~ s/(\d+)/$1\./g;

What do angle brackets mean?

Body:
I'd like to add (to the numerous answers) that there can be two different pairs of delimiters in a s/// statement.

@choroba had an example on s()[] in their answer but didn't draw any particular attention to it, so I want to add this for emphasis.

Consider the regex replacement expression in the form s{aaa}{bbb}.

It's only if the first delimiter is non-paired that it will dictate the delimiter for the entire expression. Then the end-of-match and start-of-replacement delimiters in the middle bleed together (they're the same character), and instead of s#aaa##bbb# you get

s#aaa#bbb#

On the other hand, if you lead with paired delimiters for the match part, you're free to choose again for the replacement:

# not only
s{aaa}{bbb}

# but also
s{aaa}[bbb]

# and even
s{aaa}#bbb#
s{aaa}/bbb/

This is mostly useful for things like:

s{aaa}'$literalstring'

to avoid interpolation and escaping in the replacement part, while allowing interpolation in the match.

While this usually makes the code harder to take in (and is therefore not advisable), I'm making a note of it here for completeness's sake - you may come across it in code.


问:
arithmetic operation using JavaScript
i am trying to perform addition in javascript. below is my code :

function myfunc(size){
    var m = parseInt(size)+5;
    alert(m );
```

<p>When i use 'alert',it works perfectly.. but i want to use sweet alert and it is not display anything via sweet alert. when i do:</p>

<pre class="lang-js prettyprint-override"><code>function myfunc(size){
    sweetAlert(size );
</code>```

it does display the size using the code above. the problem is, it doesn't work when i try to perform the addition. why is it so?

答:
try something like this</p>

```<code>import swal from "sweetalert";

function myfunc(size) {
  var m = parseInt(size) + 5;
  swal(String(m));
}

myfunc("6");
</code>```

Title: arithmetic operation using JavaScript

Body:
i am trying to perform addition in javascript. below is my code :

function myfunc(size){
    var m = parseInt(size)+5;
    alert(m );

When i use 'alert',it works perfectly.. but i want to use sweet alert and it is not display anything via sweet alert. when i do:

function myfunc(size){
    sweetAlert(size );

it does display the size using the code above. the problem is, it doesn't work when i try to perform the addition. why is it so?

Body:
try something like this

import swal from "sweetalert";

function myfunc(size) {
  var m = parseInt(size) + 5;
  swal(String(m));
}

myfunc("6");


问:
Delete row from two tables with condition
My example:

Table A: post_id

Table B: id + delete(null)

In that, post_id = id

I want to delete all rows for both tables where A.deleted != 'null'

I tried: Delete A, B FROM A LEFT JOIN B ON B.post_id = A.id WHERE A.deleted != 'null' - but not work

答:
If your no record fetch for delete != 'null' then you should add deleted is not null OR delete != 'null'

You can not check null value with == or != operator you need to use is or is not for this kind of filtration

```<code>Delete A, B
    FROM A LEFT JOIN B ON B.post_id = A.id
    WHERE  A.deleted is not null OR A.deleted != 'null'
</code>```

Body:
If your no record fetch for delete != 'null' then you should add deleted is not null OR delete != 'null'

You can not check null value with == or != operator you need to use is or is not for this kind of filtration

Delete A, B
    FROM A LEFT JOIN B ON B.post_id = A.id
    WHERE  A.deleted is not null OR A.deleted != 'null'


问:
detect middle (rotary) button click on android waer
I am developing an app for Android Wear and are using the hardware buttons.
I can manage to catch the buttons with the onKeyDown override:

```<code>    public boolean onKeyDown(int keyCode, KeyEvent event){
      Log.i("CLICK", Integer.toString(keyCode));
      if (event.getRepeatCount() == 0) {
        if (keyCode == KeyEvent.KEYCODE_STEM_1) {
          // Do stuff
          return true;
        } else if (keyCode == KeyEvent.KEYCODE_STEM_2) {
          // Do stuff
          return true;
        } else if (keyCode == KeyEvent.KEYCODE_STEM_3) {
          // Do stuff
          return true;
        }
      }
      return super.onKeyDown(keyCode, event);
    }
</code>```

I would also like to catch a click on the middle (rotary) button,
but when I click this button, the watch is going back to the default 'home'(watchface)-screen,
and no event is being logged.

I can manage to catch the rotary scrolling, but it's the click I'd like to use.

```<code>    @Override
    public boolean onGenericMotionEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_SCROLL && RotaryEncoder.isFromRotaryEncoder(ev)) {
            // // Note that we negate the delta value here in order to get the right scroll direction.
            // float delta = -RotaryEncoder.getRotaryAxisValue(ev)
            //         * RotaryEncoder.getScaledScrollFactor(getContext());
            // scrollBy(0, Math.round(delta));
            return true;
        }
        return super.onGenericMotionEvent(ev);
    }
</code>```

Is this possible, or is it impossible to override the functionallity of the middle watch button?

答:
AFAIU It should be getting KEYCODE_HOME as key event on pressing RSB in onKeyDown().
If it is the case then it is controlled by Android framework only and apps can't do anything with it.

Here is the official description

Key code constant: Home key. This key is handled by the framework and
  is never delivered to applications.

https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_HOME

Body:
I am developing an app for Android Wear and are using the hardware buttons.
I can manage to catch the buttons with the onKeyDown override:

    public boolean onKeyDown(int keyCode, KeyEvent event){
      Log.i("CLICK", Integer.toString(keyCode));
      if (event.getRepeatCount() == 0) {
        if (keyCode == KeyEvent.KEYCODE_STEM_1) {
          // Do stuff
          return true;
        } else if (keyCode == KeyEvent.KEYCODE_STEM_2) {
          // Do stuff
          return true;
        } else if (keyCode == KeyEvent.KEYCODE_STEM_3) {
          // Do stuff
          return true;
        }
      }
      return super.onKeyDown(keyCode, event);
    }

I would also like to catch a click on the middle (rotary) button,
but when I click this button, the watch is going back to the default 'home'(watchface)-screen,
and no event is being logged.

I can manage to catch the rotary scrolling, but it's the click I'd like to use.

    @Override
    public boolean onGenericMotionEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_SCROLL && RotaryEncoder.isFromRotaryEncoder(ev)) {
            // // Note that we negate the delta value here in order to get the right scroll direction.
            // float delta = -RotaryEncoder.getRotaryAxisValue(ev)
            //         * RotaryEncoder.getScaledScrollFactor(getContext());
            // scrollBy(0, Math.round(delta));
            return true;
        }
        return super.onGenericMotionEvent(ev);
    }

Is this possible, or is it impossible to override the functionallity of the middle watch button?


问:
How to implement decorator with two arfument function
I haven't use decorator before but now I need to implement some repitable tests that compare some lists of data and I want to use less code for this. I whant to have a function that compares list of data from two data sets.

```<code> def compare(a,b):
    for j, c in zip(a, b):
        try:
            assert j == c
        except AssertionError:
            raise AssertionError(f"\n{a} arr1: {j}\n{b} arr2:  {c}")
</code>```

And this is two lists:

```<code>arr1 = [arg1, arg2, arg3, arg4]
arr2 = [arg1, arg2, arg3, arg4]
</code>```

I'm creating decorator:

```<code>def decor(func):
    def comp(a,b):
        for j, c in zip(a, b):
            try:
                assert j == c
            except AssertionError:
                raise AssertionError(f"\n{a}: {j}\n{b}:  {c}")
            func()
    return comp
</code>```

Then defining method with two lists:

```<code>@decor
def lists():
    arr1 = [arg1, arg2, arg3, arg4]
    arr2 = [arg1, arg2, arg3, arg4]
    return arr1, arr2
</code>```

But I'm getting an error and don't know how to set expected arguments:

TypeError: comp() missing 2 required positional arguments: 'a' and 'b'

答:
If you know that your function will return two lists and you must do this with a decorator, I suggest we keep your compare(a,b) function separate for the time being to keep it simple. Then in the decorator:

```<code>def decor(func):
    def wrapper(*a, **kw):
        a, b = func(*a, **kw)
        compare(a,b)
        return a, b
    return wrapper
</code>```

Body:
I haven't use decorator before but now I need to implement some repitable tests that compare some lists of data and I want to use less code for this. I whant to have a function that compares list of data from two data sets.

 def compare(a,b):
    for j, c in zip(a, b):
        try:
            assert j == c
        except AssertionError:
            raise AssertionError(f"\n{a} arr1: {j}\n{b} arr2:  {c}")

And this is two lists:

arr1 = [arg1, arg2, arg3, arg4]
arr2 = [arg1, arg2, arg3, arg4]

I'm creating decorator:

def decor(func):
    def comp(a,b):
        for j, c in zip(a, b):
            try:
                assert j == c
            except AssertionError:
                raise AssertionError(f"\n{a}: {j}\n{b}:  {c}")
            func()
    return comp

Then defining method with two lists:

@decor
def lists():
    arr1 = [arg1, arg2, arg3, arg4]
    arr2 = [arg1, arg2, arg3, arg4]
    return arr1, arr2

But I'm getting an error and don't know how to set expected arguments:

TypeError: comp() missing 2 required positional arguments: 'a' and 'b'

Body:
If you know that your function will return two lists and you must do this with a decorator, I suggest we keep your compare(a,b) function separate for the time being to keep it simple. Then in the decorator:

def decor(func):
    def wrapper(*a, **kw):
        a, b = func(*a, **kw)
        compare(a,b)
        return a, b
    return wrapper


问:
How to instantiate a class given its parent class in Python?
I have 3 subclasses and 1 parent class that make the children share a common method.

Example:

```<code>    class Animal:
      def communicate():
        pass

    class Dog(Animal):
       def communicate():
           bark()

    class Cat(Animal):
        def communicate():
            meow()
</code>```

I would like to provide an API that instantiates a cat or a dog based on the received string that will be either "cat" or "dog" and calls .communicate(), but I don't want to write if and elses to check whether I should run Dog() or Cat(). I wonder if it is possible to bark or meow by doing something like:
    Animal("dog").communicate()

Where "dog" can be a variable.

Or if possible give the child classes some labelling and be able to instantiate them via this label, or even via the own class name.

The ideia is to not have to write conditions Everytime I define new child child classes.

Thanks in advance!

答:
Factory pattern is your solution.

Aproach to automate conditions for creating classes described here

I can show how metaclasses can be applied:

```<code>class MetaAnimal(type):
    classes = {}

    def __new__(cls, name, bases, dct):
        result = super().__new__(cls, name, bases, dct)
        cls.classes[name.lower()] = result
        return result

    @classmethod
    def get_animal(cls, name):
        return cls.classes.get(name)

class Animal(metaclass=MetaAnimal):
    def communicate(self):
        pass

class Dog(Animal):
    def communicate(self):
        self.bark()

    def bark(self):
        print('Woof')

class Cat(Animal):
    def communicate(self):
        self.meow()

    def meow(self):
        print('Meow')

MetaAnimal.get_animal('cat')().communicate()
MetaAnimal.get_animal('dog')().communicate()
</code>```

Body:
I have 3 subclasses and 1 parent class that make the children share a common method.

Example:

    class Animal:
      def communicate():
        pass

    class Dog(Animal):
       def communicate():
           bark()

    class Cat(Animal):
        def communicate():
            meow()

I would like to provide an API that instantiates a cat or a dog based on the received string that will be either "cat" or "dog" and calls .communicate(), but I don't want to write if and elses to check whether I should run Dog() or Cat(). I wonder if it is possible to bark or meow by doing something like:
    Animal("dog").communicate()

Where "dog" can be a variable.

Or if possible give the child classes some labelling and be able to instantiate them via this label, or even via the own class name.

The ideia is to not have to write conditions Everytime I define new child child classes.

Thanks in advance!

Body:
Factory pattern is your solution.

Aproach to automate conditions for creating classes described here

I can show how metaclasses can be applied:

class MetaAnimal(type):
    classes = {}

    def __new__(cls, name, bases, dct):
        result = super().__new__(cls, name, bases, dct)
        cls.classes[name.lower()] = result
        return result

    @classmethod
    def get_animal(cls, name):
        return cls.classes.get(name)

class Animal(metaclass=MetaAnimal):
    def communicate(self):
        pass

class Dog(Animal):
    def communicate(self):
        self.bark()

    def bark(self):
        print('Woof')

class Cat(Animal):
    def communicate(self):
        self.meow()

    def meow(self):
        print('Meow')

MetaAnimal.get_animal('cat')().communicate()
MetaAnimal.get_animal('dog')().communicate()


问:
React - Substitute for `setState` Callback in Functional Components?
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

```<code>const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}
</code>```

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

答:
```<code>import React, { useState, useEffect } from "react";

const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);
  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
  };
  useEffect(() => {
    console.log(openDoor);
    if (openDoor) {
      setTimeout(() => setOpenDoor(!openDoor), 1500);
    }
  }, [openDoor]);
  return (
    <>
      <button onClick={toggleOpenDoor}>Toggle</button>
      <p>{`openDoor: ${openDoor}`}</p>
    </>
  );
};

export default Example;
</code>```

Codesandbox

Body:
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

Body:
import React, { useState, useEffect } from "react";

const Example = () => {
  const [openDoor, setOpenDoor] = useState(false);
  const toggleOpenDoor = () => {
    setOpenDoor(!openDoor);
  };
  useEffect(() => {
    console.log(openDoor);
    if (openDoor) {
      setTimeout(() => setOpenDoor(!openDoor), 1500);
    }
  }, [openDoor]);
  return (
    <>
      <button onClick={toggleOpenDoor}>Toggle</button>
      <p>{`openDoor: ${openDoor}`}</p>
    </>
  );
};

export default Example;

Codesandbox


答:
Am I unaware of all the capabilities of map.

In my limited experience the iterating variable meeting would be passed in to the function.

Would it help to Change

```<code>(meeting => this.renderMeetings())}
</code>```

To This?

```<code>// pass meeting in to function
(meeting => this.renderMeetings(meeting))}
</code>```

Title: React - Dealing with undefined state when mapping over an array of objects from API

Body:
Am I unaware of all the capabilities of map.

In my limited experience the iterating variable meeting would be passed in to the function.

Would it help to Change

(meeting => this.renderMeetings())}

To This?

// pass meeting in to function
(meeting => this.renderMeetings(meeting))}


问:
RewriteCond %{HTTP_HOST} doesn't work
I'm using this tester: http://htaccess.madewithlove.be/

I'll explain my goal from the beginning:
I have a server. Everytime the client asks the server for a specific image, I want the server to redirect to another image (a newer one).

```<code>My full ISAPI htaccess:
===================
# Helicon ISAPI_Rewrite configuration file
# Version 3.1.0.60

RewriteEngine On
RewriteCompatibility2 On
RepeatLimit 32
RewriteBase

RewriteRule ^/Bing$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/Zynga$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/([0-9]+)$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/CT([0-9]+)$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^images/infowindows/SPE_title.png$ http://%{HTTP_HOST}/images/infowindows/search.png [NC,L,R=301]
</code>```

Which I have tried in some online tester, and that seems to work well, as can be seen here:
https://picasaweb.google.com/elad2109/ImageResourceRedirect?authkey=Gv1sRgCK6K3vegz4veDQ#5607413050992754706

However, defato I see the old image brought to the website (client) and that also appears via Fiddler - no redirection is done (and I don't understand why !)

i see the request in Fiddler:

```<code>GET http://www108.MyHome.com/images/infowindows/SPE_ti... HTTP/1.1
Host: www108.conduitlive.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www108.MyHome.com/bing
Cookie: __utma=264109214.1078718614.1305536197.1305547582.1305556877.4; __utmc=264109214; __utmz=264109214.1305536197.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=69165847.1285126412.1305559921.1305559921.1305559921.1; __utmb=69165847.3.10.1305559921; __utmc=69165847; __utmz=69165847.1305559921.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Pragma: no-cache
Cache-Control: no-cache
</code>```

A sreenshot can be seen here:
https://picasaweb.google.com/elad2109/ImageResourceRedirect?authkey=Gv1sRgCK6K3vegz4veDQ#5607413044216373186

Does anyone have any Idea, what am I doing wrong?

Thanks in advance

答:
You could change

```<code>RewriteRule ^images/infowindows/SPE_title.png$ http://%{HTTP_HOST}/images/infowindows/search.png [NC,L,R=301]
</code>```

to:

```<code>RewriteRule ^/images/infowindows/SPE_title.png$ /images/infowindows/search.png [NC,L,R=301]
</code>```

Notice the / character in the beginning of the regex. This could be the root of the problem.

Title: RewriteCond %{HTTP_HOST} doesn't work

Body:
I'm using this tester: http://htaccess.madewithlove.be/

I'll explain my goal from the beginning:
I have a server. Everytime the client asks the server for a specific image, I want the server to redirect to another image (a newer one).

My full ISAPI htaccess:
===================
# Helicon ISAPI_Rewrite configuration file
# Version 3.1.0.60

RewriteEngine On
RewriteCompatibility2 On
RepeatLimit 32
RewriteBase

RewriteRule ^/Bing$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/Zynga$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/([0-9]+)$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^/CT([0-9]+)$ http://%{HTTP:Host} [NC,L,P]
RewriteRule ^images/infowindows/SPE_title.png$ http://%{HTTP_HOST}/images/infowindows/search.png [NC,L,R=301]

Which I have tried in some online tester, and that seems to work well, as can be seen here:
https://picasaweb.google.com/elad2109/ImageResourceRedirect?authkey=Gv1sRgCK6K3vegz4veDQ#5607413050992754706

However, defato I see the old image brought to the website (client) and that also appears via Fiddler - no redirection is done (and I don't understand why !)

i see the request in Fiddler:

GET http://www108.MyHome.com/images/infowindows/SPE_ti... HTTP/1.1
Host: www108.conduitlive.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www108.MyHome.com/bing
Cookie: __utma=264109214.1078718614.1305536197.1305547582.1305556877.4; __utmc=264109214; __utmz=264109214.1305536197.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=69165847.1285126412.1305559921.1305559921.1305559921.1; __utmb=69165847.3.10.1305559921; __utmc=69165847; __utmz=69165847.1305559921.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Pragma: no-cache
Cache-Control: no-cache

A sreenshot can be seen here:
https://picasaweb.google.com/elad2109/ImageResourceRedirect?authkey=Gv1sRgCK6K3vegz4veDQ#5607413044216373186

Does anyone have any Idea, what am I doing wrong?

Thanks in advance

Body:
You could change

RewriteRule ^images/infowindows/SPE_title.png$ http://%{HTTP_HOST}/images/infowindows/search.png [NC,L,R=301]

to:

RewriteRule ^/images/infowindows/SPE_title.png$ /images/infowindows/search.png [NC,L,R=301]

Notice the / character in the beginning of the regex. This could be the root of the problem.


问:
type parameter t has incompatible upper bounds: view and fragment
I like to get my fragment of my Activity, but i got the error:

type parameter t has incompatible upper bounds: view and fragment

by findViewById(R.id.f_instruction) in my MainActivity.
I hope you can help me.

My Activity:

```<code>public class MainActivity extends AppCompatActivity {
Fragment f_instruction;
public static void closeFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f_instruction = findViewById(R.id.f_instruction);
}
</code>```

}

XML of Activity:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/f_instruction"
        android:name="e.marco.gymdiary.first_fragment"
        android:layout_width="410dp"
        android:layout_height="732dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

答:
you can't get fragment by getViewById() method. the correct way for doing this is :

if you are in activity:

```<code>Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);
</code>```

if you are in fragment:

```<code>Fragment fragment=getChildFragmentManager().findFragmentById(R.id.your_fragment_id);
</code>```

also this is how to get fragment manager using context (useful if you are in adapter for example)

```<code>((AppCompatActivity)context).getSupportFragmentManager();
</code>```

Body:
I like to get my fragment of my Activity, but i got the error:

type parameter t has incompatible upper bounds: view and fragment

by findViewById(R.id.f_instruction) in my MainActivity.
I hope you can help me.

My Activity:

public class MainActivity extends AppCompatActivity {
Fragment f_instruction;
public static void closeFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f_instruction = findViewById(R.id.f_instruction);
}

}

XML of Activity:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/f_instruction"
        android:name="e.marco.gymdiary.first_fragment"
        android:layout_width="410dp"
        android:layout_height="732dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
you can't get fragment by getViewById() method. the correct way for doing this is :

if you are in activity:

Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);

if you are in fragment:

Fragment fragment=getChildFragmentManager().findFragmentById(R.id.your_fragment_id);

also this is how to get fragment manager using context (useful if you are in adapter for example)

((AppCompatActivity)context).getSupportFragmentManager();


问:
How to get a list of Google Slide Title and Slide Number - Google Apps Script
I am looking to get a list of all slide titles and respective slide numbers from an existing slide deck of 50+ slides.

I have looked at this question however it has been posted a couple of years ago and doesn't work any more.

I am grateful for any guidance on how to get started on solving this problem.

答:
Is this what you are looking for?

```<code>function somethingWithSlides(){

var slidesArray = [];

var presentation = SlidesApp.openById("XXXXX");

var slidesLength = presentation.getSlides().length;
var slidesTitles = presentation.getSlides().map(function(slide){return slide.getPageElements()[0].asShape().getText().asString()});
var slidesIds = presentation.getSlides().map(function(slide){return slide.getObjectId()});

  for(var i=0;i<slidesLength;i++){
    slidesArray.push([slidesTitles[i],slidesIds[i]]);
  }

return slidesArray;

}
</code>```

If not, sorry.

Body:
Is this what you are looking for?

function somethingWithSlides(){

var slidesArray = [];

var presentation = SlidesApp.openById("XXXXX");

var slidesLength = presentation.getSlides().length;
var slidesTitles = presentation.getSlides().map(function(slide){return slide.getPageElements()[0].asShape().getText().asString()});
var slidesIds = presentation.getSlides().map(function(slide){return slide.getObjectId()});

  for(var i=0;i<slidesLength;i++){
    slidesArray.push([slidesTitles[i],slidesIds[i]]);
  }

return slidesArray;

}

If not, sorry.


问:
pandas concat() does not join on same columns
I have two dataframes which I am trying to concatenate. I made sure they have the same amount of columns and that the data types match.

However, when calling pd.concat([df1, df2], ignore_index=True) I get a dataframe back with 24 columns and lots of NaN values. I expect pd.concat() to just place the second dataframe 'underneath' the first one (so the default; axis=0).

What am I doing wrong?

```<code>>>> df1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 798810 entries, 0 to 798809
Data columns (total 12 columns):
 #   Column  Non-Null Count   Dtype
---  ------  --------------   -----
 0   0       798810 non-null  Int64
 1   1       798810 non-null  float64
 2   2       798810 non-null  float64
 3   3       798810 non-null  float64
 4   4       798810 non-null  float64
 5   5       798810 non-null  float64
 6   6       798810 non-null  Int64
 7   7       798810 non-null  float64
 8   8       798810 non-null  Int64
 9   9       798810 non-null  float64
 10  10      798810 non-null  float64
 11  11      798810 non-null  float64
dtypes: Int64(3), float64(9)
memory usage: 75.4 MB
</code>```

```<code>>>> df2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 500 entries, 0 to 499
Data columns (total 12 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   0       500 non-null    Int64
 1   1       500 non-null    float64
 2   2       500 non-null    float64
 3   3       500 non-null    float64
 4   4       500 non-null    float64
 5   5       500 non-null    float64
 6   6       500 non-null    Int64
 7   7       500 non-null    float64
 8   8       500 non-null    Int64
 9   9       500 non-null    float64
 10  10      500 non-null    float64
 11  11      500 non-null    float64
dtypes: Int64(3), float64(9)
memory usage: 48.5 KB
</code>```

```<code>>>> pd.concat([df1, df2], ignore_index=True).shape
(799310, 24)
</code>```

答:
I think columns names in one Dataframe are not numeric, but strings, so you can try:

```<code>df1.columns = df1.columns.astype(int)
df2.columns = df2.columns.astype(int)

df = pd.concat([df1, df2], ignore_index=True)
</code>```

Or:

```<code>df = pd.concat([df1.rename(columns=int), df2.rename(columns=int)], ignore_index=True)
</code>```

Body:
I have two dataframes which I am trying to concatenate. I made sure they have the same amount of columns and that the data types match.

However, when calling pd.concat([df1, df2], ignore_index=True) I get a dataframe back with 24 columns and lots of NaN values. I expect pd.concat() to just place the second dataframe 'underneath' the first one (so the default; axis=0).

What am I doing wrong?

>>> df1.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 798810 entries, 0 to 798809
Data columns (total 12 columns):
 #   Column  Non-Null Count   Dtype
---  ------  --------------   -----
 0   0       798810 non-null  Int64
 1   1       798810 non-null  float64
 2   2       798810 non-null  float64
 3   3       798810 non-null  float64
 4   4       798810 non-null  float64
 5   5       798810 non-null  float64
 6   6       798810 non-null  Int64
 7   7       798810 non-null  float64
 8   8       798810 non-null  Int64
 9   9       798810 non-null  float64
 10  10      798810 non-null  float64
 11  11      798810 non-null  float64
dtypes: Int64(3), float64(9)
memory usage: 75.4 MB

>>> df2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 500 entries, 0 to 499
Data columns (total 12 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   0       500 non-null    Int64
 1   1       500 non-null    float64
 2   2       500 non-null    float64
 3   3       500 non-null    float64
 4   4       500 non-null    float64
 5   5       500 non-null    float64
 6   6       500 non-null    Int64
 7   7       500 non-null    float64
 8   8       500 non-null    Int64
 9   9       500 non-null    float64
 10  10      500 non-null    float64
 11  11      500 non-null    float64
dtypes: Int64(3), float64(9)
memory usage: 48.5 KB

>>> pd.concat([df1, df2], ignore_index=True).shape
(799310, 24)

Body:
I think columns names in one Dataframe are not numeric, but strings, so you can try:

df1.columns = df1.columns.astype(int)
df2.columns = df2.columns.astype(int)

df = pd.concat([df1, df2], ignore_index=True)

Or:

df = pd.concat([df1.rename(columns=int), df2.rename(columns=int)], ignore_index=True)


问:
Add rows to UITableView when scrolled to bottom
Is there a way to trigger an event, such as with an IBAction, when a user scrolls to the bottom of a UITableView? I would like to add more rows if this happens. How do I do this?

答:
Simply listen to the scrollViewDidScroll: delegate method, compare the content offset with the current possible offset and if lower then some threshold call your method to update the tableview. Don't forget to call [tableView reloadData] to make sure it reload the newly added data.

EDIT: Put together abstract code, not sure if it works, but should.

```<code>- (void)scrollViewDidScroll: (UIScrollView *)scroll {
     // UITableView only moves in one direction, y axis
     CGFloat currentOffset = scroll.contentOffset.y;
     CGFloat maximumOffset = scroll.contentSize.height - scroll.frame.size.height;

     // Change 10.0 to adjust the distance from bottom
     if (maximumOffset - currentOffset <= 10.0) {
          [self methodThatAddsDataAndReloadsTableView];
     }
}
</code>```

Body:
Simply listen to the scrollViewDidScroll: delegate method, compare the content offset with the current possible offset and if lower then some threshold call your method to update the tableview. Don't forget to call [tableView reloadData] to make sure it reload the newly added data.

EDIT: Put together abstract code, not sure if it works, but should.

- (void)scrollViewDidScroll: (UIScrollView *)scroll {
     // UITableView only moves in one direction, y axis
     CGFloat currentOffset = scroll.contentOffset.y;
     CGFloat maximumOffset = scroll.contentSize.height - scroll.frame.size.height;

     // Change 10.0 to adjust the distance from bottom
     if (maximumOffset - currentOffset <= 10.0) {
          [self methodThatAddsDataAndReloadsTableView];
     }
}


问:
Idiom for handling size_t underflow in loop condition
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

```<code>for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}
</code>```

There's the --> "operator" trick, which looks strange if you're not used to it.

```<code>for (size_t i = len; i--> 0;) {
    use(a[i]);
}
</code>```

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

```<code>for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}
</code>```

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

```<code>for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}
</code>```

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

```<code>for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}
</code>```

As for the iterating backwards case, you can use signed integers but that may cause overflows.

```<code>for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}
</code>```

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

```<code>for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}
</code>```

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

答:
I tend to add another expression to the loop condition, checking for
  len > 0, but that feels clumsy.

Your code should follow the logic. It is not clumsy at all. And it is much more readable for humans.

As the loop makes no sense if the len == 0 and I usually use the if statement. It makes the code easy to understand and maintain.

```<code>if(len)
{
    for (size_t i = 0; i < len-1; i++) { /*...*/ }
}
</code>```

or you can also add the check in the loop. BTW you only check if it is not zero.

```<code> for (size_t i = 0; len && i < len-1; i++) { /*...*/ }
</code>```

Body:
In C and C++, size_t is an unsigned type that is used for expressing size. It expresses intent and somewhat simplifies range assertions (len < upper_bound vs len >= 0 && len < upper_bound for signed integers).

(In all the examples below len means the length of the array a).

The idiom for a for loop is: for (i = 0; i < len; i++). The idiom for  a backward for loop is for (i = len-1; i >= 0; i--). But having unsigned loop indices introduces subtle bugs, and every so often I mess up the edge cases.

First, the backwards for loop. This code underflows for len=0.

for (size_t i = len-1; i >= 0; i--) { // Bad: Underflows for len=0
    use(a[i]);
}

There's the --> "operator" trick, which looks strange if you're not used to it.

for (size_t i = len; i--> 0;) {
    use(a[i]);
}

You can use a signed type for the loop index variable, but that overflows if len > INT_MAX. Many people and organizations considers that risk so minimal that they just stick to int.

for (int i = len-1; i >= 0; i--) {  // BAD: overflows for len < INT_MAX
    use(a[i]);
}

So I've settled for this construct, since it's closest to the canonical for-loop form and has the simplest expressions.

for (size_t i = len; i > 0; i--) {
    size_t pos = i-1;
    use(a[pos]);
}

My problem iterating from 0 to len-1

That is, looping over the range [0, len-1). This loop underflows when len=0.

for (size_t i = 0; i < len-1; i++) {   // BAD: Underflows for len=0.
    use(a[i]);
}

As for the iterating backwards case, you can use signed integers but that may cause overflows.

for (int i = 0; i < len-1; i++) {    // BAD: Will overflow if len > INT_MAX
    use(a[i]);
}

I tend to add another expression to the loop condition, checking for len > 0, but that feels clumsy.

for (size_t i = 0; len > 0 && i < len-1; i++) {
    use(a[i]);
}

I can add an if statement before the loop, but that also feels clumsy.

Is there a less bulky way of writing a for loop with unsigned index variables looping from 0 to len-1?

Body:
I tend to add another expression to the loop condition, checking for
  len > 0, but that feels clumsy.

Your code should follow the logic. It is not clumsy at all. And it is much more readable for humans.

As the loop makes no sense if the len == 0 and I usually use the if statement. It makes the code easy to understand and maintain.

if(len)
{
    for (size_t i = 0; i < len-1; i++) { /*...*/ }
}

or you can also add the check in the loop. BTW you only check if it is not zero.

 for (size_t i = 0; len && i < len-1; i++) { /*...*/ }


问:
Scraping content from infinite scroll website
I am trying to scrape the links in a webpage with infinite scrolling. I am able to fetch only the links on the first pane. How to proceed ahead so as to form a complete list of all the links. Here is what i have so far -

from bs4 import BeautifulSoup
import requests

html = "https://www.carwale.com/used/cars-for-sale/#sc=-1&so=-1&car=7&pn=8&lcr=168&ldr=0&lir=0"
html_content = requests.get(html).text
soup = BeautifulSoup(html_content, "lxml")
table = soup.find_all("div", {"class": "card-detail-block__data"})

y = []
for i in table:
    try:
        y.append(i.find("a", {"id":"linkToDetails"}).get('href'))
    except AttributeError:
        pass

z = [('carwale.com' + item) for item in y]
z
```

答:
Try this

```<code>next_page = next_page = soup.find('a', rel='next', href=True)

if next_page:
   next_html_content = requests.get(next_page).text
</code>```

The next page URL is hidden in the site source. You can find it by searching rel="next" tag in the browser.

Body:
Try this

next_page = next_page = soup.find('a', rel='next', href=True)

if next_page:
   next_html_content = requests.get(next_page).text

The next page URL is hidden in the site source. You can find it by searching rel="next" tag in the browser.


问:
doctl is unable to find docker binary
Configuring Digital Ocean Container Registry

link : https://www.digitalocean.com/docs/kubernetes/how-to/set-up-registry/

After Successfully : Snap install doctl

```<code>#doctl regitry login
Error : unable to Find Docker binary . make sure docker is installed

#docker --version
Docker version 18.09.2, build 6247962

</code>```

Github Issue : https://github.com/digitalocean/doctl/issues/709

答:
Problem

doctl is not able to find docker because snap binary path is /usr/snap/bin
and docker binary path is /usr/local/bin/

so somehow connection between them is broken

THIS IS MY CUSTOM SOLUTION TO MAKE IT WORK :

Step-1 :  Uninstall doctl  and Refresh env path

#sudo snap remove doctl

Step-2 : Install doctl using latest package

```<code>wget https://github.com/digitalocean/doctl/releases/download/v1.17.0/doctl-1.17.0-linux-amd64.tar.gz
curl -sL https://github.com/digitalocean/doctl/releases/download/v1.38.0/doctl-1.38.0-linux-amd64.tar.gz | tar -xzv
sudo mv ~/doctl /usr/local/bin
</code>```

(optional)Step ? : Fix path Problem
if doctl not found then fix it using Symbolic Link

ln -s  /usr/local/bin/doctl /usr/snap/doctl

Step-3 : Run docker login command

#doctl registry login

**IF getting error related to x11 then run command below and try Step-3 **

```<code>sudo apt update
sudo apt -V install gnupg2 pass
</code>```

#doctl registry login

login successfully

Title: doctl is unable to find docker binary

Body:
Configuring Digital Ocean Container Registry

link : https://www.digitalocean.com/docs/kubernetes/how-to/set-up-registry/

After Successfully : Snap install doctl

#doctl regitry login
Error : unable to Find Docker binary . make sure docker is installed

#docker --version
Docker version 18.09.2, build 6247962

Github Issue : https://github.com/digitalocean/doctl/issues/709

Body:
Problem

doctl is not able to find docker because snap binary path is /usr/snap/bin
and docker binary path is /usr/local/bin/

so somehow connection between them is broken

THIS IS MY CUSTOM SOLUTION TO MAKE IT WORK :

Step-1 :  Uninstall doctl  and Refresh env path

#sudo snap remove doctl

Step-2 : Install doctl using latest package

wget https://github.com/digitalocean/doctl/releases/download/v1.17.0/doctl-1.17.0-linux-amd64.tar.gz
curl -sL https://github.com/digitalocean/doctl/releases/download/v1.38.0/doctl-1.38.0-linux-amd64.tar.gz | tar -xzv
sudo mv ~/doctl /usr/local/bin

(optional)Step ? : Fix path Problem
if doctl not found then fix it using Symbolic Link

ln -s  /usr/local/bin/doctl /usr/snap/doctl

Step-3 : Run docker login command

#doctl registry login

**IF getting error related to x11 then run command below and try Step-3 **

sudo apt update
sudo apt -V install gnupg2 pass

#doctl registry login

login successfully


问:
How to make independent push notification in Android & iOS devices?
How to make independent push notification on mobile? By independent I mean not relying on Google Firebase cloud messaging. Since GCM was depreciated I would like to make a solution not dependent on mobile devices vendors. </p>

答:
Talking about Android in particular

Using Push Notifications without using any Google's/Firebase service would be a bit tricky. Since GCM/FCM service, keep on running on the device at all times, hence there is guarantee that their notifications will definitely be delivered.

However, for your use case, if you really want to implement your own custom Push Notification Service, you can follow these steps:

Implement a background service which keeps on running in the background. Your service could be killed sometimes, due to various factors of the android device, hence, you may need to implement an AlarmReceiver to restart your service if it is killed, from time to time.

In your background service, you must either ping your server, at certain intervals, passing a unique ID, maybe a user Id, or device Id or any other uniquely identifiable ID for each device/user,  to check if there are any notifications or not. This could further be implemented in various ways, like using Socket Connection, or via APIs etc. You will have to find the best solution to minimize the number of requests on the server.

If there are any notifications, based on the passed (queried) parameters, the server should send the response with the content. Otherwise, do nothing.

Once you receive a valid (with content) response from the server, you can create a notification to remind the user about the same.

Please note, this may not be the best solution to perfectly suit your requirements on both Android and iOS, however, this is a general process of receiving a notification from the server (implementing a two-way communication at certain intervals).

You must focus on creating a service which keeps on running in the background at almost all times, to be able to use push notifications in real-time.


问:
I tried to make a player move in pygame but it didn't work and it's giving me this error:
There's the error:

```<code>File "C:/Users/jimos/PycharmProjects/ffg/app.py", line 40
   if event.type==pygame.KEYUP:
                              ^
IndentationError: unindent does not match any outer indentation level
</code>```

And I followed this tutorial:https://www.youtube.com/watch?v=FfWpgLFMI7w&t=53s

import pygame

pygame.init()

#create the screen
screen=pygame.display.set_mode((800, 600))

#Title and Icon
pygame.display.set_caption("Space Invaders")
icon=pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

#Player
playerImg=pygame.image.load('player.png')
playerX=370
playerY=480
playerX_change=0

def player(x,y):
    screen.blit(playerImg, (x, y))

#game loop
running=True
while running:

    screen.fill((255, 128, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

            # if keystroke is pressed check whether its left or right
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LEFT:
                   playerX_change= -0.1
                if event.key==pygame.K_RIGHT:
                   playerX_change= 0.1
         if event.type==pygame.KEYUP:
             if event.key==pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change= 0

    # 5=5 + -0.1 -> 5=5 - 0.1
    # 5=5 + 0.1
    playerX += playerX_change
    player(playerX,playerY)
    pygame.display.update()
```

答:
It is an Indentation issue. There is 1 blank too many before the line if event.type==pygame.KEYUP:.

Just delete 1 leading blank to solve the issue.

running=True
while running:

    screen.fill((255, 128, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

            # if keystroke is pressed check whether its left or right
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LEFT:
                   playerX_change= -0.1
                if event.key==pygame.K_RIGHT:
                   playerX_change= 0.1

        # remove 1 bank here <----------------------------
         if event.type==pygame.KEYUP:
             if event.key==pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change= 0
```

Body:
There's the error:

File "C:/Users/jimos/PycharmProjects/ffg/app.py", line 40
   if event.type==pygame.KEYUP:
                              ^
IndentationError: unindent does not match any outer indentation level

And I followed this tutorial:https://www.youtube.com/watch?v=FfWpgLFMI7w&t=53s

import pygame

pygame.init()

#create the screen
screen=pygame.display.set_mode((800, 600))

#Title and Icon
pygame.display.set_caption("Space Invaders")
icon=pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

#Player
playerImg=pygame.image.load('player.png')
playerX=370
playerY=480
playerX_change=0

def player(x,y):
    screen.blit(playerImg, (x, y))

#game loop
running=True
while running:

    screen.fill((255, 128, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

            # if keystroke is pressed check whether its left or right
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LEFT:
                   playerX_change= -0.1
                if event.key==pygame.K_RIGHT:
                   playerX_change= 0.1
         if event.type==pygame.KEYUP:
             if event.key==pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change= 0

    # 5=5 + -0.1 -> 5=5 - 0.1
    # 5=5 + 0.1
    playerX += playerX_change
    player(playerX,playerY)
    pygame.display.update()


问:
Expanding DCGs in Prolog
I'm writing a code generator that converts definite clause grammars to other grammar notations. To do this, I need to expand a grammar rule:

```<code>:- initialization(main).

main :-
        -->(example,A),writeln(A).
% this should print ([a],example1), but this is a runtime error

example --> [a],example1.
example1 --> [b].
</code>```

But -->(example, A) doesn't expand the rule, even though -->/2 appears to be defined here. Is there another way to access the definitions of DCG grammar rules?

答:
As you wrote on the comments, if you want to convert DCGs into CHRs, you need to apply the conversion before the default expansion of DCGs into clauses. For example, assuming your code is saved to a grammars.pl file:

```<code>?- assertz(term_expansion((H --> B), '--->'(H,B))).
true.

?- assertz(goal_expansion((H --> B), '--->'(H,B))).
true.

?- [grammars].
[a],example1
true.
</code>```

Title: Expanding DCGs in Prolog

Body:
I'm writing a code generator that converts definite clause grammars to other grammar notations. To do this, I need to expand a grammar rule:

:- initialization(main).

main :-
        -->(example,A),writeln(A).
% this should print ([a],example1), but this is a runtime error

example --> [a],example1.
example1 --> [b].

But -->(example, A) doesn't expand the rule, even though -->/2 appears to be defined here. Is there another way to access the definitions of DCG grammar rules?

Body:
As you wrote on the comments, if you want to convert DCGs into CHRs, you need to apply the conversion before the default expansion of DCGs into clauses. For example, assuming your code is saved to a grammars.pl file:

?- assertz(term_expansion((H --> B), '--->'(H,B))).
true.

?- assertz(goal_expansion((H --> B), '--->'(H,B))).
true.

?- [grammars].
[a],example1
true.