问:
putting conditions to my presentation controller from retrieved data firebase
im using presentation controller and i want it to appear only if the area name is (king saud university) or (king khalid airport) and the (isAvailable == true ) and the value of sensor is true.
im using different values for each area so i assign them with 1 or 2. attached is a screen shot of my firebase and my code. what do you suggest so i can solve the problem [sensors database][1]?
[areas database][2]</p>
```<code>            let storyboard = UIStoryboard(name: "Main", bundle: nil)
                            let viewController = storyboard.instantiateViewController(withIdentifier: "ConfirmAndPay")

                            if let presentationController = viewController.presentationController as? UISheetPresentationController {
                                presentationController.detents = [.medium()] /// change to [.medium(), .large()] for a half and full screen sheet
                            }
            let ref = Database.database().reference()
            ref.child("Areas").observeSingleEvent(of:
               .childAdded, with: { (snapshot) in

              let value = snapshot.value as? NSDictionary
                let isAvailable = value?["isAvailable"] as? Double ?? 0.0
                let areaname = value?["areaname"] as? String ?? ""
                print(isAvailable)
                print(areaname)

            ref.child("Sensors").observeSingleEvent(of: .value, with: { [self] (snapshot) in

              let value = snapshot.value as? NSDictionary
              let Value1 = value?["Value1"] as? Double ?? 0.0
              let Value2 = value?["Value"] as? Double ?? 0.0

                if  areaname == "King Saud University" && isAvailable == 1 && Value1 == 1  {
                    self.present(viewController, animated: true)
                } else if areaname == "King Khalid Airport" && isAvailable == 1 && Value2 == 1  {
                    self.present(viewController, animated: true)
                }else if isAvailable == 0 {
                    let cell = self.ParkingsViews.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
                    cell.layer.borderColor = UIColor.red.cgColor
                    cell.Alert.text = "No Available Parkings"
                }

            })})
        } ```

  [1]: https://i.stack.imgur.com/tqcHR.png
  [2]: https://i.stack.imgur.com/Qz3VS.png
</code>```

答:
You are trying to parse for a key called isAvailable

let isAvailable = value?["isAvailable"] as? Double ?? 0.0

But your key is not isAvailable, it is isAvailable1 and isAvailable2

Make sure you are checking for the right keys. Because of this your if conditions are always false and no view controllers get presented.

As I mentioned earlier in the comments, the way to debug these kinds of issues is to add breakpoints in your if / else blocks to check which path your code goes into and figure out why it is not going into your desired path.

Here is how to add breakpoints

Body:
im using presentation controller and i want it to appear only if the area name is (king saud university) or (king khalid airport) and the (isAvailable == true ) and the value of sensor is true.
im using different values for each area so i assign them with 1 or 2. attached is a screen shot of my firebase and my code. what do you suggest so i can solve the problem [sensors database][1]?
[areas database][2]

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
                            let viewController = storyboard.instantiateViewController(withIdentifier: "ConfirmAndPay")

                            if let presentationController = viewController.presentationController as? UISheetPresentationController {
                                presentationController.detents = [.medium()] /// change to [.medium(), .large()] for a half and full screen sheet
                            }
            let ref = Database.database().reference()
            ref.child("Areas").observeSingleEvent(of:
               .childAdded, with: { (snapshot) in

              let value = snapshot.value as? NSDictionary
                let isAvailable = value?["isAvailable"] as? Double ?? 0.0
                let areaname = value?["areaname"] as? String ?? ""
                print(isAvailable)
                print(areaname)

            ref.child("Sensors").observeSingleEvent(of: .value, with: { [self] (snapshot) in

              let value = snapshot.value as? NSDictionary
              let Value1 = value?["Value1"] as? Double ?? 0.0
              let Value2 = value?["Value"] as? Double ?? 0.0

                if  areaname == "King Saud University" && isAvailable == 1 && Value1 == 1  {
                    self.present(viewController, animated: true)
                } else if areaname == "King Khalid Airport" && isAvailable == 1 && Value2 == 1  {
                    self.present(viewController, animated: true)
                }else if isAvailable == 0 {
                    let cell = self.ParkingsViews.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
                    cell.layer.borderColor = UIColor.red.cgColor
                    cell.Alert.text = "No Available Parkings"
                }

            })})
        } ```

  [1]: https://i.stack.imgur.com/tqcHR.png
  [2]: https://i.stack.imgur.com/Qz3VS.png


来源: stackexchange

问:
How to know the position and the size of a SVG path after having changed the stroke width?
After changing with javascript the stroke-with of a path of a svg, the drawing exceeds the width and the height of the ViewBox.
But I want the path including its stroke to be fully visible in the ViewBox.

var p2 = document.getElementById('p2');
p2.setAttribute("stroke-width", "20");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg1">
  <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p1"
     d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" />
</svg>

<svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg2">
  <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p2"
     d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" />
</svg></code>```

How to know the size of the path including the stroke ? Then I could change the size of the ViewBox.

How to know the position (negative position, I guess) of the path including the stroke ? Then I could add the attribute transform (translate).

Thank you.

答:
You can use getBBox to get the bounds of a path but it ignores the stroke witdth. Adding the stroke width to the resulting bounds can help to some extent as you can see in the snippet, but you cannot count on it.

The red square represents the original bounds and the blue one is an enlarged original one (stroke with added to the each side):

const box = d3.select('path').node().getBBox();
console.log(box);

d3.select('svg')
    .append('rect')
  .attr('x', box.x)
  .attr('y', box.y)
  .attr('width', box.width)
  .attr('height', box.height)
  .style('stroke', 'red')
  .style('fill', 'none')

 d3.select('svg')
    .append('rect')
  .attr('x', box.x - 10)
  .attr('y', box.y - 10)
  .attr('width', box.width + 20)
  .attr('height', box.height + 20)
  .style('stroke', 'blue')
  .style('fill', 'none')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="250" height="200">
  <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="black" fill="none" stroke-width="10" />
  <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="white" fill="none" stroke-width="1" />
</svg></code>```

ContentLicense: CC BY-SA 4.0

Body:
After changing with javascript the stroke-with of a path of a svg, the drawing exceeds the width and the height of the ViewBox.
But I want the path including its stroke to be fully visible in the ViewBox.

var p2 = document.getElementById('p2');
p2.setAttribute("stroke-width", "20");

<svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg1">
  <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p1"
     d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" />
</svg>

<svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg2">
  <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p2"
     d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" />
</svg>

How to know the size of the path including the stroke ? Then I could change the size of the ViewBox.

How to know the position (negative position, I guess) of the path including the stroke ? Then I could add the attribute transform (translate).

Thank you.

Body:
You can use getBBox to get the bounds of a path but it ignores the stroke witdth. Adding the stroke width to the resulting bounds can help to some extent as you can see in the snippet, but you cannot count on it.

The red square represents the original bounds and the blue one is an enlarged original one (stroke with added to the each side):

const box = d3.select('path').node().getBBox();
console.log(box);

d3.select('svg')
    .append('rect')
  .attr('x', box.x)
  .attr('y', box.y)
  .attr('width', box.width)
  .attr('height', box.height)
  .style('stroke', 'red')
  .style('fill', 'none')

 d3.select('svg')
    .append('rect')
  .attr('x', box.x - 10)
  .attr('y', box.y - 10)
  .attr('width', box.width + 20)
  .attr('height', box.height + 20)
  .style('stroke', 'blue')
  .style('fill', 'none')

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="250" height="200">
  <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="black" fill="none" stroke-width="10" />
  <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="white" fill="none" stroke-width="1" />
</svg>


问:
Is there a way to access to a twitter user's following stream programmatically?
Months ago, Twitter added a new feature to enable us to see the following stream of a specific user. (see TechCrunch news - Now You Can See Twitter The Way I See Twitter).

I cannot find the official api for such data and wandering if such data can be obtained programmatically.

答:
It is the first one here:
https://dev.twitter.com/docs/api

https://dev.twitter.com/docs/api/1/get/statuses/home_timeline

ContentLicense: CC BY-SA 3.0


问:
making a data.frame igraph compatible by creating edgelist from location data
I am currently working on a project visualizing a network of think tank board members and their respective boards. The data I have is in the following format:

```<code>     name edge
1    A    1
2    A    2
3    A    3
4    B    4
5    B    5
6    C    6
</code>```

However, to make it compatible for igraphs graph_from_data_frame() function, I would need the following format:

```<code>   name from to
1    A    1  2
2    A    1  3
3    A    2  3
4    B    4  5
5    C    6  0
</code>```

I have already tried

```<code> df1 <- setDT(df1)[, list(edge = toString(edge)), name]
 df1 <- separate(df1, "edge", c("X", "Y", "Z"))
</code>```

yielding

```<code>  name X    Y    Z
1:    A 1    2    3
2:    B 4    5 <NA>
3:    C 6 <NA> <NA>
</code>```

However, I do not know how to get from this (or the initial format) to the required format to use graph_from_data_frame()
I hope you can help me. Thanks in advance

答:
You could use combn by each name with a small case handling.

```<code>by(dat, dat$name, \(x) {
  e <- x$edge
  if (length(e) == 1L) e <- c(e, 0L)
  cbind(x$name[1L], t(combn(e, 2L)))
}) |>
  do.call(what=rbind.data.frame) |>
  setNames(c('name', 'from', 'to'))
#     name from to
# A.1    A    1  2
# A.2    A    1  3
# A.3    A    2  3
# B      B    4  5
# C      C    6  0
</code>```

Note: R >= 4.1 used.

Data:

```<code>dat <- structure(list(name = c("A", "A", "A", "B", "B", "C"), edge = 1:6), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
</code>```

Body:
I am currently working on a project visualizing a network of think tank board members and their respective boards. The data I have is in the following format:

     name edge
1    A    1
2    A    2
3    A    3
4    B    4
5    B    5
6    C    6

However, to make it compatible for igraphs graph_from_data_frame() function, I would need the following format:

   name from to
1    A    1  2
2    A    1  3
3    A    2  3
4    B    4  5
5    C    6  0

I have already tried

 df1 <- setDT(df1)[, list(edge = toString(edge)), name]
 df1 <- separate(df1, "edge", c("X", "Y", "Z"))

yielding

  name X    Y    Z
1:    A 1    2    3
2:    B 4    5 <NA>
3:    C 6 <NA> <NA>

However, I do not know how to get from this (or the initial format) to the required format to use graph_from_data_frame()
I hope you can help me. Thanks in advance

Body:
You could use combn by each name with a small case handling.

by(dat, dat$name, \(x) {
  e <- x$edge
  if (length(e) == 1L) e <- c(e, 0L)
  cbind(x$name[1L], t(combn(e, 2L)))
}) |>
  do.call(what=rbind.data.frame) |>
  setNames(c('name', 'from', 'to'))
#     name from to
# A.1    A    1  2
# A.2    A    1  3
# A.3    A    2  3
# B      B    4  5
# C      C    6  0

Note: R >= 4.1 used.

Data:

dat <- structure(list(name = c("A", "A", "A", "B", "B", "C"), edge = 1:6), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))


问:
Purpose of "resolveJsonModule"?
The setting I am referencing is shown in the snippet bellow

```<code>{
  "compilerOptions": {
    "resolveJsonModule": true,
  }
}

</code>```

I don't really understand why TS language engineers would add a flag for "resolveJsonModule"? Either an environment supports resolving JSON as module via an import statement (or require() method), or the environment doesn't. Why bother with the extra complexity?

答:
Context

Historically, Node has included a specialized JSON loader (unrelated to ECMA standards) to allow importing JSON data only in CommonJS mode.

Standardized importing of anything at all (ES modules) is only a relatively recent phenomenon in ECMAScript. Importing text files containing valid JSON, parsed as native JS data ("importing JSON") is described in a proposal that is still only in stage 3.

However, there has been recent movement in regard to implementation of the above mentioned proposal:

V8 implemented it in June (Chrome 91+)

TypeScipt v4.5.0 implemented it in November

Deno v1.17.0 implemented it in December

Node LTS v16.14.0 implemented it last Tuesday (behind a CLI flag --experimental-json-modules)

TypeScript

TypeScript is a static type-checker, but also a compiler (technically a transpiler), and transforms your TS source code syntax into a syntax that is valid JavaScript for the runtime environment you have specified in your TSConfig. Because there are different runtime environments with different capabilities, the way that you configure the compiler affects the transformed JavaScript that is emitted. In regard to defaults, the compiler uses an algorithmic logic to determine settings. (I can't summarize that here: you honestly have to read the entire reference in order to understand it.) Because loading of JSON data has been a non-standard, specialized operation until extremely recently, it has not been a default.

Alternatives

All JS runtimes offer alternatives to an import statment for importing of textual JSON data (which can then be parsed using JSON.parse), and none of them require configuring the compiler in the ways that you asked about:

Note: the data parsed from the JSON strings imported using these methods will not participate in the "automatic" type inference capabilities of the compiler module graph because they aren't part of the compilation graph: so they'll be typed as any (or possibly unknown in an extremely strict configuration).

Browser and Deno: window.fetch

Deno: Deno.readTextFile

Node: fs.readFile

Additionally, because all JSON (JavaScript Object Notation) is valid JS, you can simply prepend the data in your JSON file with export default , and then save the file as data.js instead of data.json, and then import it as a standard module: import {default as data} from './data.js';.

Final notes about inferred types:

I prefer to audit the JSON I'm importing and use my own manually-written types (written either by myself or someone else: imported from a module/declaration file) for the data, rather than relying on the compiler's inferred types from import statements (which I have found to be too narrow on many occasions), by assigning the parsed JSON data to a new variable using a type assertion.

Title: Purpose of "resolveJsonModule"?

Body:
The setting I am referencing is shown in the snippet bellow

{
  "compilerOptions": {
    "resolveJsonModule": true,
  }
}

I don't really understand why TS language engineers would add a flag for "resolveJsonModule"? Either an environment supports resolving JSON as module via an import statement (or require() method), or the environment doesn't. Why bother with the extra complexity?


问:
Add buff only in one end of a manim line / arrow
I am connecting two rectangles with a line with a tip or an arrow (it doesn't matter which one). I only want buff at the end of the arrow, not both start and end.

from manim import *

class MyScene(Scene):
    def construct(self):
        rect1 = Rectangle(color=WHITE, height=0.75, width=1.5).to_edge(LEFT)
        rect2 = Rectangle(color=WHITE, height=0.75, width=1.5).next_to(rect1, buff=1.5)

        arrow = Line(start=rect1.get_right(), end=rect2.get_left(), buff=0.1).add_tip()
        # Or
        # arrow = Arrow(start=rect1.get_right(), end=rect2.get_left(), buff=0.1)

        self.play(Create(rect1))
        self.play(Create(rect2))
        self.play(Create(arrow))
        self.wait(2)
```

As you can see in the picture, there is a buff between the left rectangle and the arrow and the right rectangle and the arrow. I only want the second one.

One solution that comes to mind is that I set buff=0 and change the end position of the arrow to create the desired buff manually, but I was hoping to find a better and cleaner solution.

答: Unfortunately buff is a symmetric quantity. You'll have to modify the end points manually to get the desired effect.

Body:
I am connecting two rectangles with a line with a tip or an arrow (it doesn't matter which one). I only want buff at the end of the arrow, not both start and end.

from manim import *

class MyScene(Scene):
    def construct(self):
        rect1 = Rectangle(color=WHITE, height=0.75, width=1.5).to_edge(LEFT)
        rect2 = Rectangle(color=WHITE, height=0.75, width=1.5).next_to(rect1, buff=1.5)

        arrow = Line(start=rect1.get_right(), end=rect2.get_left(), buff=0.1).add_tip()
        # Or
        # arrow = Arrow(start=rect1.get_right(), end=rect2.get_left(), buff=0.1)

        self.play(Create(rect1))
        self.play(Create(rect2))
        self.play(Create(arrow))
        self.wait(2)

As you can see in the picture, there is a buff between the left rectangle and the arrow and the right rectangle and the arrow. I only want the second one.

One solution that comes to mind is that I set buff=0 and change the end position of the arrow to create the desired buff manually, but I was hoping to find a better and cleaner solution.


问:
How to fix this code? i tried WITH statement but it gave me an error
I tried to answer this question here in the code below, but it keeps giving me an error message!
I've tried to figure out how to

Provide the name of the sales_rep in each region with the largest amount of total_amt_usd sales?

and it gave me this Error :

aggregate function calls cannot be nested
ERD picture here

could you please help me with this?

```<code>WITH
    account_info AS (Select * from accounts),
    orders_info AS (select * from orders),
    region_info AS (select * from region),
    sales_reps_info AS (select * from sales_reps)

    SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders_info o
    JOIN account_info a
    ON o.account_id = a.id

    JOIN sales_reps_info s
    ON a.sales_rep_id = s.id

    JOIN region_info r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC
</code>```

答:
When you are using the whole table there is no need for WITH</p>
```<code>SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders o
    JOIN account a
    ON o.account_id = a.id

    JOIN sales_reps s
    ON a.sales_rep_id = s.id

    JOIN region r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC
    LIMIT 100;
</code>```

Body:
I tried to answer this question here in the code below, but it keeps giving me an error message!
I've tried to figure out how to

Provide the name of the sales_rep in each region with the largest amount of total_amt_usd sales?

and it gave me this Error :

aggregate function calls cannot be nested
ERD picture here

could you please help me with this?

WITH
    account_info AS (Select * from accounts),
    orders_info AS (select * from orders),
    region_info AS (select * from region),
    sales_reps_info AS (select * from sales_reps)

    SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders_info o
    JOIN account_info a
    ON o.account_id = a.id

    JOIN sales_reps_info s
    ON a.sales_rep_id = s.id

    JOIN region_info r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC

Body:
When you are using the whole table there is no need for WITH

SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders o
    JOIN account a
    ON o.account_id = a.id

    JOIN sales_reps s
    ON a.sales_rep_id = s.id

    JOIN region r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC
    LIMIT 100;


问:
High precision in training and validation but low precision in test
Hi to everyone!!

I have a problem with my model.
I am training a CNN with transfer learning using the MobileNet base model.
My dataset is made up of 3 classes "paper, scissors, rock" (8751 images, and all class are perfectly balanced) and I use it to create a hand gesture recognition model for the "paper, scissors, rock" game.

In the training phase with keras I get excellent results both with the training set and with the test set (accuracy, precision, AUC all more or less on 0.98%):

This is the last epochs.

When I go to use the validation set, these metrics have a very low result:

I think this could be due to overfitting and that I should do some tuning on my model, in fact through augmentation I increase the number of images in my dataset and then I try to modify the base model of the MobileNet by adding layers.

But things are not getting better ... Can you help me? I'm going crazy.
This is my model training code:

```<code>import matplotlib.pyplot as plt
import tensorflow
from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import keras
from keras.metrics import Precision, Recall

from collections import Counter

IMAGE_SIZE = (224, 224)
IMG_SHAPE = IMAGE_SIZE + (3,)
TRAIN_DATASET_DIR = "/content/PAPER_SCISSOR_ROCK/TRAIN"
TEST_DATASET_DIR = "/content/PAPER_SCISSOR_ROCK/TEST"
NUM_CLASSES = 3
BATCH_SIZE = 16
EPOCHS = 40
FC_LAYERS = [512, 512, 256, 256]
DROPOUT = 0.4
LEARNING_RATE = 0.0001

train_datagen = ImageDataGenerator(
    vertical_flip=True,
    validation_split=0.20,
    rescale=1. / 255,
    fill_mode = 'wrap',
    rotation_range = 45,
    brightness_range=[0.2,1.0]
    #brightness_range=[1, 2],
    #preprocessing_function = keras.applications.mobilenet.preprocess_input
)

# ONLY FOR TEST, SPLITT IN VALIDATION AND TEST IMAGES (TO CALCULATE PRECSION AND CONFUSION MATRIX AFTER)
test_datagen = ImageDataGenerator(
    rescale=1./255,
    validation_split=0.3
)

train_generator = train_datagen.flow_from_directory(
    TRAIN_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    shuffle=True
)

val_generator = test_datagen.flow_from_directory(
    TEST_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    subset='training',
    shuffle=True
)

test_generator = test_datagen.flow_from_directory(
    TEST_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    subset="validation",
    shuffle=True
)

def build_finetune_model(base_model, dropout, fc_layers, num_classes):
    # prevents weights from being updated in a given layer during training.
    for layer in base_model.layers:
      layer.trainable = False
    # THE NEW PART SUGGESTED
    for layer in base_model.layers[-30:]:
      layer.trainable=True

    for layer in base_model.layers:
      if "BatchNormalization" in layer.__class__.__name__:
        layer.trainable = False

    x = base_model.output
    x = Flatten()(x)
    for fc in fc_layers:
      print(fc)
      x = Dense(fc, activation='relu')(x)
      x = Dropout(dropout)(x)
    preditions = Dense(num_classes, activation='softmax')(x)
    finetune_model = Model(inputs = base_model.input, outputs = preditions)
    return finetune_model

mobielNetV2 = tensorflow.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')

finetune_model = build_finetune_model(mobielNetV2, dropout = DROPOUT, fc_layers = FC_LAYERS, num_classes = NUM_CLASSES)

finetune_model.compile(tensorflow.keras.optimizers.Adam(learning_rate=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy', 'AUC', Precision(), Recall()])

# Imposed EarlyStopping, in any era in which the model is seen to overfit, it stops.
es = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
r = finetune_model.fit_generator(train_generator, validation_data=val_generator, epochs=EPOCHS, steps_per_epoch=len(train_generator)/BATCH_SIZE,
              validation_steps=len(test_generator), callbacks=[es])
print("\nSAVE THE MODEL")

finetune_model.save(f"/content/drive/My Drive/Computer_Vision/Models/MobileNet_ScissorPaperRock_{EPOCHS}_epochs.h5")

</code>```

EDITED

This is the code about how I calculate the precision, recall and f1-scor of validation set:

```<code>import numpy as np
from sklearn.metrics import classification_report

# test_steps_per_epoch = np.math.ceil(val_generator.samples / val_generator.batch_size)
# print(test_steps_per_epoch)

predictions = finetune_model.predict(val_generator)
# Get most likely class
predicted_classes = np.argmax(predictions, axis=1)
print(val_generator, len(val_generator))
# Get ground-truth classes and class-labels
true_classes = val_generator.classes
#print(true_classes)
class_labels = list(val_generator.class_indices.keys())
#print(class_labels)

# Use scikit-learn to get statistics
report = classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)

</code>```

答: Since you are fine-tuning a MobileNet V2 model, then it is a good idea to update the weights of the last few layers. MobileNet V2 is trained to classify 1000 differnet classes, but your domain contains only 3 classes of similar features. The first few layers are usually used for the general features, while the last few layers are less general, and those would affect your model the most since your domain is a lot smaller. I'd suggest that you allow the last 20%-30% layers of MobileNet V2 to update weights.</p>

Body:
Hi to everyone!!

I have a problem with my model.
I am training a CNN with transfer learning using the MobileNet base model.
My dataset is made up of 3 classes "paper, scissors, rock" (8751 images, and all class are perfectly balanced) and I use it to create a hand gesture recognition model for the "paper, scissors, rock" game.

In the training phase with keras I get excellent results both with the training set and with the test set (accuracy, precision, AUC all more or less on 0.98%):

This is the last epochs.

When I go to use the validation set, these metrics have a very low result:

I think this could be due to overfitting and that I should do some tuning on my model, in fact through augmentation I increase the number of images in my dataset and then I try to modify the base model of the MobileNet by adding layers.

But things are not getting better ... Can you help me? I'm going crazy.
This is my model training code:

import matplotlib.pyplot as plt
import tensorflow
from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import keras
from keras.metrics import Precision, Recall

from collections import Counter

IMAGE_SIZE = (224, 224)
IMG_SHAPE = IMAGE_SIZE + (3,)
TRAIN_DATASET_DIR = "/content/PAPER_SCISSOR_ROCK/TRAIN"
TEST_DATASET_DIR = "/content/PAPER_SCISSOR_ROCK/TEST"
NUM_CLASSES = 3
BATCH_SIZE = 16
EPOCHS = 40
FC_LAYERS = [512, 512, 256, 256]
DROPOUT = 0.4
LEARNING_RATE = 0.0001

train_datagen = ImageDataGenerator(
    vertical_flip=True,
    validation_split=0.20,
    rescale=1. / 255,
    fill_mode = 'wrap',
    rotation_range = 45,
    brightness_range=[0.2,1.0]
    #brightness_range=[1, 2],
    #preprocessing_function = keras.applications.mobilenet.preprocess_input
)

# ONLY FOR TEST, SPLITT IN VALIDATION AND TEST IMAGES (TO CALCULATE PRECSION AND CONFUSION MATRIX AFTER)
test_datagen = ImageDataGenerator(
    rescale=1./255,
    validation_split=0.3
)

train_generator = train_datagen.flow_from_directory(
    TRAIN_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    shuffle=True
)

val_generator = test_datagen.flow_from_directory(
    TEST_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    subset='training',
    shuffle=True
)

test_generator = test_datagen.flow_from_directory(
    TEST_DATASET_DIR,
    target_size=IMAGE_SIZE,
    batch_size=BATCH_SIZE,
    class_mode="categorical",
    subset="validation",
    shuffle=True
)

def build_finetune_model(base_model, dropout, fc_layers, num_classes):
    # prevents weights from being updated in a given layer during training.
    for layer in base_model.layers:
      layer.trainable = False
    # THE NEW PART SUGGESTED
    for layer in base_model.layers[-30:]:
      layer.trainable=True

    for layer in base_model.layers:
      if "BatchNormalization" in layer.__class__.__name__:
        layer.trainable = False

    x = base_model.output
    x = Flatten()(x)
    for fc in fc_layers:
      print(fc)
      x = Dense(fc, activation='relu')(x)
      x = Dropout(dropout)(x)
    preditions = Dense(num_classes, activation='softmax')(x)
    finetune_model = Model(inputs = base_model.input, outputs = preditions)
    return finetune_model

mobielNetV2 = tensorflow.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet')

finetune_model = build_finetune_model(mobielNetV2, dropout = DROPOUT, fc_layers = FC_LAYERS, num_classes = NUM_CLASSES)

finetune_model.compile(tensorflow.keras.optimizers.Adam(learning_rate=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy', 'AUC', Precision(), Recall()])

# Imposed EarlyStopping, in any era in which the model is seen to overfit, it stops.
es = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
r = finetune_model.fit_generator(train_generator, validation_data=val_generator, epochs=EPOCHS, steps_per_epoch=len(train_generator)/BATCH_SIZE,
              validation_steps=len(test_generator), callbacks=[es])
print("\nSAVE THE MODEL")

finetune_model.save(f"/content/drive/My Drive/Computer_Vision/Models/MobileNet_ScissorPaperRock_{EPOCHS}_epochs.h5")

EDITED

This is the code about how I calculate the precision, recall and f1-scor of validation set:

import numpy as np
from sklearn.metrics import classification_report

# test_steps_per_epoch = np.math.ceil(val_generator.samples / val_generator.batch_size)
# print(test_steps_per_epoch)

predictions = finetune_model.predict(val_generator)
# Get most likely class
predicted_classes = np.argmax(predictions, axis=1)
print(val_generator, len(val_generator))
# Get ground-truth classes and class-labels
true_classes = val_generator.classes
#print(true_classes)
class_labels = list(val_generator.class_indices.keys())
#print(class_labels)

# Use scikit-learn to get statistics
report = classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)


问:
(Discord selfbot) Is there anyway to response if 'hi' in someone message
Is there anyway to make the selfbot response 'hello' if 'hi' is in someone message?
Like

A: hi? Anyone here?
The bot: hello

The bot response because 'hi' is in A's message.
I think it's not possible because i tried many Discord selfbot library and none of library  work (Python)

答:
Here's the code

---Starts From Here:---

```<code>// type `await lib.` to display API autocomplete
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});

// Only respond to messages containing "hi", "hey", "hello", or "sup"
if (context.params.event.content.match(/hi|hey|hello|sup/i)) {
  let messageContent = context.params.event.content.match(/hi|hey|hello|sup/i);

  await lib.discord.channels['@0.3.0'].messages.create({
    channel_id: context.params.event.channel_id,
    content: `${messageContent[0]} to you too `,
    message_reference: {
      message_id: context.params.event.id
    }
  });
}
</code>```

--Ends--

Image of code

I suggest using autocode.com it will really help you in coding life. I use it myself.

Here's a small guide https://autocode.com/guides/how-to-build-a-discord-bot/

Body:
Here's the code

---Starts From Here:---

// type `await lib.` to display API autocomplete
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});

// Only respond to messages containing "hi", "hey", "hello", or "sup"
if (context.params.event.content.match(/hi|hey|hello|sup/i)) {
  let messageContent = context.params.event.content.match(/hi|hey|hello|sup/i);

  await lib.discord.channels['@0.3.0'].messages.create({
    channel_id: context.params.event.channel_id,
    content: `${messageContent[0]} to you too `,
    message_reference: {
      message_id: context.params.event.id
    }
  });
}

--Ends--

Image of code

I suggest using autocode.com it will really help you in coding life. I use it myself.

Here's a small guide https://autocode.com/guides/how-to-build-a-discord-bot/


问:
How to get name of a specific item in array and increment its value
I am working on a simple cart, for a homework project. I would like to ask, what would be the best way to take an item from array and increment its value by one? I have 25 items in the array, and each of them has unique name, so I am not using any IDs. Would it be possible to take these items by their name value?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Nákupný košík</title>

//Database with items

let basket = [];

let products = [
{
   type: "mb",
   name: "Asus Motherboard",
   price: "320",
   link: "products/asusmb.html",
   image: "/Eshop_project/img/asusmb.jfif",
},

{
   type: "cpu",
   name: "Intel Core i3",
   price: "150",
   image: "../img/corei3.jfif",
},

{
   type: "cpu",
   name: "Intel Core i5",
   price: "300",
   image: "../img/corei5.jfif",
},

{
   type: "cpu",
   name: "Intel Core i7",
   price: "450",
   image: "../img/corei7.jfif",
},

{
   type: "cpu",
   name: "Intel Core i9",
   price: "600",
   image: "../img/corei9.jfif",
},

{
   type: "ram",
   name: "Corsair 16gb",
   price: "80",
   image: "../img/corsair16gb.jfif",
},

{
   type: "psu",
   name: "Corsair PSU",
   price: "100",
   image: "../img/corsairpsu.jfif",
},

{
   type: "ram",
   name: "Crucial 32gb",
   price: "160",
   image: "../img/crucial32gb.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX3070",
   price: "750",
   image: "../img/gforce 3070.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3080",
   price: "950",
   image: "../img/gforce_3080.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3090",
   price: "1200",
   image: "../img/gforce_3090.jfif",
},

{
   type: "mb",
   name: "Gigabyte Motherboard",
   price: "400",
   image: "../img/gigabytemb.jfif",
},

{
   type: "psu",
   name: "Gigabyte PSU",
   price: "80",
   image: "../img/gigabytepsu.jfif",
},

{
   type: "ram",
   name: "Kingston 16gb",
   price: "90",
   image: "../img/kingston16gb.jfif",
},

{
   type: "mb",
   name: "MSI Motherboard",
   price: "300",
   image: "../img/msimb.jfif",
},

{
   type: "case",
   name: "Phanteks Case",
   price: "70",
   image: "../img/Phaktekscase.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6500",
   price: "500",
   image: "../img/radeon_6500.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6800",
   price: "650",
   image: "../img/radeon_6800.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6900",
   price: "800",
   image: "../img/radeon_6900.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 3790",
   price: "400",
   image: "../img/ryzen3790.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5600",
   price: "550",
   image: "../img/ryzen5600.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5800",
   price: "700",
   image: "../img/ryzen5800.jfif",
},

{
   type: "psu",
   name: "Seasonic PSU",
   price: "95",
   image: "../img/seasonicpsu.jfif",
},

{
   type: "case",
   name: "Zalmancase",
   price: "90",
   image: "../img/zalmancase.jfif",
},

{
   type: "psu",
   name: "Evga PSU",
   price: "80",
   image: "../img/evgapsu.jfif",
}

]
localStorage.setItem('products', JSON.stringify(products));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
You can use the uniq name like Id and do something like

```<code>const changeInArr = (name, newValue) => {
const newArr = yourArray.map(elem => {
if (name === item.name) {
item.value = newValue
}
return item
}
return newer
}
</code>```

If you need change different field, you can use a key parameter like that :

```<code>const changeInArr = (name, newValue, key) => {
const newArr = yourArray.map(elem => {
if (name === item.name) {
item[key] = newValue
}
return item
}
return newer
}
</code>```

Say me if work for you

Body:
You can use the uniq name like Id and do something like

const changeInArr = (name, newValue) => {
const newArr = yourArray.map(elem => {
if (name === item.name) {
item.value = newValue
}
return item
}
return newer
}

If you need change different field, you can use a key parameter like that :

const changeInArr = (name, newValue, key) => {
const newArr = yourArray.map(elem => {
if (name === item.name) {
item[key] = newValue
}
return item
}
return newer
}

Say me if work for you


问:
Batch insertion of spreadsheet cells using gdata-objectivec-client not working
I am trying to add a batch of cells to a Google Spreadsheet using the GData Objective-C Client as described here: http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction#Batch_requests.

Here is the code of interest:

```<code>                      GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];
                  NSURL *batchUrl = [[batchFeed batchLink] URL];

                  NSMutableArray *cells = [NSMutableArray array];

                  GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                  GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];
                  [cells addObject:cellEntry];
                  [batchFeed setEntries:cells];

                  GDataBatchOperation *op;
                  op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                  [batchFeed setBatchOperation:op];

                  [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl completionHandler:nil];
</code>```

It doesn't work.  Clearly, the fetchFeedWithBatchFeed has no reference to my GDataWorksheetEntry object -- so it doesn't surprise me that it isn't working.

What am I leaving out?

Thanks in advance.

答:
I solved this problem and exposed a new issue.

First, the solution.  Once you have a GDataWorksheetEntry, this code will perform a batch operation -- in this case an insert:

```<code>                      NSURL *cellsFeedUrl = [[worksheetEntry cellsLink] URL];

                  // Get worksheet cells feed
                  [service fetchFeedWithURL:cellsFeedUrl completionHandler:
                   ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                       NSURL *batchUrl = [[feed batchLink] URL];
                       GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];

                       NSMutableArray *cells = [NSMutableArray array];

                       GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                       GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];

                       static unsigned int staticID = 0;
                       NSString *batchID = [NSString stringWithFormat:@"batchID_%u", ++staticID];
                       [cellEntry setBatchIDWithString:batchID];

                       [cells addObject:cellEntry];
                       [batchFeed setEntriesWithEntries:cells];

                       GDataBatchOperation *op;
                       op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                       [batchFeed setBatchOperation:op];

                       [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl
                                     completionHandler:
                        ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                            NSLog(@"FEED ENTRIES: %@",[feed entries]);
                            NSLog(@"ERROR: %@",error);

                        }];
                   }];
</code>```

Unfortunately, when you access the resulting batch feed (done in the logging statement) you will see this:

```<code>FEED ENTRIES: (
"GDataEntrySpreadsheetCell 0x5fcf510: {v:3.0 title:Error content:Insert not supported on batch. id:batchID_2 batchID:batchID_2 batchStatus:501}"
</code>```

)

So now I need to figure out how to hack around Google's lack of support for batch insertion.

Note that if you change the operation to update you get this:

```<code>FEED ENTRIES: (
"GDataEntrySpreadsheetCell 0xae73880: {v:3.0 title:Error content:Missing entry id id:batchID_2 batchID:batchID_2 batchStatus:400}"
</code>```

)

The missing entry id is because I created the cell without referencing an existing cell -- so I will focus on trying to provide that reference and providing a batch update call instead of a batch insert call.

Body:
I am trying to add a batch of cells to a Google Spreadsheet using the GData Objective-C Client as described here: http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction#Batch_requests.

Here is the code of interest:

                      GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];
                  NSURL *batchUrl = [[batchFeed batchLink] URL];

                  NSMutableArray *cells = [NSMutableArray array];

                  GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                  GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];
                  [cells addObject:cellEntry];
                  [batchFeed setEntries:cells];

                  GDataBatchOperation *op;
                  op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                  [batchFeed setBatchOperation:op];

                  [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl completionHandler:nil];

It doesn't work.  Clearly, the fetchFeedWithBatchFeed has no reference to my GDataWorksheetEntry object -- so it doesn't surprise me that it isn't working.

What am I leaving out?

Thanks in advance.

Body:
I solved this problem and exposed a new issue.

First, the solution.  Once you have a GDataWorksheetEntry, this code will perform a batch operation -- in this case an insert:

                      NSURL *cellsFeedUrl = [[worksheetEntry cellsLink] URL];

                  // Get worksheet cells feed
                  [service fetchFeedWithURL:cellsFeedUrl completionHandler:
                   ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                       NSURL *batchUrl = [[feed batchLink] URL];
                       GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];

                       NSMutableArray *cells = [NSMutableArray array];

                       GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                       GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];

                       static unsigned int staticID = 0;
                       NSString *batchID = [NSString stringWithFormat:@"batchID_%u", ++staticID];
                       [cellEntry setBatchIDWithString:batchID];

                       [cells addObject:cellEntry];
                       [batchFeed setEntriesWithEntries:cells];

                       GDataBatchOperation *op;
                       op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                       [batchFeed setBatchOperation:op];

                       [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl
                                     completionHandler:
                        ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                            NSLog(@"FEED ENTRIES: %@",[feed entries]);
                            NSLog(@"ERROR: %@",error);

                        }];
                   }];

Unfortunately, when you access the resulting batch feed (done in the logging statement) you will see this:

FEED ENTRIES: (
"GDataEntrySpreadsheetCell 0x5fcf510: {v:3.0 title:Error content:Insert not supported on batch. id:batchID_2 batchID:batchID_2 batchStatus:501}"

)

So now I need to figure out how to hack around Google's lack of support for batch insertion.

Note that if you change the operation to update you get this:

FEED ENTRIES: (
"GDataEntrySpreadsheetCell 0xae73880: {v:3.0 title:Error content:Missing entry id id:batchID_2 batchID:batchID_2 batchStatus:400}"

)

The missing entry id is because I created the cell without referencing an existing cell -- so I will focus on trying to provide that reference and providing a batch update call instead of a batch insert call.


问:
Visual Studio Code - Jump from interface definition to implementation
I'm using Visual Studio Code for PHP development. I can click on a method and select "Go to definition" which will point me to the interface which defines the method. What I'm missing is a operation to jump from the interface definition to the place where the method is implemented.

I can use "Find all references" on the interface definition, among all function calls this will also list the implementation but it is hard to find them if a method is used in many different places. Is there a way to search only for all implementations of a method?

答: You can use (Laravel Goto) extension, And go to defineition block using ctrl + click


问:
Fatal error: Call to undefined function get_header() in /home/a7053783/public_html/index.php on line 1

Fatal error: Call to undefined function get_header() in
  /home/a7053783/public_html/index.php on line 1.

How can I fix the error mentioned above?

答:
As probably you are creating your own wordpress theme. I'm so good at wordpress, but do you have header.php file in the same folder as index.php in what you call get_header();?

Because, if you are viewing your index.php theme-file on the actual homepage..then it is unlikely, that wordpress is missing the function.

Also you must make sure, that your theme's functions.php file is correctly filed. I cant remember anymore, what were the MOST critical aspects in the function-file. But this may very well be the problem.

You probably want to double check all of your theme-creating-steps using this tutorial. And also let it be noted, that you can get better wordpress related answers from wordpress.stackexchange.com.


答:
With the current structure, the only way is to use Array.map.

If you want to optimize it then you need to convert the array to the object.

const products = [
  {
    type: 'cpu',
    name: 'AMD Ryzen 5800',
    price: '700',
    image: 'img/ryzen5800.jfif'
  },
  {
    type: 'cpu',
    name: 'AMD Ryzen 6000',
    price: '800',
    image: 'img/ryzen6000.jfif'
  }
]

const productObj = products.reduce((obj, product) => {
  return {
    ...obj,
    [product.name]: product
  }
}, {})

console.log(productObj)
console.log(productObj['AMD Ryzen 6000'])```

Title: How to get name of a specific item in array and increment its value

Body:
I am working on a simple cart, for a homework project. I would like to ask, what would be the best way to take an item from array and increment its value by one? I have 25 items in the array, and each of them has unique name, so I am not using any IDs. Would it be possible to take these items by their name value?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Nákupný košík</title>

//Database with items

let basket = [];

let products = [
{
   type: "mb",
   name: "Asus Motherboard",
   price: "320",
   link: "products/asusmb.html",
   image: "/Eshop_project/img/asusmb.jfif",
},

{
   type: "cpu",
   name: "Intel Core i3",
   price: "150",
   image: "../img/corei3.jfif",
},

{
   type: "cpu",
   name: "Intel Core i5",
   price: "300",
   image: "../img/corei5.jfif",
},

{
   type: "cpu",
   name: "Intel Core i7",
   price: "450",
   image: "../img/corei7.jfif",
},

{
   type: "cpu",
   name: "Intel Core i9",
   price: "600",
   image: "../img/corei9.jfif",
},

{
   type: "ram",
   name: "Corsair 16gb",
   price: "80",
   image: "../img/corsair16gb.jfif",
},

{
   type: "psu",
   name: "Corsair PSU",
   price: "100",
   image: "../img/corsairpsu.jfif",
},

{
   type: "ram",
   name: "Crucial 32gb",
   price: "160",
   image: "../img/crucial32gb.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX3070",
   price: "750",
   image: "../img/gforce 3070.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3080",
   price: "950",
   image: "../img/gforce_3080.jfif",
},

{
   type: "gpu",
   name: "Nvidia Geforce RTX 3090",
   price: "1200",
   image: "../img/gforce_3090.jfif",
},

{
   type: "mb",
   name: "Gigabyte Motherboard",
   price: "400",
   image: "../img/gigabytemb.jfif",
},

{
   type: "psu",
   name: "Gigabyte PSU",
   price: "80",
   image: "../img/gigabytepsu.jfif",
},

{
   type: "ram",
   name: "Kingston 16gb",
   price: "90",
   image: "../img/kingston16gb.jfif",
},

{
   type: "mb",
   name: "MSI Motherboard",
   price: "300",
   image: "../img/msimb.jfif",
},

{
   type: "case",
   name: "Phanteks Case",
   price: "70",
   image: "../img/Phaktekscase.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6500",
   price: "500",
   image: "../img/radeon_6500.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6800",
   price: "650",
   image: "../img/radeon_6800.jfif",
},

{
   type: "gpu",
   name: "AMD Radeon 6900",
   price: "800",
   image: "../img/radeon_6900.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 3790",
   price: "400",
   image: "../img/ryzen3790.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5600",
   price: "550",
   image: "../img/ryzen5600.jfif",
},

{
   type: "cpu",
   name: "AMD Ryzen 5800",
   price: "700",
   image: "../img/ryzen5800.jfif",
},

{
   type: "psu",
   name: "Seasonic PSU",
   price: "95",
   image: "../img/seasonicpsu.jfif",
},

{
   type: "case",
   name: "Zalmancase",
   price: "90",
   image: "../img/zalmancase.jfif",
},

{
   type: "psu",
   name: "Evga PSU",
   price: "80",
   image: "../img/evgapsu.jfif",
}

]
localStorage.setItem('products', JSON.stringify(products));


问:
How to get a MD5 hash from a string in Golang?
This is how I started to get a md5 hash from a string:

```<code>import "crypto/md5"

var original = "my string comes here"
var hash = md5.New(original)
</code>```

But obviously this is not how it works. Can someone provide me a working sample for this?

答:
just another answer</p>
```<code>// MD5 hashes using md5 algorithm
func MD5(text string) string {
    data := []byte(text)
    return fmt.Sprintf("%x", md5.Sum(data))
}
</code>```

Body:
This is how I started to get a md5 hash from a string:

import "crypto/md5"

var original = "my string comes here"
var hash = md5.New(original)

But obviously this is not how it works. Can someone provide me a working sample for this?

Body:
just another answer

// MD5 hashes using md5 algorithm
func MD5(text string) string {
    data := []byte(text)
    return fmt.Sprintf("%x", md5.Sum(data))
}


问:
Change value title of a converted dropdown to radio buttons
I am using the following script (jsfiddle) to convert dropdown list to button selection.  But it displays the text of the button from the value of the option.

Is there a way to change the text displayed for each button, without changing the value of the button? Like giving it an id (getElementById) or something?  So the new buttons are like: Option 1, Option 2.. etc.

Current code:

// http://stackoverflow.com/questions/3975331/update-drop-down-selection-with-radio-button-selection-using-jquery
// http://jsfiddle.net/ChinmayeeG/TkGP8/
$(function () {

  $('.radioSelect').each(function (selectIndex, selectElement) {

    var select = $(selectElement);
    var container = $("
");
    select.parent().append(container);
    container.append(select);

    select.find('option').each(function (optionIndex, optionElement) {
      var radioGroup = select.attr('id') + "Group";
      var label = $("");
      container.append(label);

      $("<input type='radio' name='" + radioGroup + "' />")
          .attr("value", $(this).val())
          //.click((function () { select.val($(this).val()); })) //radio updates select - see optional below
          .appendTo(label);

      $("" + $(this).val() + "").appendTo(label);
    });

    //http://stackoverflow.com/questions/4957207/how-to-check-uncheck-radio-button-on-click
    //optional - this logic handles unchecking when clicking on an already checked radio
    container.find(":radio + span").mousedown(
      function (e) {
        var $span = $(this);
        var $radio = $($span.prev());
        if ($radio.is(':checked')) {
          var uncheck = function() {
            setTimeout(function () { $radio.prop('checked', false); }, 0);
          };
          var unbind = function() {
            $span.unbind('mouseup', up);
          };
          var up = function() {
            uncheck();
            unbind();
          };
          $span.bind('mouseup', up);
          $span.one('mouseout', unbind);
        } else {
          select.val($radio.val());
        }
      }
    );

    select.change((function () { //select updates radio
      $("input[name='" + select.attr('id') + "Group" + "'][value='" + this.value + "']").prop("checked", true);
    }));
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* http://jsfiddle.net/496c9/ */
 .radioSelectContainer > select {
     /*display: none;*/
}
.radioSelectContainer > label {
    display: inline-block;
    margin: 0.3em 0.3em 0 0;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid #D0D0D0;
}
.radioSelectContainer > label > span {
    padding:0.2em;
    text-align:center;
    display:block;
}
.radioSelectContainer > label > input {
    position:absolute;
    top:-20px;
}
.radioSelectContainer > label > input:checked + span {
    background-color:#404040;
    color:#F7F7F7;
}</code>```

<select class="radioSelect" id="sizeOptions">
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="2XL">2XL</option>
    <option value="3XL">3XL</option>
    <option value="4XL">4XL</option>
</select>```

答:
You mean something like

http://jsfiddle.net/mplungjan/2bok3gn1/

```<code>const sizes = {"S":"Small","M":"Medium"...."4XL":"Huge"}
</code>```

and

```<code>$("<span>" + sizes[$(this).val()] + "</span>").appendTo(label);
</code>```

Body:
I am using the following script (jsfiddle) to convert dropdown list to button selection.  But it displays the text of the button from the value of the option.

Is there a way to change the text displayed for each button, without changing the value of the button? Like giving it an id (getElementById) or something?  So the new buttons are like: Option 1, Option 2.. etc.

Current code:

// http://stackoverflow.com/questions/3975331/update-drop-down-selection-with-radio-button-selection-using-jquery
// http://jsfiddle.net/ChinmayeeG/TkGP8/
$(function () {

  $('.radioSelect').each(function (selectIndex, selectElement) {

    var select = $(selectElement);
    var container = $("
");
    select.parent().append(container);
    container.append(select);

    select.find('option').each(function (optionIndex, optionElement) {
      var radioGroup = select.attr('id') + "Group";
      var label = $("");
      container.append(label);

      $("<input type='radio' name='" + radioGroup + "' />")
          .attr("value", $(this).val())
          //.click((function () { select.val($(this).val()); })) //radio updates select - see optional below
          .appendTo(label);

      $("" + $(this).val() + "").appendTo(label);
    });

    //http://stackoverflow.com/questions/4957207/how-to-check-uncheck-radio-button-on-click
    //optional - this logic handles unchecking when clicking on an already checked radio
    container.find(":radio + span").mousedown(
      function (e) {
        var $span = $(this);
        var $radio = $($span.prev());
        if ($radio.is(':checked')) {
          var uncheck = function() {
            setTimeout(function () { $radio.prop('checked', false); }, 0);
          };
          var unbind = function() {
            $span.unbind('mouseup', up);
          };
          var up = function() {
            uncheck();
            unbind();
          };
          $span.bind('mouseup', up);
          $span.one('mouseout', unbind);
        } else {
          select.val($radio.val());
        }
      }
    );

    select.change((function () { //select updates radio
      $("input[name='" + select.attr('id') + "Group" + "'][value='" + this.value + "']").prop("checked", true);
    }));
  });
});

/* http://jsfiddle.net/496c9/ */
 .radioSelectContainer > select {
     /*display: none;*/
}
.radioSelectContainer > label {
    display: inline-block;
    margin: 0.3em 0.3em 0 0;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid #D0D0D0;
}
.radioSelectContainer > label > span {
    padding:0.2em;
    text-align:center;
    display:block;
}
.radioSelectContainer > label > input {
    position:absolute;
    top:-20px;
}
.radioSelectContainer > label > input:checked + span {
    background-color:#404040;
    color:#F7F7F7;
}

<select class="radioSelect" id="sizeOptions">
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="2XL">2XL</option>
    <option value="3XL">3XL</option>
    <option value="4XL">4XL</option>
</select>

Body:
You mean something like

http://jsfiddle.net/mplungjan/2bok3gn1/

const sizes = {"S":"Small","M":"Medium"...."4XL":"Huge"}

and

$("<span>" + sizes[$(this).val()] + "</span>").appendTo(label);


问:
Can't change color of a "Leading Icon" of a ListTile in Flutter
I have a Drawer with a ListView, inside that I have the ListTiles. In every ListTile there is a leading element, the Icon. I want to change the color of all Icons inside ListTiles from my ThemeData. I tried however it doesn't work.

Here is my current code (the class only):

```<code>class _UniversalConverter extends State<UniversalConverter> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.blue),
        ),
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Universal Converter"),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('Home'),
                  leading: const Icon(Icons.home),
                  onTap: () {},
                ),
                ListTile(
                  title: const Text('Angle'),
                  leading: const Icon(Icons.block),
                  onTap: () {},
                ),
              ],
            ),
          ),
        ));
  }
}
</code>```

As you can see I have the iconTheme: const IconThemeData(color: Colors.blue), but it doesn't do anything.

Any help would be appreciated,
Thanks!

答:
Try using ListTileTheme

```<code>listTileTheme: ListTileThemeData(
  iconColor: Colors.blue
),
</code>```

or

```<code>ListTile(
   title: const Text('Angle'),
   leading: const Icon(Icons.block, color: Theme.of(context).iconTheme.color),
   onTap: () {},
),
</code>```

Body:
I have a Drawer with a ListView, inside that I have the ListTiles. In every ListTile there is a leading element, the Icon. I want to change the color of all Icons inside ListTiles from my ThemeData. I tried however it doesn't work.

Here is my current code (the class only):

class _UniversalConverter extends State<UniversalConverter> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.blue),
        ),
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Universal Converter"),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('Home'),
                  leading: const Icon(Icons.home),
                  onTap: () {},
                ),
                ListTile(
                  title: const Text('Angle'),
                  leading: const Icon(Icons.block),
                  onTap: () {},
                ),
              ],
            ),
          ),
        ));
  }
}

As you can see I have the iconTheme: const IconThemeData(color: Colors.blue), but it doesn't do anything.

Any help would be appreciated,
Thanks!

Body:
Try using ListTileTheme

listTileTheme: ListTileThemeData(
  iconColor: Colors.blue
),

or

ListTile(
   title: const Text('Angle'),
   leading: const Icon(Icons.block, color: Theme.of(context).iconTheme.color),
   onTap: () {},
),


问:
Laravel 8 fetching coordinates data and display in Google Maps in JavaScript
I have coordinates stored in my database, and I want to fetch those coordinates to display on Google Maps, where the user will click on the link which says like "view on map" in the column table. However, the link will redirect to that map based on stored coordinates from the database, and I don't know how to fetch those coordinates from the database with JavaScript.

```<code>var map;
var myLatLng;

function initMap() {

  var loc = { lat: -74.17972, lng:34.56445312 };

  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: loc,
  });

  var marker = new google.maps.Marker({
    position: loc,
    map: map,
    draggable: true
  });
}
</code>```

答:
I believe the way to make client js talks to you db , will be through an API Call by Ajax.

You can create an Api route and controller function to handle query the coords
from the DB and test it out

Body:
I have coordinates stored in my database, and I want to fetch those coordinates to display on Google Maps, where the user will click on the link which says like "view on map" in the column table. However, the link will redirect to that map based on stored coordinates from the database, and I don't know how to fetch those coordinates from the database with JavaScript.

var map;
var myLatLng;

function initMap() {

  var loc = { lat: -74.17972, lng:34.56445312 };

  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: loc,
  });

  var marker = new google.maps.Marker({
    position: loc,
    map: map,
    draggable: true
  });
}


问:
excel power query transforming data from text to decimal
Howto transform a colum with postive and negative values, which is loaded as text into a column with decial values without errors. the minus sign seems to make the error:

I use a german version of excel 365 on windows 10

答: Finally solve the problem: It was q quircky minus-sign, which had to be replaced by a standard minus sign before changing type to decimal. Unfortunatley at first sign this quirky decimals looked like nomral ones</p>


问:
r programming - logistic regression plot
```<code>  mutate(prob = ifelse(outcome == "pos", 0","1"))%>%
>   ggplot(aes( plasma_glucose, prob)) +
+   geom_point(alpha = 1) +
+   geom_smooth(method = "glm", method.args = list(family = "binomial")) +
+   labs(
+     title = "Logistic Regression Model",
+     x = "Plasma Glucose Concentration",
+     y = "Probability of being diabete-pos"
+   )
</code>```

output-
Error: Problem with mutate() column prob.
i prob = ifelse(outcome == "pos", 0, 1, ).
x unused argument (alist())

I am new to R programming and not sure how to rectify the above code? I am trying to plot logistic regression result.

答:
Here is an answer regarding your first error message unused argument (alist()), in case anybody else gets here by googling that error message:

You get the unused argument error in R if you try to call a function with an argument this function doesn't have: such as:

foo <- function(x) x

foo(x = 10, y = 10) # notice the y-argument
#> Error in foo(x = 10, y = 10): unused argument (y = 10)
```
<ul>
<li>You get the <code>unused argument (alist())</code> error if you call a function with a trailing comma, as R see this as another - completely empty - argument. For example:</li>
</ul>
<pre class="lang-r prettyprint-override"><code>foo(x = 10, ) # notice the comma
#> Error in foo(x = 10, ): unused argument (alist())
</code>```

As @Rfanatic said in the comments, remove the extra comma and this error message goes away.

Body:
  mutate(prob = ifelse(outcome == "pos", 0","1"))%>%
>   ggplot(aes( plasma_glucose, prob)) +
+   geom_point(alpha = 1) +
+   geom_smooth(method = "glm", method.args = list(family = "binomial")) +
+   labs(
+     title = "Logistic Regression Model",
+     x = "Plasma Glucose Concentration",
+     y = "Probability of being diabete-pos"
+   )

output-
Error: Problem with mutate() column prob.
i prob = ifelse(outcome == "pos", 0, 1, ).
x unused argument (alist())

I am new to R programming and not sure how to rectify the above code? I am trying to plot logistic regression result.

Body:
Here is an answer regarding your first error message unused argument (alist()), in case anybody else gets here by googling that error message:

You get the unused argument error in R if you try to call a function with an argument this function doesn't have: such as:

foo <- function(x) x

foo(x = 10, y = 10) # notice the y-argument
#> Error in foo(x = 10, y = 10): unused argument (y = 10)

You get the unused argument (alist()) error if you call a function with a trailing comma, as R see this as another - completely empty - argument. For example:

foo(x = 10, ) # notice the comma
#> Error in foo(x = 10, ): unused argument (alist())

As @Rfanatic said in the comments, remove the extra comma and this error message goes away.


问:
Converting unicode fraction characters (vulgar fractions) to decimals in Excel 2003
I'm trying to convert the following text to a decimal number in excel 2003:

"93⅛"

The output should be: 93.125

I've gotten this to work with ¼, ½, ¾ by using the Replace function in VBA:
For example, this works:

```<code>cur_cell = Replace(cur_cell, "½", " 1/2")
</code>```

However, the ⅛ and family characters are not supported in the VBA editor. They display as ??. Instead, I tried to replace the unicode value directly:

```<code>cur_cell = Replace(cur_cell, " & ChrW$(&H215B) & ", " 1/8")
</code>```

But this doesn't work.

Is there a good way to convert these strings to numbers that I can use?

答:
The correct syntax is:

```<code>cur_cell = Replace(cur_cell, ChrW$(&H215B), " 1/8")
</code>```

Your example was saying: replace the string consisting of a space, an ampersand, a space [etc.] with 1/8. Clearly that's not what you want to do!

I'd actually recommend:

```<code>cur_cell.Value = Replace(Replace(cur_cell.Value, ChrW$(&H215B), ".125")," ","")
</code>```

to circumvent Excel's automatic replacement of fractions. I just don't like to rely on that kind of automatic stuff. Why not write it as a decimal number straight off? Also, I like explicitly refering to the cell's .Value property as opposed to relying on it being the default property.

Body:
I'm trying to convert the following text to a decimal number in excel 2003:

"93⅛"

The output should be: 93.125

I've gotten this to work with ¼, ½, ¾ by using the Replace function in VBA:
For example, this works:

cur_cell = Replace(cur_cell, "½", " 1/2")

However, the ⅛ and family characters are not supported in the VBA editor. They display as ??. Instead, I tried to replace the unicode value directly:

cur_cell = Replace(cur_cell, " & ChrW$(&H215B) & ", " 1/8")

But this doesn't work.

Is there a good way to convert these strings to numbers that I can use?

Body:
The correct syntax is:

cur_cell = Replace(cur_cell, ChrW$(&H215B), " 1/8")

Your example was saying: replace the string consisting of a space, an ampersand, a space [etc.] with 1/8. Clearly that's not what you want to do!

I'd actually recommend:

cur_cell.Value = Replace(Replace(cur_cell.Value, ChrW$(&H215B), ".125")," ","")

to circumvent Excel's automatic replacement of fractions. I just don't like to rely on that kind of automatic stuff. Why not write it as a decimal number straight off? Also, I like explicitly refering to the cell's .Value property as opposed to relying on it being the default property.


问:
Discord.js v12 How to get total number on reactions from fetched embed
So i've been trying to count the reactions statistic after it was accepted or rejected, i'd try to find a solution but i can't here's my code

```<code>module.exports = {
  name: 'accept-suggestion',
  cooldown: 3,
  description: 'Accept a sugegstion',
  permissions: 'MANAGE_ROLES',
  usage: '[suggestion id] [reason]',
  async run(client, message, args, cmd, Discord){
    message.delete()
    const messageID = args[0];
    const acceptMsg = args.slice(1).join(" ");

    if(!messageID) return message.reply('Please specify a suggestion Id!').then(msg => {
      msg.delete({ timeout: 3000 })
    })
    if(!acceptMsg) return message.reply('Please specify a reason!').then(msg => {
      msg.delete({ timeout: 3000})
    })

    try {
      const suggestionChannel = message.guild.channels.cache.get(
        'SuggestionChannel_ID'
      );

      const moderator = message.author.tag

      const suggestedEmbed = await suggestionChannel.messages.fetch(messageID);
      console.log(suggestedEmbed)
      const data = suggestedEmbed.embeds[0];
      const dataStats = suggestedEmbed[0];

      let upVote = dataStats.reactions.cache.get('✅').count;
      let downVote = dataStats.reactions.cache.get('❌').count;

      const acceptEmbed = new Discord.MessageEmbed()
        .setTitle("Suggestion (Accepted)")
        .setColor('#1dc44a')
        .setAuthor(data.author.name, data.author.iconURL)
        .setDescription(data.description)
        .addFields(
          {name: `Accepted by ${moderator}`, value: ` > ${acceptMsg}`},
          {name: 'Statistic', value: `${upVote}\n${downVote}`}
        )
        .setFooter(`${data.author.name}'s suggestion`, data.author.iconURL)

      suggestedEmbed.edit(acceptEmbed).then(msg => msg.reactions.removeAll())

      const user = await client.users.cache.find(
        (u) => u.tag === data.author.name
      );
      user.send("Your suggestion has been accepted!")
    } catch(err) {
      console.log(err)
    }
  }
}
</code>```

you maybe wondering why i put .reactions after dataStats, i put it because i thought it would work by seeing the output off the suggestedEmbed(the output: https://pastebin.com/yEhDecur) i hope someone could fix this :)

答:
Running the fetch() method with a id parameter only returns a single Message so accessing it like a array/collection won't work

      const dataStats = suggestedEmbed[0];
```
<p>this needs to change to</p>
<pre class="lang-js prettyprint-override"><code>      const dataStats = suggestedEmbed;
</code>```

https://discord.js.org/#/docs/discord.js/stable/class/MessageManager?scrollTo=fetch

Body:
So i've been trying to count the reactions statistic after it was accepted or rejected, i'd try to find a solution but i can't here's my code

module.exports = {
  name: 'accept-suggestion',
  cooldown: 3,
  description: 'Accept a sugegstion',
  permissions: 'MANAGE_ROLES',
  usage: '[suggestion id] [reason]',
  async run(client, message, args, cmd, Discord){
    message.delete()
    const messageID = args[0];
    const acceptMsg = args.slice(1).join(" ");

    if(!messageID) return message.reply('Please specify a suggestion Id!').then(msg => {
      msg.delete({ timeout: 3000 })
    })
    if(!acceptMsg) return message.reply('Please specify a reason!').then(msg => {
      msg.delete({ timeout: 3000})
    })

    try {
      const suggestionChannel = message.guild.channels.cache.get(
        'SuggestionChannel_ID'
      );

      const moderator = message.author.tag

      const suggestedEmbed = await suggestionChannel.messages.fetch(messageID);
      console.log(suggestedEmbed)
      const data = suggestedEmbed.embeds[0];
      const dataStats = suggestedEmbed[0];

      let upVote = dataStats.reactions.cache.get('✅').count;
      let downVote = dataStats.reactions.cache.get('❌').count;

      const acceptEmbed = new Discord.MessageEmbed()
        .setTitle("Suggestion (Accepted)")
        .setColor('#1dc44a')
        .setAuthor(data.author.name, data.author.iconURL)
        .setDescription(data.description)
        .addFields(
          {name: `Accepted by ${moderator}`, value: ` > ${acceptMsg}`},
          {name: 'Statistic', value: `${upVote}\n${downVote}`}
        )
        .setFooter(`${data.author.name}'s suggestion`, data.author.iconURL)

      suggestedEmbed.edit(acceptEmbed).then(msg => msg.reactions.removeAll())

      const user = await client.users.cache.find(
        (u) => u.tag === data.author.name
      );
      user.send("Your suggestion has been accepted!")
    } catch(err) {
      console.log(err)
    }
  }
}

you maybe wondering why i put .reactions after dataStats, i put it because i thought it would work by seeing the output off the suggestedEmbed(the output: https://pastebin.com/yEhDecur) i hope someone could fix this :)

Body:
Running the fetch() method with a id parameter only returns a single Message so accessing it like a array/collection won't work

      const dataStats = suggestedEmbed[0];

this needs to change to

      const dataStats = suggestedEmbed;

https://discord.js.org/#/docs/discord.js/stable/class/MessageManager?scrollTo=fetch


问:
Firebase CLI v10.0.1 is incompatible with Node.js v10.24.1 Please upgrade Node.js >=12
I am facing this issue while deploying my firebase function through Git Actions

```<code>Firebase CLI v10.0.1 is incompatible with Node.js v10.24.1 Please upgrade Node.js to version >= 12
</code>```

My Firebase version:9.16.6
Node version : 14.15.4..

Edit: Here is the dependencies section of my package.json file.

"dependencies": {
  "axios": "^0.21.1",
  "cryptr": "^6.0.2",
  "dotenv": "^10.0.0",
  "fetch": "^1.1.0",
  "firebase": "^8.10.0",
  "firebase-admin": "^9.8.0",
  "firebase-functions": "^3.16.0",
  "lodash": "^4.17.21",
  "node-fetch": "^2.6.1",
  "request": "^2.88.2",
  "request-promise": "^4.2.6"
},
"devDependencies": {
  "eslint": "^7.6.0",
  "eslint-config-google": "^0.14.0",
  "firebase-functions-test": "^0.2.0"
}
```

答: i added https://github.com/actions/setup-node to my workflow (this probably isnt required). And changed w9jds/firebase-action@x.x.x to w9jds/firebase-action@master (Changed specific version to master`. This fixed it for me. I hope it works!

Body:
I am facing this issue while deploying my firebase function through Git Actions

Firebase CLI v10.0.1 is incompatible with Node.js v10.24.1 Please upgrade Node.js to version >= 12

My Firebase version:9.16.6
Node version : 14.15.4..

Edit: Here is the dependencies section of my package.json file.

"dependencies": {
  "axios": "^0.21.1",
  "cryptr": "^6.0.2",
  "dotenv": "^10.0.0",
  "fetch": "^1.1.0",
  "firebase": "^8.10.0",
  "firebase-admin": "^9.8.0",
  "firebase-functions": "^3.16.0",
  "lodash": "^4.17.21",
  "node-fetch": "^2.6.1",
  "request": "^2.88.2",
  "request-promise": "^4.2.6"
},
"devDependencies": {
  "eslint": "^7.6.0",
  "eslint-config-google": "^0.14.0",
  "firebase-functions-test": "^0.2.0"
}


问:
Two extra views put inside of a ForEach with a filtering search bar
So I have a ScrollView that contains a list of all the contacts imported from a user's phone. Above the ScrollView, I have a 'filter search bar' that has a binding that causes the list to show only contacts where the name contains the same string as the search bar filter. For some reason, the last two contacts in the list always pop up at the bottom of the list, no matter what the string is (even if it's a string not contained in any of the contact names on the phone). I tried deleting a contact and the problem persists, because the original contact was just replaced with the new second to last contact. Any help fixing this would be much appreciated!

```<code>            struct SomeView: View {
                @State var friendsFilterText: String = ""
                @State var savedContacts: CustomContact = []
                var body: some View {
                var filteredContactsCount = 0
                if friendsFilterText.count != 0 {
                    for contact in appState.savedContacts {
                        if contact.name.lowercased().contains(friendsFilterText.lowercased()) {
                            filteredContactsCount += 1
                        }
                    }
                } else {
                    filteredContactsCount = savedContacts.count
                }
                return HStack {
                    Image(systemName: "magnifyingglass")
                    ZStack {
                        HStack {
                            Text("Type a name...")
                                .opacity(friendsFilterText.count > 0 ? 0 : 1)
                            Spacer()
                        }
                        CocoaTextField("", text: $friendsFilterText)
                        .background(Color.clear)
                    }
                    Button(action: {
                        friendsFilterText = ""
                    }, label: {
                        Image(systemName: "multiply.circle.fill")
                    })
                }.frame(height: 38)
            HStack(spacing: 10) {
                Text("Your contacts (\(filteredContactsCount))")
                Spacer()
                Button(action: {
                    fetchContacts()
                }, label: {
                    Image(systemName: "square.and.arrow.down")
                })

                Button(action: {
                    // edit button action
                }, label: {
                    Text("Edit")
                })

            }
            ScrollView {
                VStack {
                    ForEach(savedContacts, id: \.self.name) { contact in
                    if contact.name.lowercased().contains(friendsFilterText.lowercased()) || friendsFilterText.count == 0 {
                        Button(action: {
                            // contact button action
                        }, label: {
                            HStack(spacing: 20) {
                               Image(systemName: "person.crop.circle.fill")
                                    .font(.system(size: 41))
                                    .frame(width: 41, height: 41)

                                VStack(alignment: .leading, spacing: 4) {
                                    Text(contact.name)
                                    Text(contact.phoneNumber)
                                }
                                Spacer()
                            }.frame(height: 67)
                        })
                    }
                }
                }
            }
        }
   }
</code>```

CustomContact is a custom struct with properties phoneNumber and name. I've attached images below of the issue I'm experiencing. I'm thinking MAYBE it's because there's something off timing-wise with the friendsFilterText and the ForEach rendering but I'm really not sure.

In the image set below, the 'Extra Contact 1' and 'Extra Contact 2' are ALWAYS rendered, unless I add a filter, then switch to a different view, then back to this view (which leads me to believe it's a timing thing again).

https://imgur.com/a/CJW2CUS

答:
You should move the count calculation out of the view into a computed var.

And if CustomContact is your single contact struct, it should actually read @State var savedContacts: [CustomContact] = [] i.e. an array of CustomContact.

The rest worked fine with me, no extra contacts showing.

```<code>struct ContentView: View {

    @State var friendsFilterText: String = ""
    @State var savedContacts: [CustomContact] = []

    // computed var
    var filteredContactsCount: Int {
        if friendsFilterText.isEmpty { return savedContacts.count }
        return savedContacts.filter({ $0.name.lowercased().contains(friendsFilterText.lowercased()) }).count
    }

    var body: some View {

...
</code>```

Body:
So I have a ScrollView that contains a list of all the contacts imported from a user's phone. Above the ScrollView, I have a 'filter search bar' that has a binding that causes the list to show only contacts where the name contains the same string as the search bar filter. For some reason, the last two contacts in the list always pop up at the bottom of the list, no matter what the string is (even if it's a string not contained in any of the contact names on the phone). I tried deleting a contact and the problem persists, because the original contact was just replaced with the new second to last contact. Any help fixing this would be much appreciated!

            struct SomeView: View {
                @State var friendsFilterText: String = ""
                @State var savedContacts: CustomContact = []
                var body: some View {
                var filteredContactsCount = 0
                if friendsFilterText.count != 0 {
                    for contact in appState.savedContacts {
                        if contact.name.lowercased().contains(friendsFilterText.lowercased()) {
                            filteredContactsCount += 1
                        }
                    }
                } else {
                    filteredContactsCount = savedContacts.count
                }
                return HStack {
                    Image(systemName: "magnifyingglass")
                    ZStack {
                        HStack {
                            Text("Type a name...")
                                .opacity(friendsFilterText.count > 0 ? 0 : 1)
                            Spacer()
                        }
                        CocoaTextField("", text: $friendsFilterText)
                        .background(Color.clear)
                    }
                    Button(action: {
                        friendsFilterText = ""
                    }, label: {
                        Image(systemName: "multiply.circle.fill")
                    })
                }.frame(height: 38)
            HStack(spacing: 10) {
                Text("Your contacts (\(filteredContactsCount))")
                Spacer()
                Button(action: {
                    fetchContacts()
                }, label: {
                    Image(systemName: "square.and.arrow.down")
                })

                Button(action: {
                    // edit button action
                }, label: {
                    Text("Edit")
                })

            }
            ScrollView {
                VStack {
                    ForEach(savedContacts, id: \.self.name) { contact in
                    if contact.name.lowercased().contains(friendsFilterText.lowercased()) || friendsFilterText.count == 0 {
                        Button(action: {
                            // contact button action
                        }, label: {
                            HStack(spacing: 20) {
                               Image(systemName: "person.crop.circle.fill")
                                    .font(.system(size: 41))
                                    .frame(width: 41, height: 41)

                                VStack(alignment: .leading, spacing: 4) {
                                    Text(contact.name)
                                    Text(contact.phoneNumber)
                                }
                                Spacer()
                            }.frame(height: 67)
                        })
                    }
                }
                }
            }
        }
   }

CustomContact is a custom struct with properties phoneNumber and name. I've attached images below of the issue I'm experiencing. I'm thinking MAYBE it's because there's something off timing-wise with the friendsFilterText and the ForEach rendering but I'm really not sure.

In the image set below, the 'Extra Contact 1' and 'Extra Contact 2' are ALWAYS rendered, unless I add a filter, then switch to a different view, then back to this view (which leads me to believe it's a timing thing again).

https://imgur.com/a/CJW2CUS

Body:
You should move the count calculation out of the view into a computed var.

And if CustomContact is your single contact struct, it should actually read @State var savedContacts: [CustomContact] = [] i.e. an array of CustomContact.

The rest worked fine with me, no extra contacts showing.

struct ContentView: View {

    @State var friendsFilterText: String = ""
    @State var savedContacts: [CustomContact] = []

    // computed var
    var filteredContactsCount: Int {
        if friendsFilterText.isEmpty { return savedContacts.count }
        return savedContacts.filter({ $0.name.lowercased().contains(friendsFilterText.lowercased()) }).count
    }

    var body: some View {

...


问:
Eclipse Maven 2 installation
I am doing a Maven build in Eclipse where my project requires Maven 2.  My Maven runtime is set to embedded (3.2.1/1.5.1.20150109-1819).  How do I set the runtime to use Maven 2?

I tried setting a runtime installation by pointing to my Maven 2 installation, but that did not work.

答:
Actually you have selected the wrong folder of maven. When you have unzipped the file directory will look like

you should have select directory pointed by red highlighter.

you should select the red highlighted folder. In your case you are pointing bin directory that's why it is creating problem.

Please do not forgot to click on your installed maven.
This has resolved my issue.

Title: Eclipse Maven 2 installation


问:
How to write Firebase Realtime Database to Firestore automatically?
I am currently doing a project that uses Arduino to collect data and store the data in cloud and display the data on cloud on mobile app. From what I have tried, Arduino can only upload data to Firebase realtime database, but my Flutter mobile app needs the data to be stored in Firestore. Is there any way to write firebase realtime database data into Firestore automatically when there is changes in the realtime database?

This is the realtime database structure:
realtime database structure

and I would like to append the data into respective field in Firestore like this:
firestore structure

I have tried to read the data every 5 seconds and write it to Firebase but it does not seems like very efficient:

```<code>final userDbRef = FirebaseDatabase.instance.ref("user/");
 String uid = globals.uid;

 Stream<DatabaseEvent> stream = userDbRef.onValue;

 // Subscribe to the stream!
 var subscription = stream.listen((DatabaseEvent event) {
   // print('Listening');
   dynamic values = event.snapshot.value;
   final data = new Map<String, dynamic>.from(values);

   globals.temp = data['temp'];
   globals.hr = data ['hr'];
   globals.spo2 = data['spo2'];
   globals.position = data['position'];
   globals.time = DateTime.parse(data['time']);
 });

 subscription.pause();

 String date = DateTime.now().add(const Duration(hours: 8)).toString().substring(0, 10);

 dynamic result = await DatabaseService(uid: uid).getUserData('patient');
 if (result[date].toString() == 'null') {
   await DatabaseService(uid: uid).updateSingleUserData('patient', {
     date: {
       'time': ['${date} 00:00:00.000'],
       'hr': [95],
       'temp': [36.5],
       'spo2': [98],
       'position': ['lying'],
     },
   });
 } else {
   List timeList = result[date]['time'];
   List hrList = result[date]['hr'];
   List tempList = result[date]['temp'];
   List spo2List = result[date]['spo2'];
   List positionList = result[date]['position'];

   if ((!timeList.contains(globals.time.toString())) & (globals.time.toString() != 'null')) {
     timeList.add(globals.time.toString());
     hrList.add(globals.hr);
     tempList.add(globals.temp);
     spo2List.add(globals.spo2);
     positionList.add(globals.position);

    await DatabaseService(uid:uid).updateSingleUserData('patient', {
       date: {
         'time': timeList,
         'hr': hrList,
         'temp': tempList,
         'spo2': spo2List,
         'position': positionList,
       },
     });
   }
 }
 subscription.resume();
</code>```

Thank you.

答:
Is there any way to write firebase realtime database data into
Firestore automatically when there is changes in the realtime
database?

Yes, a common approach is to use a Cloud Function that is automatically triggered each time a new node is added to the Realtime Database. The Cloud Function is executed in the back-end, i.e. on the Firebase/Google Cloud infrastructure, and therefore you don't need to write any code in your Flutter app for this data mirroring/transfert.

Here is a simple example with generic paths:

```<code>// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

exports.duplicateToFirestore = functions.database.ref('/myRTDBPath/{pushId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const nodeVal = snapshot.val();

      // Write it to a Firestore collection

      return admin.firestore().collection('myFirestoreCollection').add(nodeVal);

    });
</code>```

I let you do the work of transformation of the RTDB node value to the Firestore document structure you are looking for.

Body:
I am currently doing a project that uses Arduino to collect data and store the data in cloud and display the data on cloud on mobile app. From what I have tried, Arduino can only upload data to Firebase realtime database, but my Flutter mobile app needs the data to be stored in Firestore. Is there any way to write firebase realtime database data into Firestore automatically when there is changes in the realtime database?

This is the realtime database structure:
realtime database structure

and I would like to append the data into respective field in Firestore like this:
firestore structure

I have tried to read the data every 5 seconds and write it to Firebase but it does not seems like very efficient:

final userDbRef = FirebaseDatabase.instance.ref("user/");
 String uid = globals.uid;

 Stream<DatabaseEvent> stream = userDbRef.onValue;

 // Subscribe to the stream!
 var subscription = stream.listen((DatabaseEvent event) {
   // print('Listening');
   dynamic values = event.snapshot.value;
   final data = new Map<String, dynamic>.from(values);

   globals.temp = data['temp'];
   globals.hr = data ['hr'];
   globals.spo2 = data['spo2'];
   globals.position = data['position'];
   globals.time = DateTime.parse(data['time']);
 });

 subscription.pause();

 String date = DateTime.now().add(const Duration(hours: 8)).toString().substring(0, 10);

 dynamic result = await DatabaseService(uid: uid).getUserData('patient');
 if (result[date].toString() == 'null') {
   await DatabaseService(uid: uid).updateSingleUserData('patient', {
     date: {
       'time': ['${date} 00:00:00.000'],
       'hr': [95],
       'temp': [36.5],
       'spo2': [98],
       'position': ['lying'],
     },
   });
 } else {
   List timeList = result[date]['time'];
   List hrList = result[date]['hr'];
   List tempList = result[date]['temp'];
   List spo2List = result[date]['spo2'];
   List positionList = result[date]['position'];

   if ((!timeList.contains(globals.time.toString())) & (globals.time.toString() != 'null')) {
     timeList.add(globals.time.toString());
     hrList.add(globals.hr);
     tempList.add(globals.temp);
     spo2List.add(globals.spo2);
     positionList.add(globals.position);

    await DatabaseService(uid:uid).updateSingleUserData('patient', {
       date: {
         'time': timeList,
         'hr': hrList,
         'temp': tempList,
         'spo2': spo2List,
         'position': positionList,
       },
     });
   }
 }
 subscription.resume();

Thank you.

Body:
Is there any way to write firebase realtime database data into
Firestore automatically when there is changes in the realtime
database?

Yes, a common approach is to use a Cloud Function that is automatically triggered each time a new node is added to the Realtime Database. The Cloud Function is executed in the back-end, i.e. on the Firebase/Google Cloud infrastructure, and therefore you don't need to write any code in your Flutter app for this data mirroring/transfert.

Here is a simple example with generic paths:

// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

exports.duplicateToFirestore = functions.database.ref('/myRTDBPath/{pushId}')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const nodeVal = snapshot.val();

      // Write it to a Firestore collection

      return admin.firestore().collection('myFirestoreCollection').add(nodeVal);

    });

I let you do the work of transformation of the RTDB node value to the Firestore document structure you are looking for.