问:
Open Settings App from another App in iOS - React Native
I'm going through the docs in React Native and can only find navigating to external links from the app I am in.

I want to be able to navigate to the Settings app (more specifically to the privacy > location services page) but, can not seem to find the necessary information on it. There is the native iOS way of doing it which I am trying to replicate through React Native.

Is this possible?

I have tried the following to detect if there is a Settings URL. The console logs that the Settings url works however, it does not navigate to that page.

Update: thanks to @zvona I am now navigating to the settings page but not sure how to get to a specific deep link.

```<code>Linking.canOpenURL('app-settings:').then(supported => {

    console.log(`Settings url works`)
    Linking.openURL('app-settings:'
}).catch(error => {
    console.log(`An error has occured: ${error}`)
})
</code>```

答:
You can import Linking from 'react-native' and then use Linking.openSettings() to trigger the call. This link explains it very concisely:

https://til.hashrocket.com/posts/eyegh79kqs-how-to-open-the-settings-app-in-reactnative-060

Body:
I'm going through the docs in React Native and can only find navigating to external links from the app I am in.

I want to be able to navigate to the Settings app (more specifically to the privacy > location services page) but, can not seem to find the necessary information on it. There is the native iOS way of doing it which I am trying to replicate through React Native.

Is this possible?

I have tried the following to detect if there is a Settings URL. The console logs that the Settings url works however, it does not navigate to that page.

Update: thanks to @zvona I am now navigating to the settings page but not sure how to get to a specific deep link.

Linking.canOpenURL('app-settings:').then(supported => {

    console.log(`Settings url works`)
    Linking.openURL('app-settings:'
}).catch(error => {
    console.log(`An error has occured: ${error}`)
})


来源: stackexchange

问:
How to best structure this data in MySQL tables?
I am building a scheduling application for a production facility.

There are 8 separate production cells in the building and, for each given day, each cell has a different production capacity (ex. production cell A has 6 people working on 06-01-2020).

I am trying to figure out the best way to structure this data so it can be easily updated via a nightly sync with their ERP.

Presently, I am storing all of the data in one table as follows:

```<code>ID (primary key) | Date | Production Cell ID | Resource
</code>```

Neither the Date, Production Cell ID, nor Resource can be Unique, as each of them will have duplicates many, many times over.

Given this, I am unclear on how to run a query to 1) check if a row exists and 2) insert or update accordingly.

Is there a better way to structure this data?

For instance, should each Production Cell be its own table with its own list of Dates?

答:
A compound unique index would serve your purposes quite well. It allows you to specify a set of columns, such that the combination of data in those columns must be unique.

For your purposes:

```<code>CREATE UNIQUE INDEX pcell_date_index
ON production_cell_data(date,cell_id);
</code>```

This assumes that you should only have one row for any combination of production cell + date.

Queries to get/update a unique row (without the ID) will need to include both columns in the where clause, but should perform very well with the index.

ContentLicense: CC BY-SA 4.0

Body:
I am building a scheduling application for a production facility.

There are 8 separate production cells in the building and, for each given day, each cell has a different production capacity (ex. production cell A has 6 people working on 06-01-2020).

I am trying to figure out the best way to structure this data so it can be easily updated via a nightly sync with their ERP.

Presently, I am storing all of the data in one table as follows:

ID (primary key) | Date | Production Cell ID | Resource

Neither the Date, Production Cell ID, nor Resource can be Unique, as each of them will have duplicates many, many times over.

Given this, I am unclear on how to run a query to 1) check if a row exists and 2) insert or update accordingly.

Is there a better way to structure this data?

For instance, should each Production Cell be its own table with its own list of Dates?

Body:
A compound unique index would serve your purposes quite well. It allows you to specify a set of columns, such that the combination of data in those columns must be unique.

For your purposes:

CREATE UNIQUE INDEX pcell_date_index
ON production_cell_data(date,cell_id);

This assumes that you should only have one row for any combination of production cell + date.

Queries to get/update a unique row (without the ID) will need to include both columns in the where clause, but should perform very well with the index.


问:
Reversing a MultiLabelBinarizer to create a list within a column
In Python3, I have a starting dataframe in the format of a multilabel binary data:

```<code>df1:

"a" "b" "c" "d" "e"

 1   1   0   0   1
 0   0   1   0   1
 1   0   0   0   0
 0   1   1   0   1
</code>```

What I need to achieve is this:

```<code>df2:

"a" "b" "c" "d" "e" "labels"

 1   1   0   0   1   ["a", "b", "e"]
 0   0   1   0   1   ["c", "e"]
 1   0   0   0   0   ["a"]
 0   1   1   0   1   ["b", "c", "e"]
</code>```

To start, I tried using the inverse_transform() function from MultiLabelBinarizer from sklearn based on this previous stack question.

```<code>from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
mlb.fit(df1.columns)
mlb.inverse_transform(df1.values)

ValueError: Expected indicator for 15 classes, but got 5
</code>```

I tried following the exact documentation from sklearn, but I am not sure where I went wrong. I tried tweaking a few of the parameters, but I do not understand what the issue is.

答:
You can stack data, filter the values, and groupby:

```<code>df['labels'] = (df.stack()
   .loc[lambda x: x>0]
   .reset_index()
   .groupby('level_0')
   .agg({'level_1':list})
)
</code>```

Output:

```<code>   "a"  "b"  "c"  "d"  "e"           labels
0    1    1    0    0    1  ["a", "b", "e"]
1    0    0    1    0    1       ["c", "e"]
2    1    0    0    0    0            ["a"]
3    0    1    1    0    1  ["b", "c", "e"]
</code>```

Body:
In Python3, I have a starting dataframe in the format of a multilabel binary data:

df1:

"a" "b" "c" "d" "e"

 1   1   0   0   1
 0   0   1   0   1
 1   0   0   0   0
 0   1   1   0   1

What I need to achieve is this:

df2:

"a" "b" "c" "d" "e" "labels"

 1   1   0   0   1   ["a", "b", "e"]
 0   0   1   0   1   ["c", "e"]
 1   0   0   0   0   ["a"]
 0   1   1   0   1   ["b", "c", "e"]

To start, I tried using the inverse_transform() function from MultiLabelBinarizer from sklearn based on this previous stack question.

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
mlb.fit(df1.columns)
mlb.inverse_transform(df1.values)

ValueError: Expected indicator for 15 classes, but got 5

I tried following the exact documentation from sklearn, but I am not sure where I went wrong. I tried tweaking a few of the parameters, but I do not understand what the issue is.

Body:
You can stack data, filter the values, and groupby:

df['labels'] = (df.stack()
   .loc[lambda x: x>0]
   .reset_index()
   .groupby('level_0')
   .agg({'level_1':list})
)

Output:

   "a"  "b"  "c"  "d"  "e"           labels
0    1    1    0    0    1  ["a", "b", "e"]
1    0    0    1    0    1       ["c", "e"]
2    1    0    0    0    0            ["a"]
3    0    1    1    0    1  ["b", "c", "e"]


问:
Create List of child objects from list of parent object
I would like to create list of child objects from list of parent object. Like If i have list of bookingroom which has one member room then i would like to create list of room from it.

eg. code:

```<code>    Dim BookingRoomList As List(Of BookingRoom) = New List(Of BookingRoom)
    Dim RoomList As List(Of Room) = New List(Of Room)

    BookingRoomList = BookingRooms.FillGrid()
    For Each BookingRoomInfo As BookingRoom In BookingRoomList
        RoomList.Add(BookingRoomInfo.RoomInfo)
    Next
</code>```

Is there any short cut method instead of iterating over for earch?

答:
You can use Linq and the AddRange method:

```<code>RoomList.AddRange(BookingRoomList.Select(Function(room) room.RoomInfo))
</code>```

Apart from that, you can shorten the declarations considerably: Dim x As T = New T() is equivalent to Dim x As New T() and you should generally prefer the latter.

Furthermore, your instantiation of BookingRoomList is completely redundant (a logical error) because you overwrite the value later on.

Finally, you can initialise the room list directly in the constructor call, or alternatively you can omit the constructor call entirely – the Linq expression already returns a fully-fledged collection. Which leaves us with:

```<code>Dim BookingRoomList As List(Of BookingRoom) = BookingRooms.FillGrid()
Dim RoomList = BookingRoomList.Select(Function(room) room.RoomInfo)).ToList()
</code>```

And that’s it.

ContentLicense: CC BY-SA 3.0

Body:
I would like to create list of child objects from list of parent object. Like If i have list of bookingroom which has one member room then i would like to create list of room from it.

eg. code:

    Dim BookingRoomList As List(Of BookingRoom) = New List(Of BookingRoom)
    Dim RoomList As List(Of Room) = New List(Of Room)

    BookingRoomList = BookingRooms.FillGrid()
    For Each BookingRoomInfo As BookingRoom In BookingRoomList
        RoomList.Add(BookingRoomInfo.RoomInfo)
    Next

Is there any short cut method instead of iterating over for earch?

Body:
You can use Linq and the AddRange method:

RoomList.AddRange(BookingRoomList.Select(Function(room) room.RoomInfo))

Apart from that, you can shorten the declarations considerably: Dim x As T = New T() is equivalent to Dim x As New T() and you should generally prefer the latter.

Furthermore, your instantiation of BookingRoomList is completely redundant (a logical error) because you overwrite the value later on.

Finally, you can initialise the room list directly in the constructor call, or alternatively you can omit the constructor call entirely – the Linq expression already returns a fully-fledged collection. Which leaves us with:

Dim BookingRoomList As List(Of BookingRoom) = BookingRooms.FillGrid()
Dim RoomList = BookingRoomList.Select(Function(room) room.RoomInfo)).ToList()

And that’s it.


问:
How to use a Ternary Operator with multiple condition in flutter dart?
how to use ternary if else with two or more condition using "OR" and "AND" like

```<code>    if(foo == 1 || foo == 2)
     {
      do something
      }
     {
      else do something
      }
</code>```

i want to use it like

```<code>  foo == 1 || foo == 2 ? doSomething : doSomething
</code>```

答:
it is easy,

```<code>if(foo == 1 || foo == 2)
 {
  do something
  }
 {
  else do something
  }
</code>```

it can be written thus for OR statement

foo==1 || foo==2 ? do something : else do something

it can be written thus for AND statement

foo==1 && foo==2 ? do something : else do something

both will work perfectly

Body:
how to use ternary if else with two or more condition using "OR" and "AND" like

    if(foo == 1 || foo == 2)
     {
      do something
      }
     {
      else do something
      }

i want to use it like

  foo == 1 || foo == 2 ? doSomething : doSomething

Body:
it is easy,

if(foo == 1 || foo == 2)
 {
  do something
  }
 {
  else do something
  }

it can be written thus for OR statement

foo==1 || foo==2 ? do something : else do something

it can be written thus for AND statement

foo==1 && foo==2 ? do something : else do something

both will work perfectly


问:
API request and Error in curl::curl_fetch_memory(url, handle = handle) : SSL certificate problem: certificate has expired
I was running the code for months without any issues, and couple days before.

```<code>GET(url="myurl", query)
</code>```

Today I've got an error

```<code>Error in curl::curl_fetch_memory(url, handle = handle) :
SSL certificate problem: certificate has expired
</code>```

The SSL cert on the site is active and ends in a year.

Also the same GET request is working via browser....

What is the issue? ♂

答:
Try testing your server with this tool: https://www.ionos.com/tools/ssl-checker and see if it says that it is "not installed correctly".

If you find that it has been working historically but recently stopped, you likely have an invalid chain of trust. Recently, a common root CA certificate expired. Your server may be using this and sending it as part of it's chain of certificates it sends to clients. If that is the case, and it is this recently-expired root CA, your fix will  most likely look like removing that root certificate from your bundle. So you'd include the intermediate certificates still, but exclude the root. You can then use these tools to revalidate if things are setup correctly.

You can also see the chain and some of the validity information using this tool: https://www.sslshopper.com/ssl-checker.html

Body:
I was running the code for months without any issues, and couple days before.

GET(url="myurl", query)

Today I've got an error

Error in curl::curl_fetch_memory(url, handle = handle) :
SSL certificate problem: certificate has expired

The SSL cert on the site is active and ends in a year.

Also the same GET request is working via browser....

What is the issue? ♂


问:
Multiple progressbar progress value incorrect android
I have a View with multiple progress bars.Individual progress bars doesnt persist their value when i switch to last tab(tab 4) and i come back.[Basically when home tab is not visible and brought to visibility again].

The progress bars are placed inside a LinearLayout which is hosted inside Fragment. Looks like Youtube app. In home page, i have 5 progress bar.
For the first time when i set progress all progress bar values looks perfect.
Individual progress bar are showing their own individual values.

However when i switch to tab 4(not in picture), i come back, all progress bar's value get set to the last progress bar's value. See Image below.

I checked by removing Progress bar with TextBox, the value persists as per set.
I have added max value to progress bar, used the methods 1. setProgress, 2. incrementProgressBy,  no improvement.

Since textbox behaves correctly ,i couldnt figure out my problem kindly help.

PS: In android Fragment(tab) gets recreated when its not visible and brought to visibility.to avoid this i made restrictions in onCreateview to persist the last created rootview.

答:
There is an accepted answer, but I ran into this same issue with multiple progress bars on different Fragments and in recycler views. My issue was related to a well observed Android progress bar bug that does not always update progress bars (see accepted answer here: android progressBar does not update progress view/drawable)

In my case I had a custom Progress Bar and added these methods to get around this bug. Sucks that we as developers have to figure this out the hard way so often.

```<code>  fun setProgressSafely(progress: Int) {
    setProgress(progress + 1)
    setProgress(progress)
}

fun setMaxSafely(max: Int) {
    setMax(max + 1)
    setMax(max)
}
</code>```

Body:
There is an accepted answer, but I ran into this same issue with multiple progress bars on different Fragments and in recycler views. My issue was related to a well observed Android progress bar bug that does not always update progress bars (see accepted answer here: android progressBar does not update progress view/drawable)

In my case I had a custom Progress Bar and added these methods to get around this bug. Sucks that we as developers have to figure this out the hard way so often.

  fun setProgressSafely(progress: Int) {
    setProgress(progress + 1)
    setProgress(progress)
}

fun setMaxSafely(max: Int) {
    setMax(max + 1)
    setMax(max)
}


问:
Tensorflow: Using Batch Normalization gives poor (erratic) validation loss and accuracy
I am trying to use Batch Normalization using tf.layers.batch_normalization() and my code looks like this:

def create_conv_exp_model(fingerprint_input, model_settings, is_training):

  # Dropout placeholder
  if is_training:
    dropout_prob = tf.placeholder(tf.float32, name='dropout_prob')

  # Mode placeholder
  mode_placeholder = tf.placeholder(tf.bool, name="mode_placeholder")

  he_init = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG")

  # Input Layer
  input_frequency_size = model_settings['bins']
  input_time_size = model_settings['spectrogram_length']
  net = tf.reshape(fingerprint_input,
                   [-1, input_time_size, input_frequency_size, 1],
                   name="reshape")
  net = tf.layers.batch_normalization(net,
                                      training=mode_placeholder,
                                      name='bn_0')

  for i in range(1, 6):
    net = tf.layers.conv2d(inputs=net,
                           filters=8*(2**i),
                           kernel_size=[5, 5],
                           padding='same',
                           kernel_initializer=he_init,
                           name="conv_%d"%i)
    net = tf.layers.batch_normalization(net,
                                        training=mode_placeholder,
                                        name='bn_%d'%i)
    with tf.name_scope("relu_%d"%i):
      net = tf.nn.relu(net)
    net = tf.layers.max_pooling2d(net, [2, 2], [2, 2], 'SAME',
                                  name="maxpool_%d"%i)

  net_shape = net.get_shape().as_list()
  net_height = net_shape[1]
  net_width = net_shape[2]
  net = tf.layers.conv2d( inputs=net,
                          filters=1024,
                          kernel_size=[net_height, net_width],
                          strides=(net_height, net_width),
                          padding='same',
                          kernel_initializer=he_init,
                          name="conv_f")
  net = tf.layers.batch_normalization( net,
                                        training=mode_placeholder,
                                        name='bn_f')
  with tf.name_scope("relu_f"):
    net = tf.nn.relu(net)

  net = tf.layers.conv2d( inputs=net,
                          filters=model_settings['label_count'],
                          kernel_size=[1, 1],
                          padding='same',
                          kernel_initializer=he_init,
                          name="conv_l")

  ### Squeeze
  squeezed = tf.squeeze(net, axis=[1, 2], name="squeezed")

  if is_training:
    return squeezed, dropout_prob, mode_placeholder
  else:
    return squeezed, mode_placeholder
```

<p>And my train step looks like this:</p>

<pre class="lang-py prettyprint-override"><code>update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
  optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate_input)
  gvs = optimizer.compute_gradients(cross_entropy_mean)
  capped_gvs = [(tf.clip_by_value(grad, -2., 2.), var) for grad, var in gvs]
  train_step = optimizer.apply_gradients(gvs))
</code>```

During training, I am feeding the graph with:

train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run(
    [
        merged_summaries, evaluation_step, cross_entropy_mean, train_step,
        increment_global_step
    ],
    feed_dict={
        fingerprint_input: train_fingerprints,
        ground_truth_input: train_ground_truth,
        learning_rate_input: learning_rate_value,
        dropout_prob: 0.5,
        mode_placeholder: True
    })
```

<p>During validation, </p>

<pre class="lang-py prettyprint-override"><code>validation_summary, validation_accuracy, conf_matrix = sess.run(
                [merged_summaries, evaluation_step, confusion_matrix],
                feed_dict={
                    fingerprint_input: validation_fingerprints,
                    ground_truth_input: validation_ground_truth,
                    dropout_prob: 1.0,
                    mode_placeholder: False
                })
</code>```

My loss and accuracy curves (orange is training, blue is validation):
Plot of loss vs number of iterations,
Plot of accuracy vs number of iterations

The validation loss (and accuracy) seem very erratic. Is my implementation of Batch Normalization wrong? Or is this normal with Batch Normalization and I should wait for more iterations?

答: I also observed oscillations in validation loss when adding batch norm before ReLU. We found that moving the batch norm after the ReLU resolved the issue.</p>

Body:
I am trying to use Batch Normalization using tf.layers.batch_normalization() and my code looks like this:

def create_conv_exp_model(fingerprint_input, model_settings, is_training):

  # Dropout placeholder
  if is_training:
    dropout_prob = tf.placeholder(tf.float32, name='dropout_prob')

  # Mode placeholder
  mode_placeholder = tf.placeholder(tf.bool, name="mode_placeholder")

  he_init = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG")

  # Input Layer
  input_frequency_size = model_settings['bins']
  input_time_size = model_settings['spectrogram_length']
  net = tf.reshape(fingerprint_input,
                   [-1, input_time_size, input_frequency_size, 1],
                   name="reshape")
  net = tf.layers.batch_normalization(net,
                                      training=mode_placeholder,
                                      name='bn_0')

  for i in range(1, 6):
    net = tf.layers.conv2d(inputs=net,
                           filters=8*(2**i),
                           kernel_size=[5, 5],
                           padding='same',
                           kernel_initializer=he_init,
                           name="conv_%d"%i)
    net = tf.layers.batch_normalization(net,
                                        training=mode_placeholder,
                                        name='bn_%d'%i)
    with tf.name_scope("relu_%d"%i):
      net = tf.nn.relu(net)
    net = tf.layers.max_pooling2d(net, [2, 2], [2, 2], 'SAME',
                                  name="maxpool_%d"%i)

  net_shape = net.get_shape().as_list()
  net_height = net_shape[1]
  net_width = net_shape[2]
  net = tf.layers.conv2d( inputs=net,
                          filters=1024,
                          kernel_size=[net_height, net_width],
                          strides=(net_height, net_width),
                          padding='same',
                          kernel_initializer=he_init,
                          name="conv_f")
  net = tf.layers.batch_normalization( net,
                                        training=mode_placeholder,
                                        name='bn_f')
  with tf.name_scope("relu_f"):
    net = tf.nn.relu(net)

  net = tf.layers.conv2d( inputs=net,
                          filters=model_settings['label_count'],
                          kernel_size=[1, 1],
                          padding='same',
                          kernel_initializer=he_init,
                          name="conv_l")

  ### Squeeze
  squeezed = tf.squeeze(net, axis=[1, 2], name="squeezed")

  if is_training:
    return squeezed, dropout_prob, mode_placeholder
  else:
    return squeezed, mode_placeholder

And my train step looks like this:

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
  optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate_input)
  gvs = optimizer.compute_gradients(cross_entropy_mean)
  capped_gvs = [(tf.clip_by_value(grad, -2., 2.), var) for grad, var in gvs]
  train_step = optimizer.apply_gradients(gvs))

During training, I am feeding the graph with:

train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run(
    [
        merged_summaries, evaluation_step, cross_entropy_mean, train_step,
        increment_global_step
    ],
    feed_dict={
        fingerprint_input: train_fingerprints,
        ground_truth_input: train_ground_truth,
        learning_rate_input: learning_rate_value,
        dropout_prob: 0.5,
        mode_placeholder: True
    })

During validation,

validation_summary, validation_accuracy, conf_matrix = sess.run(
                [merged_summaries, evaluation_step, confusion_matrix],
                feed_dict={
                    fingerprint_input: validation_fingerprints,
                    ground_truth_input: validation_ground_truth,
                    dropout_prob: 1.0,
                    mode_placeholder: False
                })

My loss and accuracy curves (orange is training, blue is validation):
Plot of loss vs number of iterations,
Plot of accuracy vs number of iterations

The validation loss (and accuracy) seem very erratic. Is my implementation of Batch Normalization wrong? Or is this normal with Batch Normalization and I should wait for more iterations?


问:
Update a rather large if statement of values to be an array
Here is a piece of JavaScript code that is rather large and clunky. I would like to take all of the setValue() code values and place it all into an array. At this point it seems as though I should just be able to take the values and place them into an array but I feel like I am skipping a step. Thanks for your help.

if (VS_group == "group") {
                                setValue('CORNER_1A_COUNT',"S06");
                                setValue('INBOARD_111_COUNT',"S06");
                                setValue('INBOARD_112_COUNT',"S06");
                                setValue('INBOARD_113_COUNT',"S06");
                                setValue('INBOARD_114_COUNT',"S06");
                                setValue('INBOARD_115_COUNT',"S06");
                                setValue('INBOARD_116_COUNT',"S06");
                                setValue('INBOARD_117_COUNT',"S06");
                                setValue('INBOARD_118_COUNT',"S06");
                                setValue('INBOARD_119_COUNT',"S06");
                                setValue('INBOARD_120_COUNT',"S06");
                                setValue('CORNER_1C_COUNT',"S06");
                                setValue('CORNER_1A',"RED");
                                setValue('INBOARD_111',"RED");
                                setValue('INBOARD_112',"RED");
                                setValue('INBOARD_113',"RED");
                                setValue('INBOARD_114',"RED");
                                setValue('INBOARD_115',"WHT");
                                setValue('INBOARD_116',"WHT");
                                setValue('INBOARD_117',"BLU");
                                setValue('INBOARD_118',"BLU");
                                setValue('INBOARD_119',"BLU");
                                setValue('INBOARD_120',"BLU");
                                setValue('CORNER_1C',"BLU");
                                setValue('ALLEY_1D_COUNT',"S06");                                                                                setValue('ALLEY_1P_COUNT',"S06");
                                setValue('ALLEY_1D',"WHT");                                                                                setValue('ALLEY_1P',"WHT");
                                setValue('CORNER_1B_COUNT',"S06");
                                setValue('INBOARD_131_COUNT',"S06");
                                setValue('INBOARD_132_COUNT',"S06");
                                setValue('INBOARD_133_COUNT',"S06");
                                setValue('INBOARD_134_COUNT',"S06");
                                setValue('INBOARD_135_COUNT',"S06");
                                setValue('INBOARD_136_COUNT',"S06");
                                setValue('INBOARD_137_COUNT',"S06");
                                setValue('INBOARD_138_COUNT',"S06");
                                setValue('INBOARD_139_COUNT',"S06");
                                setValue('INBOARD_140_COUNT',"S06");
                                setValue('CORNER_1D_COUNT',"S06");
                                setValue('CORNER_1B',"RED");
                                setValue('INBOARD_131',"RED");
                                setValue('INBOARD_132',"RED");
                                setValue('INBOARD_133',"RED");
                                setValue('INBOARD_134',"RED");
                                setValue('INBOARD_135',"RED");
                                setValue('INBOARD_136',"BLU");
                                setValue('INBOARD_137',"BLU");
                                setValue('INBOARD_138',"BLU");
                                setValue('INBOARD_139',"BLU");
                                setValue('INBOARD_140',"BLU");
                                setValue('CORNER_1D',"BLU");
                            }
```

答:
You can store these values in an array and apply a loop on that array something like that

[ ['INBOARD_140_COUNT', 'S06'], ['INBOARD_141_COUNT', 'S07'] ].forEach(([key, value] => setValue(key, value));```

When you run code snippet on StackOverflow it will give an error because "setValue()" is not defined, I wrote this just for better understanding

Body:
You can store these values in an array and apply a loop on that array something like that

[ ['INBOARD_140_COUNT', 'S06'], ['INBOARD_141_COUNT', 'S07'] ].forEach(([key, value] => setValue(key, value));

When you run code snippet on StackOverflow it will give an error because "setValue()" is not defined, I wrote this just for better understanding


问:
Xamarin: publish iOS to App Store from Visual Studio no working
I'm actively using Visual Studio 16.6 windows / 8.6.1 macOS to build and test iOS / Android application, in Xamarin Forms. macOS is running Xcode 11.

I can't push to AppStoreConnect from "Sign and Distribute" directly.

Everything is working fine step by step: build in release for iDevice, signing and distribution profile accepted, export to IPA file, and uploading via Xcode->Organizer. But i'd like to do this simply from Visual Studio; either on my PC or mac.

I have the following errors on Visual Studio / windows when uploading to AppStoreConnect:

```<code>Error: unable to create IPA file for distribution of archive myApp
MessagingRemoteException: error happened on client Build160001055 during execution of an answer for category xvs/Build/16.6.0.1055/execute-task/myApp.iOS/c1cf1c8002fCopy
TypeInitializationException: The type initializer for 'Microsoft.Build.Tasks.Copy' threw an exception.
PlatformNotSupportedException: Operation is not supported on this platform.
</code>```

I have the following error on Visual Studio / macOS when uploading to AppStoreConnect:

```<code>Publication failure: we are unable to create an authentification session.
</code>```

Notice Visual Studio / macOS is asking creds (i'm using developper account) while Visual Studio / windows is not (i surely have it registered before, but i don't remember).

答: This issue appears to have been resolved in a hotfix (16.6.1) released today, as per this bug report:  https://developercommunity.visualstudio.com/content/problem/961282/xamarinios-fails-to-build-with-messagingremoteexce.html</p>

Body:
I'm actively using Visual Studio 16.6 windows / 8.6.1 macOS to build and test iOS / Android application, in Xamarin Forms. macOS is running Xcode 11.

I can't push to AppStoreConnect from "Sign and Distribute" directly.

Everything is working fine step by step: build in release for iDevice, signing and distribution profile accepted, export to IPA file, and uploading via Xcode->Organizer. But i'd like to do this simply from Visual Studio; either on my PC or mac.

I have the following errors on Visual Studio / windows when uploading to AppStoreConnect:

Error: unable to create IPA file for distribution of archive myApp
MessagingRemoteException: error happened on client Build160001055 during execution of an answer for category xvs/Build/16.6.0.1055/execute-task/myApp.iOS/c1cf1c8002fCopy
TypeInitializationException: The type initializer for 'Microsoft.Build.Tasks.Copy' threw an exception.
PlatformNotSupportedException: Operation is not supported on this platform.

I have the following error on Visual Studio / macOS when uploading to AppStoreConnect:

Publication failure: we are unable to create an authentification session.

Notice Visual Studio / macOS is asking creds (i'm using developper account) while Visual Studio / windows is not (i surely have it registered before, but i don't remember).


问:
Median of Multiple Columns of a DF in R (all values together)
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

```<code>    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352
</code>```

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

答:
Another option is </p>

```<code>median(t(df[4:7]), na.rm = TRUE)
</code>```

Body:
I have a dataframe containing a few numeric columns and I need to get the median for all these values (all rows and columns), not by row, not by column, just one median for all values.
Although that seems simple, I could not find an explanation.

The df I have is similar to:

    rep_id  sex     activator   P16401      P81605      B7Z958      B4DT29
    CF9     Female  Control     808.3071    772.20756   14114.372   5516.857
    CF10    Female  Control     1332.5300   739.96297   19373.688   4855.419
    CF11    Female  Control     748.3975    1449.46860  17310.500   5324.638
    CF12    Female  Control     1271.5207   978.48424   6217.883    6015.900
    CF13    Female  Control     554.3564    461.37956   6659.669    5739.060
    CF14    Female  Control     1575.7039   1770.07244  7143.650    5936.352

(the number of rows and columns vary in different use cases, usually many more than this example)
I just need the median of all numerical values. The equivalent of what would be =MEDIAN(D2:G7) in Excel, but for many reasons I prefer analyzing all the data in R.
The expected result for this example would be 3312.74572

Body:
Another option is

median(t(df[4:7]), na.rm = TRUE)


问:
Insert from One Table Into Another with Where clause
I'm trying to insert values from table 2 (in the pacp2 column) into table 1 (in the pacp column) where the facility_id from both tables matches and where table1 pacp column is null.  I get the following error:

Msg 4104, Level 16, State 1, Line 5 The multi-part identifier
  "table1.FACILITYID" could not be bound. Msg 4104, Level 16, State 1,
  Line 5 The multi-part identifier "table1.pacp" could not be bound.

Does anyone know why this isn't working?  I've tried using alias for both tables but that won't work.

```<code>INSERT INTO database.dbo.table1 (pacp)
SELECT pacp2
FROM table2
WHERE database.dbo.table1.facility_id = database.dbo.table2.facility_id
    AND database.dbo.table1.pacp IS NULL
</code>```

答:
The description of your question suggests that you are looking for an update rather than an insert.

Here is one option using an updatable cte:

```<code>with cte as (
    select t1.pacp, t2.pacp2
    from table1 t1
    inner join table2 t2 on t1.facility_id = t2.facility_id
    where t1.pacp is null
)
update cte set pacp = pacp2
</code>```

For rows of table1 where pacp is null, the query attempts to retrieve the value of pacp2 from table2, using facility_id for matching. If it succeeds, then it updates the corresponding row in table1 and sets pacp to the value of pacp2.

Body:
I'm trying to insert values from table 2 (in the pacp2 column) into table 1 (in the pacp column) where the facility_id from both tables matches and where table1 pacp column is null.  I get the following error:

Msg 4104, Level 16, State 1, Line 5 The multi-part identifier
  "table1.FACILITYID" could not be bound. Msg 4104, Level 16, State 1,
  Line 5 The multi-part identifier "table1.pacp" could not be bound.

Does anyone know why this isn't working?  I've tried using alias for both tables but that won't work.

INSERT INTO database.dbo.table1 (pacp)
SELECT pacp2
FROM table2
WHERE database.dbo.table1.facility_id = database.dbo.table2.facility_id
    AND database.dbo.table1.pacp IS NULL

Body:
The description of your question suggests that you are looking for an update rather than an insert.

Here is one option using an updatable cte:

with cte as (
    select t1.pacp, t2.pacp2
    from table1 t1
    inner join table2 t2 on t1.facility_id = t2.facility_id
    where t1.pacp is null
)
update cte set pacp = pacp2

For rows of table1 where pacp is null, the query attempts to retrieve the value of pacp2 from table2, using facility_id for matching. If it succeeds, then it updates the corresponding row in table1 and sets pacp to the value of pacp2.


问:
How to create a seperate dataframe of rows that contain NaN with pandas
Is it possible to create a new dataFrame using pandas that contains any row that has NaN in any column from an existing datafram to be reviewed by a person?

I'm able to get rows that contain NaN in a specific column with:
    df_nan = df[pd.isna(df["sales_person"])]

but is there a way to do this without having to list out each column name?

答:
Here you go:

df_nan = df[df.apply(lambda row: any(pd.isna(row)), axis=1)]
```


答:
Let us try dot with str.split

```<code>df['labels'] = df.dot(df.columns+',').str[:-1].str.split(',')
0    ["a", "b", "e"]
1         ["c", "e"]
2              ["a"]
3    ["b", "c", "e"]
dtype: object
</code>```

Title: Reversing a MultiLabelBinarizer to create a list within a column

Body:
Let us try dot with str.split

df['labels'] = df.dot(df.columns+',').str[:-1].str.split(',')
0    ["a", "b", "e"]
1         ["c", "e"]
2              ["a"]
3    ["b", "c", "e"]
dtype: object


问:
rails, only admin can see json page
maybe someone did this before me, i cant handle with this.
I have system where many users, admins. Im using extJS, JSON, Rails.

So, my question is: How in rails i can do that www.mysite.com/user/54/?format=ext_json&_dc=1306937167419&start=0&limit=50&fields=["respondent[email] CAN SEE ONLY ADMINS and just average users can see text "Sorry, only admins" ??

if simple, *.json pages can see only admins.

this is my controller

```<code>  def uz
    @answers      = Question.find(params[:id])

    if session[:user].is_admin == 1

    end

    respond_to do |format|
      format.ext_json { render :json => @answers.to_ext_json(:class => Answer, :include => [:respondent]) }
    end
  end
</code>```

im tried this (create before_filter) but nothing

```<code>  def checking
    if session[:user].is_admin == 1
        WHAT TO DO HERE
    end
  end
</code>```

答:
You can create before_filter in controller where you can check format, action and session and return 404 error page

http://apidock.com/rails/ActionController/Filters/ClassMethods/before_filter

```<code>before_filter :admin_required

...

private
def admin_required

  case params[:format].to_sym
  when :ext_json
     #....redirect with eror or something if not admin
  end
end
</code>```

Title: rails, only admin can see json page

Body:
maybe someone did this before me, i cant handle with this.
I have system where many users, admins. Im using extJS, JSON, Rails.

So, my question is: How in rails i can do that www.mysite.com/user/54/?format=ext_json&_dc=1306937167419&start=0&limit=50&fields=["respondent[email] CAN SEE ONLY ADMINS and just average users can see text "Sorry, only admins" ??

if simple, *.json pages can see only admins.

this is my controller

  def uz
    @answers      = Question.find(params[:id])

    if session[:user].is_admin == 1

    end

    respond_to do |format|
      format.ext_json { render :json => @answers.to_ext_json(:class => Answer, :include => [:respondent]) }
    end
  end

im tried this (create before_filter) but nothing

  def checking
    if session[:user].is_admin == 1
        WHAT TO DO HERE
    end
  end

Body:
You can create before_filter in controller where you can check format, action and session and return 404 error page

http://apidock.com/rails/ActionController/Filters/ClassMethods/before_filter

before_filter :admin_required

...

private
def admin_required

  case params[:format].to_sym
  when :ext_json
     #....redirect with eror or something if not admin
  end
end


问:
Delete all apps and services in specific space
Is there a foundry script or command to cleanup all space apps/services, the problem that we have many apps which is related to services and you cannot delete them until you delete all apps, is there any script or command which can help ?

I dont want to hard-code all the apps and services,  is there a way for a given space delete all apps and services instances?
is it possible to make mass delete for services?

答:
The easiest thing would be to cf delete-space, wait for that to finish, then cf create-space to remake your space. The cf delete-space is recursive so it would delete everything in that space.

The only challenge might be if you have lots of people invited to your space, this would delete the space so their access would be removed and you'd need to add that back after you recreate the space.

Aside from that, you're going to need to script it.

I would try this order:

grab all the apps in the space

for each app

delete the app (this should also delete service bindings)

grab all of the service instances in the space

if you use service keys, for each service

check for service keys, if present delete them

for each service instance, delete the instance

run cf delete-orphaned-routes, that should clean up all the routes left behind

alternatively, you could use cf delete -r when you delete the app and it will delete the routes associated as well.

As far as how you get "all the apps" or "all the services", you could do something like cf apps | tail +5 | awk '{print $1}' or cf services | tail +4 | awk '{print $1}', or you could use cf curl and the API. The API will be a little trickier though because you have to deal with paging (or maybe not, if you don't have that many apps/services).


问:
Share dynamic URL link on linkedin
In HTML code I written script with data-url statically which working fine but my question is how to share link which is generated dynamically?

HTML

```<code><div>
  <script type="IN/Share" data-url="http://www.everdrobe.com/rate/551107c763eef/recent" data-counter="top" id="linked_url"></script>
</div>
</code>```

Linkedin Script

```<code><script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
</code>```

I think script executed only once at load time that's why it not working any other way Can I share?
Help should appraciate.

答:
You can share on LinkedIn using a format like so...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Sharing Documentation.

So, of course, then you can share in JS dynamically with just...

```<code>var yoururl = "yoursite.com?something=somethingelse&test=test2";

$('.share-link').html(
    '<a href="' +
    'https://www.linkedin.com/sharing/share-offsite/?url=' +
    encodeURIComponent(yoururl) +
    '">Share on LinkedIn</a>'
);
</code>```

If you want to prepolulate things like title, description, thumbnail, etc., then check out the OpenGraph tags ase described by the Official LinkedIn Shareable Documentation.

Title: Share dynamic URL link on linkedin

Body:
In HTML code I written script with data-url statically which working fine but my question is how to share link which is generated dynamically?

HTML

Linkedin Script

I think script executed only once at load time that's why it not working any other way Can I share?
Help should appraciate.

Body:
You can share on LinkedIn using a format like so...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Sharing Documentation.

So, of course, then you can share in JS dynamically with just...

var yoururl = "yoursite.com?something=somethingelse&test=test2";

$('.share-link').html(
    '<a href="' +
    'https://www.linkedin.com/sharing/share-offsite/?url=' +
    encodeURIComponent(yoururl) +
    '">Share on LinkedIn</a>'
);

If you want to prepolulate things like title, description, thumbnail, etc., then check out the OpenGraph tags ase described by the Official LinkedIn Shareable Documentation.


问:
Visual Studio Code Python Interactive Window env different from selected?
I am using visual studio code to try and replace the Spyder IDE. To replicate Spyder's variable explorer, I am trying to leverage VS code's Python Interactive Window.

Upon launching Vs Code, I select my environment using "Select Interpreter" and then picking the env. This then changes at the bottom of the application as expected.

However, when I then try and run my code in the interactive window it appears to reference a different environment? It also keeps telling me to install ipykernel.

Is this functioning correctly? I do see an option to change the env in the interactive window but that doesn't do anything.enter image description here

I found a similar question here But I have ipykernel installed in my environment so I'm not sure why it wouldn't notice that? Is there another dependency?

答:
Start off by opening your Anaconda prompt and from there activate your virtual environment (type: conda activate my_env, replacing my_env with your environment name, and hit enter.)
Then type the command: 'code', which will open up VS Code from within your active virtual environment. Before this approach, also check that your VS Code settings.json file has the python path set correctly to your environment installation. Now it should work.
To see your install path: Anaconda is installed in your user home directory: Windows 10: C:\Users\\Anaconda3\</p>


问:
How to avoid UIWebView on Firebase/Auth
I need to get a Firebase/Auth version where UIWebView has been replaced with WKWebView

After an AppStore rejection due to use of UIWebView I'm trying to update to a version of Firebase pods which are not using it. But after pod update, pod install, pod deintegrate ... the Firebase/Auth version I can get Firebase/Auth (5.20.2):

is still using UIWebView so how can I update to the latest version or any version not using UIWebView
Below my Podfile and Podfile.lock

```<code># Uncomment the next line to define a global platform for your project
#platform :ios, '9.0'

#target 'globa_jap-desktop' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for globa_jap-desktop

#end

target 'globa_jap-mobile' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
 pod 'Firebase/Core'
 pod 'Firebase/Auth'
 pod 'Firebase/Messaging'
 pod 'Firebase/Database'
 pod 'Fabric'
 pod 'Crashlytics'
 #Login UI pods
 pod 'FirebaseUI/Google'
 pod 'FirebaseUI/Twitter'

end
</code>```

Podfile.lock

```<code>PODS:
  - Crashlytics (3.14.0):
    - Fabric (~> 1.10.2)
  - Fabric (1.10.2)
  - Firebase/Auth (5.20.2):
    - Firebase/CoreOnly
    - FirebaseAuth (= 5.4.2)
  - Firebase/Core (5.20.2):
    - Firebase/CoreOnly
    - FirebaseAnalytics (= 5.8.1)
  - Firebase/CoreOnly (5.20.2):
    - FirebaseCore (= 5.4.1)
  - Firebase/Database (5.20.2):
    - Firebase/CoreOnly
    - FirebaseDatabase (= 5.1.1)
  - Firebase/Messaging (5.20.2):
    - Firebase/CoreOnly
    - FirebaseMessaging (= 3.5.0)
  - FirebaseAnalytics (5.8.1):
    - FirebaseCore (~> 5.4)
    - FirebaseInstanceID (~> 3.8)
    - GoogleAppMeasurement (= 5.8.1)
    - GoogleUtilities/AppDelegateSwizzler (~> 5.2)
    - GoogleUtilities/MethodSwizzler (~> 5.2)
    - GoogleUtilities/Network (~> 5.2)
    - "GoogleUtilities/NSData+zlib (~> 5.2)"
    - nanopb (~> 0.3)
  - FirebaseAnalyticsInterop (1.5.0)
  - FirebaseAuth (5.4.2):
    - FirebaseAuthInterop (~> 1.0)
    - FirebaseCore (~> 5.2)
    - GoogleUtilities/Environment (~> 5.2)
    - GTMSessionFetcher/Core (~> 1.1)
  - FirebaseAuthInterop (1.1.0)
  - FirebaseCore (5.4.1):
    - GoogleUtilities/Environment (~> 5.2)
    - GoogleUtilities/Logger (~> 5.2)
  - FirebaseDatabase (5.1.1):
    - FirebaseAuthInterop (~> 1.0)
    - FirebaseCore (~> 5.2)
    - leveldb-library (~> 1.18)
  - FirebaseInstanceID (3.8.1):
    - FirebaseCore (~> 5.2)
    - GoogleUtilities/Environment (~> 5.2)
    - GoogleUtilities/UserDefaults (~> 5.2)
  - FirebaseMessaging (3.5.0):
    - FirebaseAnalyticsInterop (~> 1.1)
    - FirebaseCore (~> 5.2)
    - FirebaseInstanceID (~> 3.6)
    - GoogleUtilities/Environment (~> 5.3)
    - GoogleUtilities/Reachability (~> 5.3)
    - GoogleUtilities/UserDefaults (~> 5.3)
    - Protobuf (~> 3.1)
  - FirebaseUI/Auth (6.2.1):
    - Firebase/Auth (~> 5.0)
    - GoogleUtilities/UserDefaults
  - FirebaseUI/Google (6.2.1):
    - FirebaseUI/Auth
    - GoogleSignIn (~> 4.0)
  - FirebaseUI/Twitter (6.2.1):
    - FirebaseUI/Auth
    - TwitterKit (~> 3.0)
  - GoogleAppMeasurement (5.8.1):
    - GoogleUtilities/AppDelegateSwizzler (~> 5.2)
    - GoogleUtilities/MethodSwizzler (~> 5.2)
    - GoogleUtilities/Network (~> 5.2)
    - "GoogleUtilities/NSData+zlib (~> 5.2)"
    - nanopb (~> 0.3)
  - GoogleSignIn (4.4.0):
    - "GoogleToolboxForMac/NSDictionary+URLArguments (~> 2.1)"
    - "GoogleToolboxForMac/NSString+URLArguments (~> 2.1)"
    - GTMSessionFetcher/Core (~> 1.1)
  - GoogleToolboxForMac/DebugUtils (2.2.2):
    - GoogleToolboxForMac/Defines (= 2.2.2)
  - GoogleToolboxForMac/Defines (2.2.2)
  - "GoogleToolboxForMac/NSDictionary+URLArguments (2.2.2)":
    - GoogleToolboxForMac/DebugUtils (= 2.2.2)
    - GoogleToolboxForMac/Defines (= 2.2.2)
    - "GoogleToolboxForMac/NSString+URLArguments (= 2.2.2)"
  - "GoogleToolboxForMac/NSString+URLArguments (2.2.2)"
  - GoogleUtilities/AppDelegateSwizzler (5.8.0):
    - GoogleUtilities/Environment
    - GoogleUtilities/Logger
    - GoogleUtilities/Network
  - GoogleUtilities/Environment (5.8.0)
  - GoogleUtilities/Logger (5.8.0):
    - GoogleUtilities/Environment
  - GoogleUtilities/MethodSwizzler (5.8.0):
    - GoogleUtilities/Logger
  - GoogleUtilities/Network (5.8.0):
    - GoogleUtilities/Logger
    - "GoogleUtilities/NSData+zlib"
    - GoogleUtilities/Reachability
  - "GoogleUtilities/NSData+zlib (5.8.0)"
  - GoogleUtilities/Reachability (5.8.0):
    - GoogleUtilities/Logger
  - GoogleUtilities/UserDefaults (5.8.0):
    - GoogleUtilities/Logger
  - GTMSessionFetcher/Core (1.4.0)
  - leveldb-library (1.22)
  - nanopb (0.3.9011):
    - nanopb/decode (= 0.3.9011)
    - nanopb/encode (= 0.3.9011)
  - nanopb/decode (0.3.9011)
  - nanopb/encode (0.3.9011)
  - Protobuf (3.11.4)
  - TwitterCore (3.2.0)
  - TwitterKit (3.4.2):
    - TwitterCore (>= 3.2.0)

DEPENDENCIES:
  - Crashlytics
  - Fabric
  - Firebase/Auth
  - Firebase/Core
  - Firebase/Database
  - Firebase/Messaging
  - FirebaseUI/Google
  - FirebaseUI/Twitter

SPEC REPOS:
  trunk:
    - Crashlytics
    - Fabric
    - Firebase
    - FirebaseAnalytics
    - FirebaseAnalyticsInterop
    - FirebaseAuth
    - FirebaseAuthInterop
    - FirebaseCore
    - FirebaseDatabase
    - FirebaseInstanceID
    - FirebaseMessaging
    - FirebaseUI
    - GoogleAppMeasurement
    - GoogleSignIn
    - GoogleToolboxForMac
    - GoogleUtilities
    - GTMSessionFetcher
    - leveldb-library
    - nanopb
    - Protobuf
    - TwitterCore
    - TwitterKit

SPEC CHECKSUMS:
  Crashlytics: 540b7e5f5da5a042647227a5e3ac51d85eed06df
  Fabric: 706c8b8098fff96c33c0db69cbf81f9c551d0d74
  Firebase: 0c8cf33f266410c61ab3e2265cfa412200351d9c
  FirebaseAnalytics: ece1aa57a4f43c64d53a648b5a5e05151aae947b
  FirebaseAnalyticsInterop: 3f86269c38ae41f47afeb43ebf32a001f58fcdae
  FirebaseAuth: dd7bbf03a5aee0eafb3a1aee4d2812bd74bac890
  FirebaseAuthInterop: a0f37ae05833af156e72028f648d313f7e7592e9
  FirebaseCore: f1a9a8be1aee4bf71a2fc0f4096df6788bdfda61
  FirebaseDatabase: 2c15b0ea6f2c6eb5e57413f9d6340f1e50b81ae3
  FirebaseInstanceID: a122b0c258720cf250551bb2bedf48c699f80d90
  FirebaseMessaging: 4235f949ce1c4e827aeb19705ba5c53f9b85aa10
  FirebaseUI: c9e227a7d44e2e422a461cb3f4ead8dc5c7326e6
  GoogleAppMeasurement: ffe513e90551844a739e7bcbb1d2aca1c28a4338
  GoogleSignIn: 7ff245e1a7b26d379099d3243a562f5747e23d39
  GoogleToolboxForMac: 800648f8b3127618c1b59c7f97684427630c5ea3
  GoogleUtilities: 04fce34bcd5620c1ee76fb79172105c74a4df335
  GTMSessionFetcher: 6f5c8abbab8a9bce4bb3f057e317728ec6182b10
  leveldb-library: 55d93ee664b4007aac644a782d11da33fba316f7
  nanopb: 18003b5e52dab79db540fe93fe9579f399bd1ccd
  Protobuf: 176220c526ad8bd09ab1fb40a978eac3fef665f7
  TwitterCore: 8cbc9ad34d91c63a0035ea05bfbfc0d7ca72a28c
  TwitterKit: 5e4f41d70b9abdb41df5467f52d7aa2c0fd26ebb

PODFILE CHECKSUM: cb6d407f7cb8b554f5566b911add079a3c3c3021

COCOAPODS: 1.9.1
</code>```

I tried setting the a version for Firebase/Auth in the Podfile but fails due to uncompatibility with other pods

My last try was to get the last version of FirebaseCore straight from git

pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'

but failed with the following message

```<code>[!] CocoaPods could not find compatible versions for pod "GoogleUtilities/Logger":
  In Podfile:
    FirebaseCore (from `https://github.com/firebase/firebase-ios-sdk.git`, branch `master`) was resolved to 6.7.0, which depends on
      GoogleUtilities/Logger (~> 6.5)

    FirebaseUI/Twitter was resolved to 6.2.1, which depends on
      FirebaseUI/Auth (= 6.2.1) was resolved to 6.2.1, which depends on
        GoogleUtilities/UserDefaults was resolved to 5.8.0, which depends on
          GoogleUtilities/Logger (= 5.8.0)
</code>```

Any help thanks!

Working on Xcode 11.3.1

答:
I was stuck at a very old checkout of Firebase for a long time and ran into UIWebView deprecated when I tried uploading my app. On the terminal, I went the project folder and did:

```<code>pod repo update
pod deintegrate
gem install cocoa pods
</code>```

Then ran my podfile and was able to get the latest Firebase Core 6.7.1. However, I got an error message about an include file missing.  I eventually changed that line to fetch this tag:

```<code>pod 'Firebase/Core', '~> 6.7.0'
</code>```

And that fixed the problem. There are no UIWebVew references here:

```<code>Using FirebaseAuth (6.2.3)
</code>```

Title: How to avoid UIWebView on Firebase/Auth

Body:
I need to get a Firebase/Auth version where UIWebView has been replaced with WKWebView

After an AppStore rejection due to use of UIWebView I'm trying to update to a version of Firebase pods which are not using it. But after pod update, pod install, pod deintegrate ... the Firebase/Auth version I can get Firebase/Auth (5.20.2):

is still using UIWebView so how can I update to the latest version or any version not using UIWebView
Below my Podfile and Podfile.lock

# Uncomment the next line to define a global platform for your project
#platform :ios, '9.0'

#target 'globa_jap-desktop' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for globa_jap-desktop

#end

target 'globa_jap-mobile' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
 pod 'Firebase/Core'
 pod 'Firebase/Auth'
 pod 'Firebase/Messaging'
 pod 'Firebase/Database'
 pod 'Fabric'
 pod 'Crashlytics'
 #Login UI pods
 pod 'FirebaseUI/Google'
 pod 'FirebaseUI/Twitter'

end

Podfile.lock

PODS:
  - Crashlytics (3.14.0):
    - Fabric (~> 1.10.2)
  - Fabric (1.10.2)
  - Firebase/Auth (5.20.2):
    - Firebase/CoreOnly
    - FirebaseAuth (= 5.4.2)
  - Firebase/Core (5.20.2):
    - Firebase/CoreOnly
    - FirebaseAnalytics (= 5.8.1)
  - Firebase/CoreOnly (5.20.2):
    - FirebaseCore (= 5.4.1)
  - Firebase/Database (5.20.2):
    - Firebase/CoreOnly
    - FirebaseDatabase (= 5.1.1)
  - Firebase/Messaging (5.20.2):
    - Firebase/CoreOnly
    - FirebaseMessaging (= 3.5.0)
  - FirebaseAnalytics (5.8.1):
    - FirebaseCore (~> 5.4)
    - FirebaseInstanceID (~> 3.8)
    - GoogleAppMeasurement (= 5.8.1)
    - GoogleUtilities/AppDelegateSwizzler (~> 5.2)
    - GoogleUtilities/MethodSwizzler (~> 5.2)
    - GoogleUtilities/Network (~> 5.2)
    - "GoogleUtilities/NSData+zlib (~> 5.2)"
    - nanopb (~> 0.3)
  - FirebaseAnalyticsInterop (1.5.0)
  - FirebaseAuth (5.4.2):
    - FirebaseAuthInterop (~> 1.0)
    - FirebaseCore (~> 5.2)
    - GoogleUtilities/Environment (~> 5.2)
    - GTMSessionFetcher/Core (~> 1.1)
  - FirebaseAuthInterop (1.1.0)
  - FirebaseCore (5.4.1):
    - GoogleUtilities/Environment (~> 5.2)
    - GoogleUtilities/Logger (~> 5.2)
  - FirebaseDatabase (5.1.1):
    - FirebaseAuthInterop (~> 1.0)
    - FirebaseCore (~> 5.2)
    - leveldb-library (~> 1.18)
  - FirebaseInstanceID (3.8.1):
    - FirebaseCore (~> 5.2)
    - GoogleUtilities/Environment (~> 5.2)
    - GoogleUtilities/UserDefaults (~> 5.2)
  - FirebaseMessaging (3.5.0):
    - FirebaseAnalyticsInterop (~> 1.1)
    - FirebaseCore (~> 5.2)
    - FirebaseInstanceID (~> 3.6)
    - GoogleUtilities/Environment (~> 5.3)
    - GoogleUtilities/Reachability (~> 5.3)
    - GoogleUtilities/UserDefaults (~> 5.3)
    - Protobuf (~> 3.1)
  - FirebaseUI/Auth (6.2.1):
    - Firebase/Auth (~> 5.0)
    - GoogleUtilities/UserDefaults
  - FirebaseUI/Google (6.2.1):
    - FirebaseUI/Auth
    - GoogleSignIn (~> 4.0)
  - FirebaseUI/Twitter (6.2.1):
    - FirebaseUI/Auth
    - TwitterKit (~> 3.0)
  - GoogleAppMeasurement (5.8.1):
    - GoogleUtilities/AppDelegateSwizzler (~> 5.2)
    - GoogleUtilities/MethodSwizzler (~> 5.2)
    - GoogleUtilities/Network (~> 5.2)
    - "GoogleUtilities/NSData+zlib (~> 5.2)"
    - nanopb (~> 0.3)
  - GoogleSignIn (4.4.0):
    - "GoogleToolboxForMac/NSDictionary+URLArguments (~> 2.1)"
    - "GoogleToolboxForMac/NSString+URLArguments (~> 2.1)"
    - GTMSessionFetcher/Core (~> 1.1)
  - GoogleToolboxForMac/DebugUtils (2.2.2):
    - GoogleToolboxForMac/Defines (= 2.2.2)
  - GoogleToolboxForMac/Defines (2.2.2)
  - "GoogleToolboxForMac/NSDictionary+URLArguments (2.2.2)":
    - GoogleToolboxForMac/DebugUtils (= 2.2.2)
    - GoogleToolboxForMac/Defines (= 2.2.2)
    - "GoogleToolboxForMac/NSString+URLArguments (= 2.2.2)"
  - "GoogleToolboxForMac/NSString+URLArguments (2.2.2)"
  - GoogleUtilities/AppDelegateSwizzler (5.8.0):
    - GoogleUtilities/Environment
    - GoogleUtilities/Logger
    - GoogleUtilities/Network
  - GoogleUtilities/Environment (5.8.0)
  - GoogleUtilities/Logger (5.8.0):
    - GoogleUtilities/Environment
  - GoogleUtilities/MethodSwizzler (5.8.0):
    - GoogleUtilities/Logger
  - GoogleUtilities/Network (5.8.0):
    - GoogleUtilities/Logger
    - "GoogleUtilities/NSData+zlib"
    - GoogleUtilities/Reachability
  - "GoogleUtilities/NSData+zlib (5.8.0)"
  - GoogleUtilities/Reachability (5.8.0):
    - GoogleUtilities/Logger
  - GoogleUtilities/UserDefaults (5.8.0):
    - GoogleUtilities/Logger
  - GTMSessionFetcher/Core (1.4.0)
  - leveldb-library (1.22)
  - nanopb (0.3.9011):
    - nanopb/decode (= 0.3.9011)
    - nanopb/encode (= 0.3.9011)
  - nanopb/decode (0.3.9011)
  - nanopb/encode (0.3.9011)
  - Protobuf (3.11.4)
  - TwitterCore (3.2.0)
  - TwitterKit (3.4.2):
    - TwitterCore (>= 3.2.0)

DEPENDENCIES:
  - Crashlytics
  - Fabric
  - Firebase/Auth
  - Firebase/Core
  - Firebase/Database
  - Firebase/Messaging
  - FirebaseUI/Google
  - FirebaseUI/Twitter

SPEC REPOS:
  trunk:
    - Crashlytics
    - Fabric
    - Firebase
    - FirebaseAnalytics
    - FirebaseAnalyticsInterop
    - FirebaseAuth
    - FirebaseAuthInterop
    - FirebaseCore
    - FirebaseDatabase
    - FirebaseInstanceID
    - FirebaseMessaging
    - FirebaseUI
    - GoogleAppMeasurement
    - GoogleSignIn
    - GoogleToolboxForMac
    - GoogleUtilities
    - GTMSessionFetcher
    - leveldb-library
    - nanopb
    - Protobuf
    - TwitterCore
    - TwitterKit

SPEC CHECKSUMS:
  Crashlytics: 540b7e5f5da5a042647227a5e3ac51d85eed06df
  Fabric: 706c8b8098fff96c33c0db69cbf81f9c551d0d74
  Firebase: 0c8cf33f266410c61ab3e2265cfa412200351d9c
  FirebaseAnalytics: ece1aa57a4f43c64d53a648b5a5e05151aae947b
  FirebaseAnalyticsInterop: 3f86269c38ae41f47afeb43ebf32a001f58fcdae
  FirebaseAuth: dd7bbf03a5aee0eafb3a1aee4d2812bd74bac890
  FirebaseAuthInterop: a0f37ae05833af156e72028f648d313f7e7592e9
  FirebaseCore: f1a9a8be1aee4bf71a2fc0f4096df6788bdfda61
  FirebaseDatabase: 2c15b0ea6f2c6eb5e57413f9d6340f1e50b81ae3
  FirebaseInstanceID: a122b0c258720cf250551bb2bedf48c699f80d90
  FirebaseMessaging: 4235f949ce1c4e827aeb19705ba5c53f9b85aa10
  FirebaseUI: c9e227a7d44e2e422a461cb3f4ead8dc5c7326e6
  GoogleAppMeasurement: ffe513e90551844a739e7bcbb1d2aca1c28a4338
  GoogleSignIn: 7ff245e1a7b26d379099d3243a562f5747e23d39
  GoogleToolboxForMac: 800648f8b3127618c1b59c7f97684427630c5ea3
  GoogleUtilities: 04fce34bcd5620c1ee76fb79172105c74a4df335
  GTMSessionFetcher: 6f5c8abbab8a9bce4bb3f057e317728ec6182b10
  leveldb-library: 55d93ee664b4007aac644a782d11da33fba316f7
  nanopb: 18003b5e52dab79db540fe93fe9579f399bd1ccd
  Protobuf: 176220c526ad8bd09ab1fb40a978eac3fef665f7
  TwitterCore: 8cbc9ad34d91c63a0035ea05bfbfc0d7ca72a28c
  TwitterKit: 5e4f41d70b9abdb41df5467f52d7aa2c0fd26ebb

PODFILE CHECKSUM: cb6d407f7cb8b554f5566b911add079a3c3c3021

COCOAPODS: 1.9.1

I tried setting the a version for Firebase/Auth in the Podfile but fails due to uncompatibility with other pods

My last try was to get the last version of FirebaseCore straight from git

pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'

but failed with the following message

[!] CocoaPods could not find compatible versions for pod "GoogleUtilities/Logger":
  In Podfile:
    FirebaseCore (from `https://github.com/firebase/firebase-ios-sdk.git`, branch `master`) was resolved to 6.7.0, which depends on
      GoogleUtilities/Logger (~> 6.5)

    FirebaseUI/Twitter was resolved to 6.2.1, which depends on
      FirebaseUI/Auth (= 6.2.1) was resolved to 6.2.1, which depends on
        GoogleUtilities/UserDefaults was resolved to 5.8.0, which depends on
          GoogleUtilities/Logger (= 5.8.0)

Any help thanks!

Working on Xcode 11.3.1

Body:
I was stuck at a very old checkout of Firebase for a long time and ran into UIWebView deprecated when I tried uploading my app. On the terminal, I went the project folder and did:

pod repo update
pod deintegrate
gem install cocoa pods

Then ran my podfile and was able to get the latest Firebase Core 6.7.1. However, I got an error message about an include file missing.  I eventually changed that line to fetch this tag:

pod 'Firebase/Core', '~> 6.7.0'

And that fixed the problem. There are no UIWebVew references here:

Using FirebaseAuth (6.2.3)


问:
android studio recyclerview firebase not showing data
l am try to build Android book store project using Firebase Database and recyclerview to display my data . But the problem is when i run my app i have empty activity without any error .

RecyclerViewActivity java:

```<code>package sky.ex.ai.booksstore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class RecyclerViewActivity extends AppCompatActivity {

    RecyclerView rviwe;
    ArrayList<BookDetails> plist;
    ItemAdapter itemAdapter;
    FirebaseDatabase fb;
    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        rviwe = findViewById(R.id.recycler_view);
        plist = new ArrayList<BookDetails>();
        fb = FirebaseDatabase.getInstance();
        ref = fb.getReference("Library");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){

                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));

                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
        LinearLayoutManager im = new LinearLayoutManager((this));
        rviwe.setLayoutManager(im);
        itemAdapter = new ItemAdapter(plist);
        rviwe.setAdapter(itemAdapter);

    }
}
</code>```

activity_recycler_view xml

```<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=".RecyclerViewActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Item layout xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="138dp"
        android:layout_height="59dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/book" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="10dp">

        <TextView
            android:id="@+id/book_name_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book name" />

        <TextView
            android:id="@+id/book_author_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book Author" />

        <TextView
            android:id="@+id/book_price_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book price" />
    </LinearLayout>
</LinearLayout>
</code>```

Book Details Class

```<code>package sky.ex.ai.booksstore;

    public class BookDetails {

       String bkAuthor;
       String bkname;

        public BookDetails() {
        }

       public BookDetails(String bkname, String bkAuthor){
           this.bkAuthor = bkAuthor;
           this.bkname = bkname;
       }

        public String getBkAuthor() {
            return bkAuthor;
        }

        public void setBkAuthor(String bkAuthor) {
            this.bkAuthor = bkAuthor;
        }

        public String getBkname() {
            return bkname;
        }

        public void setBkname(String bkname) {
            this.bkname = bkname;
        }
    }
</code>```

Item Adapter java

```<code>package sky.ex.ai.booksstore
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    public ArrayList<BookDetails> itemlist;

    public ItemAdapter(ArrayList<BookDetails> itemlist) {
        this.itemlist = itemlist;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater
                .from(viewGroup.getContext()).inflate(R.layout.item_layot,viewGroup, false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
        holder.txt_pname.setText("Book Name :" +itemlist.get(i).bkname);
        holder.txt_pid.setText("Book Author :" +itemlist.get(i).bkAuthor);
    }

    @Override
    public int getItemCount() {
        if (itemlist==null)
            return 0;
        else  return itemlist.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public ImageButton imgb1;
        public TextView txt_pid,txt_pname,txt_pric;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_pid = itemView.findViewById(R.id.book_name_list);
            txt_pname = itemView.findViewById(R.id.book_author_list);
        }
    }

}
</code>```

Database structure

any idea please ?

答:
After getting data, call notifyDataSetChanged() on the adapter

```<code>    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds:dataSnapshot.getChildren()){

                BookDetails p = ds.getValue(BookDetails.class);
                plist.add(new BookDetails(p.bkname,p.bkAuthor));

                Log.i("THE_CURRENT_USER:::", p.toString());
            }
        itemAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
</code>```

Body:
l am try to build Android book store project using Firebase Database and recyclerview to display my data . But the problem is when i run my app i have empty activity without any error .

RecyclerViewActivity java:

package sky.ex.ai.booksstore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class RecyclerViewActivity extends AppCompatActivity {

    RecyclerView rviwe;
    ArrayList<BookDetails> plist;
    ItemAdapter itemAdapter;
    FirebaseDatabase fb;
    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        rviwe = findViewById(R.id.recycler_view);
        plist = new ArrayList<BookDetails>();
        fb = FirebaseDatabase.getInstance();
        ref = fb.getReference("Library");

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds:dataSnapshot.getChildren()){

                    BookDetails p = ds.getValue(BookDetails.class);
                    plist.add(new BookDetails(p.bkname,p.bkAuthor));

                    Log.i("THE_CURRENT_USER:::", p.toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
        LinearLayoutManager im = new LinearLayoutManager((this));
        rviwe.setLayoutManager(im);
        itemAdapter = new ItemAdapter(plist);
        rviwe.setAdapter(itemAdapter);

    }
}

activity_recycler_view xml

<?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=".RecyclerViewActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Item layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="138dp"
        android:layout_height="59dp"
        android:layout_weight="1"
        app:srcCompat="@drawable/book" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="10dp">

        <TextView
            android:id="@+id/book_name_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book name" />

        <TextView
            android:id="@+id/book_author_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book Author" />

        <TextView
            android:id="@+id/book_price_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Book price" />
    </LinearLayout>
</LinearLayout>

Book Details Class

package sky.ex.ai.booksstore;

    public class BookDetails {

       String bkAuthor;
       String bkname;

        public BookDetails() {
        }

       public BookDetails(String bkname, String bkAuthor){
           this.bkAuthor = bkAuthor;
           this.bkname = bkname;
       }

        public String getBkAuthor() {
            return bkAuthor;
        }

        public void setBkAuthor(String bkAuthor) {
            this.bkAuthor = bkAuthor;
        }

        public String getBkname() {
            return bkname;
        }

        public void setBkname(String bkname) {
            this.bkname = bkname;
        }
    }

Item Adapter java

package sky.ex.ai.booksstore
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    public ArrayList<BookDetails> itemlist;

    public ItemAdapter(ArrayList<BookDetails> itemlist) {
        this.itemlist = itemlist;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater
                .from(viewGroup.getContext()).inflate(R.layout.item_layot,viewGroup, false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
        holder.txt_pname.setText("Book Name :" +itemlist.get(i).bkname);
        holder.txt_pid.setText("Book Author :" +itemlist.get(i).bkAuthor);
    }

    @Override
    public int getItemCount() {
        if (itemlist==null)
            return 0;
        else  return itemlist.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        public ImageButton imgb1;
        public TextView txt_pid,txt_pname,txt_pric;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            txt_pid = itemView.findViewById(R.id.book_name_list);
            txt_pname = itemView.findViewById(R.id.book_author_list);
        }
    }

}

Database structure

any idea please ?

Body:
After getting data, call notifyDataSetChanged() on the adapter

    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds:dataSnapshot.getChildren()){

                BookDetails p = ds.getValue(BookDetails.class);
                plist.add(new BookDetails(p.bkname,p.bkAuthor));

                Log.i("THE_CURRENT_USER:::", p.toString());
            }
        itemAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }


问:
Express.js doesn't register some of the endpoints in other env
This is the code of my index.ts. I build it with TS "build": "tsc -p ./tsconfig.json && cp -R ./src/adminUI ./dist"

```<code>const db = mongoose.connection;
const app = express();

// TODO: whitelist
app.use(cors());
app.use(auth);
app.use('/static', express.static(path.join(__dirname, 'adminUI')));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use((req, _, next) => {
    console.log(req.path);
    console.log('Time: ', Date.now());
    next();
});

app.use('/api', endpoints);
app.use('/que', UI);
app.use('/admin', adminUI);

// START APP AFTER DB IS CONNECTED
db.once('open', () => {
    app.listen(process.env.port || 3010, () => console.log(`Listening on port ${process.env.port || 3010}!`));
    routesList.terminal(app);

    new Queue().start(+process.env.cronTime || null);
});

db.on('error', err => dbDebugger('connection error:', err));

// CONNECT TO THE DB
mongoose.connect(`mongodb://${process.env.mongoAuth || ''}${process.env.mongoHost}/admin`);
</code>```

When I run it locally I have all of the endpoints

```<code>      List All Routes        |
|------------------------------|
| Method |         URI         |
|--------|---------------------|
| GET    | api/items           |
| GET    | api/bank            |
| GET    | api/bank/:id        |
| POST   | api/bank            |
| POST   | api/bank/update     |
| POST   | api/bank/remove     |
| POST   | api/parser          |
| GET    | api/parser          |
| GET    | api/parser/bank/:id |
| GET    | api/parser/:id      |
| POST   | api/parser/update   |
| POST   | api/parser/remove   |
| POST   | api/test            |
| GET    | admin               |
| GET    | admin/updatebank    |
| GET    | admin/updateparser
</code>```

When I run it on prod server with the same deps and node js, I get these endpoints

```<code>.-----------------------------.
0|index    | |       List All Routes       |
0|index    | |-----------------------------|
0|index    | | Method |        URI         |
0|index    | |--------|--------------------|
0|index    | | GET    | api                |
0|index    | | GET    | admin              |
0|index    | | GET    | admin/updatebank   |
0|index    | | GET    | admin/updateparser |
0|index    | '-----------------------------'
</code>```

And funny but I don't' have api/ endpoint, it somehome redirects to /api/items

答:
If this truly is an issue of env vars preventing the registering of certain routes, check everywhere that an env var is used near when routes are registered or attached to the app.

Enabling debugging with express might help you understand what's going on.

You mention the problem occurs when you run it on your prod server. What if you run it locally but first set NODE_ENV to production? If this is an issue of env vars, try narrowing down which one could be causing it by incrementally setting them in your own local environment.

My suspicion is that this is not an issue relating to env. It could be, but that seems unlikely.

Body:
This is the code of my index.ts. I build it with TS "build": "tsc -p ./tsconfig.json && cp -R ./src/adminUI ./dist"

const db = mongoose.connection;
const app = express();

// TODO: whitelist
app.use(cors());
app.use(auth);
app.use('/static', express.static(path.join(__dirname, 'adminUI')));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());

app.use((req, _, next) => {
    console.log(req.path);
    console.log('Time: ', Date.now());
    next();
});

app.use('/api', endpoints);
app.use('/que', UI);
app.use('/admin', adminUI);

// START APP AFTER DB IS CONNECTED
db.once('open', () => {
    app.listen(process.env.port || 3010, () => console.log(`Listening on port ${process.env.port || 3010}!`));
    routesList.terminal(app);

    new Queue().start(+process.env.cronTime || null);
});

db.on('error', err => dbDebugger('connection error:', err));

// CONNECT TO THE DB
mongoose.connect(`mongodb://${process.env.mongoAuth || ''}${process.env.mongoHost}/admin`);

When I run it locally I have all of the endpoints

      List All Routes        |
|------------------------------|
| Method |         URI         |
|--------|---------------------|
| GET    | api/items           |
| GET    | api/bank            |
| GET    | api/bank/:id        |
| POST   | api/bank            |
| POST   | api/bank/update     |
| POST   | api/bank/remove     |
| POST   | api/parser          |
| GET    | api/parser          |
| GET    | api/parser/bank/:id |
| GET    | api/parser/:id      |
| POST   | api/parser/update   |
| POST   | api/parser/remove   |
| POST   | api/test            |
| GET    | admin               |
| GET    | admin/updatebank    |
| GET    | admin/updateparser

When I run it on prod server with the same deps and node js, I get these endpoints

.-----------------------------.
0|index    | |       List All Routes       |
0|index    | |-----------------------------|
0|index    | | Method |        URI         |
0|index    | |--------|--------------------|
0|index    | | GET    | api                |
0|index    | | GET    | admin              |
0|index    | | GET    | admin/updatebank   |
0|index    | | GET    | admin/updateparser |
0|index    | '-----------------------------'

And funny but I don't' have api/ endpoint, it somehome redirects to /api/items


问:
SQL Join two query

I need some help combining these two queries so I can get this in one single view.

Query 1

```<code>select t.*, n.caption, n.description
from (
    select NodeID,
              count(distinct cpuindex) as number_of_cpu,
                case
                           When count(distinct cpuindex) < 8 THEN 1
                           Else count(distinct cpuindex)/8
                           End AS number_of_cores
    from CPUMultiLoad_Detail (nolock) where nodeid in (select nodeid from nodesdata)
       group by NodeID
   ) as t
inner join NodesData as n (nolock) on n.nodeid = t.nodeid
where n.description NOT Like '%Windows%'
order by n.description
</code>```

Query 2

```<code>SELECT D.Environment, B.Name, C.Caption, A.ComponentStatisticData, A.ErrorMessage
FROM [APM_CurrentStatistics] A, APM_Application B, NodesData C
join NodesCustomProperties D on D.NodeID= C.NodeID
WHERE
A.ApplicationID=B.ID AND
A.NodeID=C.NodeID AND
B.Name IN ('Oracle Database Licensing')
</code>```

I want to join first query and second query so I have CPU Information and Licensing Information in same table. How do I join both query? We can use common key Nodes.NodeID to join and not sure how. Any help will be greatly appreciated.

答:
Consider joining the inner aggregate subquery of first query which holds distinct NodeID to the second query using a CTE. Additionally, use explicit JOIN(current standard in SQL) and heed bad habits to kick : using table aliases like (a, b, c) and use more informative table aliases.

```<code>WITH agg AS
   (
    select NodeID,
           count(distinct cpuindex) as number_of_cpu,
           case
               when count(distinct cpuindex) < 8 THEN 1
               else count(distinct cpuindex) / 8
           end AS number_of_cores
    from CPUMultiLoad_Detail
    where nodeid in (select nodeid from nodesdata)
    group by NodeID
   )

SELECT cp.Environment, app.Name, n.Caption,
       cs.ComponentStatisticData, cs.ErrorMessage,
       agg.NodeID, agg.number_of_cpu, agg.number_of_cores, n.description
FROM APM_CurrentStatistics cs
INNER JOIN APM_Application app
  ON cs.ApplicationID = app.ID
  AND app.Name IN ('Oracle Database Licensing')
INNER JOIN NodesData n
  ON cs.NodeID = n.NodeID
  AND n.description NOT LIKE '%Windows%'
INNER JOIN NodesCustomProperties cp
  ON cp.NodeID = n.NodeID
INNER JOIN agg
  ON cs.NodeID = agg.NodeID
ORDER BY n.description
</code>```

Title: SQL Join two query

Body:
I need some help combining these two queries so I can get this in one single view.

Query 1

select t.*, n.caption, n.description
from (
    select NodeID,
              count(distinct cpuindex) as number_of_cpu,
                case
                           When count(distinct cpuindex) < 8 THEN 1
                           Else count(distinct cpuindex)/8
                           End AS number_of_cores
    from CPUMultiLoad_Detail (nolock) where nodeid in (select nodeid from nodesdata)
       group by NodeID
   ) as t
inner join NodesData as n (nolock) on n.nodeid = t.nodeid
where n.description NOT Like '%Windows%'
order by n.description

Query 2

SELECT D.Environment, B.Name, C.Caption, A.ComponentStatisticData, A.ErrorMessage
FROM [APM_CurrentStatistics] A, APM_Application B, NodesData C
join NodesCustomProperties D on D.NodeID= C.NodeID
WHERE
A.ApplicationID=B.ID AND
A.NodeID=C.NodeID AND
B.Name IN ('Oracle Database Licensing')

I want to join first query and second query so I have CPU Information and Licensing Information in same table. How do I join both query? We can use common key Nodes.NodeID to join and not sure how. Any help will be greatly appreciated.

Body:
Consider joining the inner aggregate subquery of first query which holds distinct NodeID to the second query using a CTE. Additionally, use explicit JOIN(current standard in SQL) and heed bad habits to kick : using table aliases like (a, b, c) and use more informative table aliases.

WITH agg AS
   (
    select NodeID,
           count(distinct cpuindex) as number_of_cpu,
           case
               when count(distinct cpuindex) < 8 THEN 1
               else count(distinct cpuindex) / 8
           end AS number_of_cores
    from CPUMultiLoad_Detail
    where nodeid in (select nodeid from nodesdata)
    group by NodeID
   )

SELECT cp.Environment, app.Name, n.Caption,
       cs.ComponentStatisticData, cs.ErrorMessage,
       agg.NodeID, agg.number_of_cpu, agg.number_of_cores, n.description
FROM APM_CurrentStatistics cs
INNER JOIN APM_Application app
  ON cs.ApplicationID = app.ID
  AND app.Name IN ('Oracle Database Licensing')
INNER JOIN NodesData n
  ON cs.NodeID = n.NodeID
  AND n.description NOT LIKE '%Windows%'
INNER JOIN NodesCustomProperties cp
  ON cp.NodeID = n.NodeID
INNER JOIN agg
  ON cs.NodeID = agg.NodeID
ORDER BY n.description


问:
How do I add custom actions to a change model form in Django Admin?
I'm working with Django admin, and I'd like to be able to use an existing instance of a model as a template for making a new object, so people using django admin don't need to re-key all the same properties on a object, when making new objects.

I'm picturing it a bit like this at the bottom of the Django admin form for updating a single object:

The django docs explain how to add bulk actions, by adding to the actions on a model, like so:

```<code>class ArticleAdmin(admin.ModelAdmin):

    actions = ['make_published']

    def make_published(self, request, queryset):
        queryset.update(status='p')

    make_published.short_description = "Mark selected stories as published"
</code>```

However, it wasn't so clear to me how to do this for a single change model form on an object, for actions I only want to apply to model at a time.

How would I do this?

I'm guessing I probably need to hack around with the change_model form, but beyond that, I'm not so sure.

Is there a fast way to do this without overriding loads of templates ?

答:
As pointed out, there is not a way and needs to be hacked. Here's I think an elegant hack for adding custom actions to both the list and change form views. It doesn't actually save the form just execute whatever custom action you want against the current object and return you back to the same change form page.

from django.db.models import Model

from django.contrib import admin, messages
from django.contrib.admin.options import (
    unquote,
    csrf_protect_m,
    HttpResponseRedirect,
)

class ArticleAdmin(admin.ModelAdmin):
    change_form_template = 'book/admin_change_form_book.html'

    actions = ['make_published']

    def make_published(self, request, queryset):
        if isinstance(queryset, Model):
            obj = queryset
            obj.status = 'p'
            obj.save()
            updated_count = 1
        else:
            updated_count = queryset.update(status='p')

        msg = "Marked {} new objects from existing".format(updated_count)
        self.message_user(request, msg, messages.SUCCESS)

    make_published.short_description = "Mark selected stories as published"

    @csrf_protect_m
    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        if request.method == 'POST' and '_make_published' in request.POST:
            obj = self.get_object(request, unquote(object_id))
            self.make_published(request, obj)
            return HttpResponseRedirect(request.get_full_path())

        return admin.ModelAdmin.changeform_view(
            self, request,
            object_id=object_id,
            form_url=form_url,
            extra_context=extra_context,
        )

```

<p>Now you can add an <code><input></code> for the action to the custom template view (this example uses <code>book/admin_change_form_book.html</code> in change_form_template)</p>

<pre class="lang-html prettyprint-override"><code>{% extends 'admin/change_form.html' %}

{% block form_top %}
<input
    type="submit"
    name="_make_published"
    value="Mark Published"
    class="grp-button grp-default"
>
{% endblock %}
</code>```

If you look at the admin/change_form.html (i.e. "django/contrib/admin/templates/admin/change_form.html") you can insert this custom <input> action anywhere between the <form...> </form> tags on the page. Including these blocks:

{% block form_top %}

{% block after_related_objects %}

{% block submit_buttons_bottom %}

Body:
I'm working with Django admin, and I'd like to be able to use an existing instance of a model as a template for making a new object, so people using django admin don't need to re-key all the same properties on a object, when making new objects.

I'm picturing it a bit like this at the bottom of the Django admin form for updating a single object:

The django docs explain how to add bulk actions, by adding to the actions on a model, like so:

class ArticleAdmin(admin.ModelAdmin):

    actions = ['make_published']

    def make_published(self, request, queryset):
        queryset.update(status='p')

    make_published.short_description = "Mark selected stories as published"

However, it wasn't so clear to me how to do this for a single change model form on an object, for actions I only want to apply to model at a time.

How would I do this?

I'm guessing I probably need to hack around with the change_model form, but beyond that, I'm not so sure.

Is there a fast way to do this without overriding loads of templates ?

Body:
As pointed out, there is not a way and needs to be hacked. Here's I think an elegant hack for adding custom actions to both the list and change form views. It doesn't actually save the form just execute whatever custom action you want against the current object and return you back to the same change form page.

from django.db.models import Model

from django.contrib import admin, messages
from django.contrib.admin.options import (
    unquote,
    csrf_protect_m,
    HttpResponseRedirect,
)

class ArticleAdmin(admin.ModelAdmin):
    change_form_template = 'book/admin_change_form_book.html'

    actions = ['make_published']

    def make_published(self, request, queryset):
        if isinstance(queryset, Model):
            obj = queryset
            obj.status = 'p'
            obj.save()
            updated_count = 1
        else:
            updated_count = queryset.update(status='p')

        msg = "Marked {} new objects from existing".format(updated_count)
        self.message_user(request, msg, messages.SUCCESS)

    make_published.short_description = "Mark selected stories as published"

    @csrf_protect_m
    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        if request.method == 'POST' and '_make_published' in request.POST:
            obj = self.get_object(request, unquote(object_id))
            self.make_published(request, obj)
            return HttpResponseRedirect(request.get_full_path())

        return admin.ModelAdmin.changeform_view(
            self, request,
            object_id=object_id,
            form_url=form_url,
            extra_context=extra_context,
        )

Now you can add an <input> for the action to the custom template view (this example uses book/admin_change_form_book.html in change_form_template)

{% extends 'admin/change_form.html' %}

{% block form_top %}
<input
    type="submit"
    name="_make_published"
    value="Mark Published"
    class="grp-button grp-default"
>
{% endblock %}

If you look at the admin/change_form.html (i.e. "django/contrib/admin/templates/admin/change_form.html") you can insert this custom <input> action anywhere between the <form...> </form> tags on the page. Including these blocks:

{% block form_top %}

{% block after_related_objects %}

{% block submit_buttons_bottom %}


问:
How to update a clicked element using useState
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

```<code>const [backgroundColor, setBackgroundColor] = useState({background: "green"});
</code>```

in my function I have something like this:

```<code>function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}
</code>```

then in my return JSX code I have

```<code>{subButtons.map(function(subButton, index){
   return (<div key={index} onClick={updateBackground} style={backgroundColor}>{subButton}</div>)
 })}
</code>```

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

答:
You should use array instead single background object. Like this:

```<code>const subButtons = ['button1', 'button2', 'button3']
const [backgroundColors, setBackgroundColor] = useState(subButtons.map(() => { return { background: "green" } }))

function updateBackground(index){
  let newBackgroundColors = [...backgroundColors]
  newBackgroundColors[index] = { background: "blue" }
  setBackgroundColor([...newBackgroundColors])
}

return (subButtons.map(function(subButton, index){
 return (<div key={index} onClick={()=>updateBackground(index)} style={backgroundColors[index]}>{subButton}</div>)
}))
</code>```

See in playground: https://jscomplete.com/playground/s505358

Body:
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

const [backgroundColor, setBackgroundColor] = useState({background: "green"});

in my function I have something like this:

function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}

then in my return JSX code I have

{subButtons.map(function(subButton, index){
   return (
{subButton}
)
 })}

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

Body:
You should use array instead single background object. Like this:

const subButtons = ['button1', 'button2', 'button3']
const [backgroundColors, setBackgroundColor] = useState(subButtons.map(() => { return { background: "green" } }))

function updateBackground(index){
  let newBackgroundColors = [...backgroundColors]
  newBackgroundColors[index] = { background: "blue" }
  setBackgroundColor([...newBackgroundColors])
}

return (subButtons.map(function(subButton, index){
 return (<div key={index} onClick={()=>updateBackground(index)} style={backgroundColors[index]}>{subButton}</div>)
}))

See in playground: https://jscomplete.com/playground/s505358