问:
Shiny app error sourcing debug
I'm loading a shiny app built to render a risk with new input variables from a logistic regression model built on a csv file. Any ideas for debug? The error message when loading the app is as follows:</p>

```<code>ERROR: Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa   with such message on the R studio console :
Warning in checkEncoding(file) :
  The input file C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Prediction IRA chez ileostomises.R does not seem to be encoded in UTF8
Warning: invalid input found on input connection 'C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Prediction IRA chez ileostomises.R'
Error in parse(file, keep.source = FALSE, srcfile = src, encoding = enc) :
  C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Pr:5:14: unexpected INCOMPLETE_STRING
4: ui <- fluidPage(
5:   titlePanel("Pr
                ^
Warning: Error in sourceUTF8: Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa
Stack trace (innermost first):
    1: runApp
Error : Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa
</code>```

```<code> ui <- fluidPage(
  titlePanel("Prédiction d'insuffisance rénale aiguë chez les iléostomisés"),
   sidebarLayout(
     sidebarPanel(

  checkboxGroupInput("checkboxGroup1", "Cancer colorectal",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup2", "Maladie cardiovasculaire",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup3", "Maladie thrombo-embolique veineuse",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup4","Démence",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup5","Résection rectale antérieure",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup6","Hémicolectomie gauche",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup7","Chimiothérapie per iléostomie",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup8","Iléostomie à haut débit",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup9","Deshydratation",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  sliderInput("slider1","Créatininémie pré-opératoire", min = 20, max = 400, value = 100),

  sliderInput("slider2", "Age", min = 0, max = 100, value = 50)
),

  mainPanel(
tabPanel("Probabilité de développer une insuffisance rénale aiguë",textOutput("pred1")))
 ))

data_app <- read.csv("./data/DatasetpourShiny", header = TRUE, sep = ";", quote = "\"", dec = ",", fill = TRUE)
server <- function(input, output) {

  model1 <- glm(Augmentation.creat.26.umolL.en.48H ~
              Cancer.colique.ou.rectal +
              ATCD.maladie.cardiovasculaire +
              ATCD.MTEV +
              Demences +
              Resection.anterieure.rectum +
              Type.colectomie_2 +
              Chimio.porteur.ileostomie +
              Stomie.a.haut.debit +
              Deshydratation.post.op +
              Creatininemie.pre.operatoire +
              Age, family= "binomial", data = data_app)

  model1pred <- reactive ({
Cancer.colique.ou.rectalInput <- input$checkboxGroup1
ATCD.maladie.cardiovasculaireInput <- input$checkboxGroup2
ATCD.MTEVInput <- input$checkboxGroup3
DemencesInput <- input$checkboxGroup4
Resection.anterieure.rectumInput <- input$checkboxGroup5
Type.colectomie_2Input <- input$checkboxGroup6
Chimio.porteur.ileostomieInput <- input$checkboxGroup7
Stomie.a.haut.debitInput <- input$checkboxGroup8
Deshydratation.post.opInput <- input$checkboxGroup9
Creatininemie.pre.operatoireInput <- input$slider1
AgeInput <- input$slider2

    predict(model1,
        newdata = data.frame(
          Cancer.colique.ou.rectal =  Cancer.colique.ou.rectalInput,
          ATCD.maladie.cardiovasculaire = ATCD.maladie.cardiovasculaireInput,
          ATCD.MTEV = ATCD.MTEVInput,
          Demences = DemencesInput,
          Resection.anterieure.rectum = Resection.anterieure.rectumInput,
          Type.colectomie_2 = Type.colectomie_2Input,
          Chimio.porteur.ileostomie  =  Chimio.porteur.ileostomieInput,
          Stomie.a.haut.debit = Stomie.a.haut.debitInput,
          Deshydratation.post.op = Deshydratation.post.opInput,
          Creatininemie.pre.operatoire = Creatininemie.pre.operatoireInput,
          Age = AgeInput
        ))
  })
  output$pred1 <- rendertext({
exp(model1pred())/(1+exp(model1pred()))*100
  })
 }

shinyApp(ui = ui, server = server)
</code>```

答:
On Rstudio :

Go to file in top left corner.

Select save with encoding

select UTF-8

Do this for all R scripts (server.R/app.R)

This worked for me.

Title: Shiny app error sourcing debug

Body:
I'm loading a shiny app built to render a risk with new input variables from a logistic regression model built on a csv file. Any ideas for debug? The error message when loading the app is as follows:

ERROR: Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa   with such message on the R studio console :
Warning in checkEncoding(file) :
  The input file C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Prediction IRA chez ileostomises.R does not seem to be encoded in UTF8
Warning: invalid input found on input connection 'C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Prediction IRA chez ileostomises.R'
Error in parse(file, keep.source = FALSE, srcfile = src, encoding = enc) :
  C:/Users/Vincent/Documents/R Apprentissage/Applications Shiny/Prediction insuffisance renale aigue chez les ileostomises.R/Pr:5:14: unexpected INCOMPLETE_STRING
4: ui <- fluidPage(
5:   titlePanel("Pr
                ^
Warning: Error in sourceUTF8: Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa
Stack trace (innermost first):
    1: runApp
Error : Error sourcing C:\Users\Vincent\AppData\Local\Temp\RtmpATsPEW\filef604271fa

 ui <- fluidPage(
  titlePanel("Prédiction d'insuffisance rénale aiguë chez les iléostomisés"),
   sidebarLayout(
     sidebarPanel(

  checkboxGroupInput("checkboxGroup1", "Cancer colorectal",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup2", "Maladie cardiovasculaire",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup3", "Maladie thrombo-embolique veineuse",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup4","Démence",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup5","Résection rectale antérieure",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup6","Hémicolectomie gauche",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup7","Chimiothérapie per iléostomie",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup8","Iléostomie à haut débit",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  checkboxGroupInput("checkboxGroup9","Deshydratation",
                     choices = list("Absente" = 1,
                                    "Présente" = 2),
                     selected = 1),

  sliderInput("slider1","Créatininémie pré-opératoire", min = 20, max = 400, value = 100),

  sliderInput("slider2", "Age", min = 0, max = 100, value = 50)
),

  mainPanel(
tabPanel("Probabilité de développer une insuffisance rénale aiguë",textOutput("pred1")))
 ))

data_app <- read.csv("./data/DatasetpourShiny", header = TRUE, sep = ";", quote = "\"", dec = ",", fill = TRUE)
server <- function(input, output) {

  model1 <- glm(Augmentation.creat.26.umolL.en.48H ~
              Cancer.colique.ou.rectal +
              ATCD.maladie.cardiovasculaire +
              ATCD.MTEV +
              Demences +
              Resection.anterieure.rectum +
              Type.colectomie_2 +
              Chimio.porteur.ileostomie +
              Stomie.a.haut.debit +
              Deshydratation.post.op +
              Creatininemie.pre.operatoire +
              Age, family= "binomial", data = data_app)

  model1pred <- reactive ({
Cancer.colique.ou.rectalInput <- input$checkboxGroup1
ATCD.maladie.cardiovasculaireInput <- input$checkboxGroup2
ATCD.MTEVInput <- input$checkboxGroup3
DemencesInput <- input$checkboxGroup4
Resection.anterieure.rectumInput <- input$checkboxGroup5
Type.colectomie_2Input <- input$checkboxGroup6
Chimio.porteur.ileostomieInput <- input$checkboxGroup7
Stomie.a.haut.debitInput <- input$checkboxGroup8
Deshydratation.post.opInput <- input$checkboxGroup9
Creatininemie.pre.operatoireInput <- input$slider1
AgeInput <- input$slider2

    predict(model1,
        newdata = data.frame(
          Cancer.colique.ou.rectal =  Cancer.colique.ou.rectalInput,
          ATCD.maladie.cardiovasculaire = ATCD.maladie.cardiovasculaireInput,
          ATCD.MTEV = ATCD.MTEVInput,
          Demences = DemencesInput,
          Resection.anterieure.rectum = Resection.anterieure.rectumInput,
          Type.colectomie_2 = Type.colectomie_2Input,
          Chimio.porteur.ileostomie  =  Chimio.porteur.ileostomieInput,
          Stomie.a.haut.debit = Stomie.a.haut.debitInput,
          Deshydratation.post.op = Deshydratation.post.opInput,
          Creatininemie.pre.operatoire = Creatininemie.pre.operatoireInput,
          Age = AgeInput
        ))
  })
  output$pred1 <- rendertext({
exp(model1pred())/(1+exp(model1pred()))*100
  })
 }

shinyApp(ui = ui, server = server)


来源: stackexchange

问:
What is the right approach for state change?
I am trying to implement this in my app:

Original code:

```<code><Searchbox change={this.onSearchChange}/>
</code>```

But this is not working. While trying several options, I found following codes work:

Code 1:

```<code><Searchbox change={event => setState({/*the state is changed*/})}/>
</code>```

Code 2:

```<code><Searchbox change={event => this.onSearchChange(event)}/>
</code>```

Reading the documentation, I believe I wrote the correct syntax in the first time, but I want to be sure.

答:
```<code><Searchbox change={event => this.onSearchChange(event)}/>
</code>```

This a better option if you want to do any kinds of valiadation/ modification before setting the state in onSearchChange

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement this in my app:

Original code:

<Searchbox change={this.onSearchChange}/>

But this is not working. While trying several options, I found following codes work:

Code 1:

<Searchbox change={event => setState({/*the state is changed*/})}/>

Code 2:

<Searchbox change={event => this.onSearchChange(event)}/>

Reading the documentation, I believe I wrote the correct syntax in the first time, but I want to be sure.

Body:
<Searchbox change={event => this.onSearchChange(event)}/>

This a better option if you want to do any kinds of valiadation/ modification before setting the state in onSearchChange


问:
import module in Class, but NameError when using module in class method
In my python script, I'm trying to import module in class and use the imported module in the class method.

```<code>class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)
</code>```

Howerver, when I try to use the test class, such as

```<code>test("http://test.com")
</code>```

I get the error:

NameError: name 'urllib' is not defined

Why import statement in class body do not take effect?

I use python 3.8.1 in windows 10.

答:
It was self.urllib.parse that you were missing.

If you really want to import a module inside a class you must access it from that class:

```<code>class Test:
    import urllib.parse as ul

    def __init__(self, url):
        urlComponents = self.ul.urlsplit(url)

t1 = Test("www.test.com")
print(t1)
</code>```

Result : <main.Test at 0x5029>

Body:
In my python script, I'm trying to import module in class and use the imported module in the class method.

class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)

Howerver, when I try to use the test class, such as

test("http://test.com")

I get the error:

NameError: name 'urllib' is not defined

Why import statement in class body do not take effect?

I use python 3.8.1 in windows 10.

Body:
It was self.urllib.parse that you were missing.

If you really want to import a module inside a class you must access it from that class:

class Test:
    import urllib.parse as ul

    def __init__(self, url):
        urlComponents = self.ul.urlsplit(url)

t1 = Test("www.test.com")
print(t1)

Result : <main.Test at 0x5029>


问:
Why && in return and casting?
I was looking at the core Java book and the equality test part confused me a bit

What is the meaning of this specific return line, especially with the &&

Why does it need to cast otherObject to Employee when it already know if it's of the same class?

```<code>class Employee
{
...
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal
        if (getClass() != otherObject.getClass())
           return false;
        // now we know otherObject is a non-null Employee
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values
        return name.equals(other.name)
           && salary == other.salary
           && hireDay.equals(other.hireDay);
    }
}
</code>```

答:
It's a logical short-circuiting and operator. It is a shorter (and faster) way to write

```<code>if (name.equals(other.name)) {
    if (salary == other.salary) {
        return hireDay.equals(other.hireDay);
    }
}
return false;
</code>```

(note that the original does not involve branches). As for why it needs a cast for otherObject to Employee; it is precisely because it does not know that otherObject is an Employee - in fact, you have

```<code>public boolean equals(Object otherObject)
</code>```

which means otherObject is an Object (as required by Object.equals(Object)). You need a cast to tell the compiler that at runtime otherObject is an Employee (or throw a class cast exception).

If you expected the compiler to "know" that after

```<code>// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass())
   return false;
</code>```

It's safe to infer otherObject is an Employee, I'm sorry to inform you Java does not make any such inference (currently). Compilers aren't sentient (despite seeming like it sometimes).

Title: Why && in return and casting?

Body:
I was looking at the core Java book and the equality test part confused me a bit

What is the meaning of this specific return line, especially with the &&

Why does it need to cast otherObject to Employee when it already know if it's of the same class?

class Employee
{
...
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal
        if (getClass() != otherObject.getClass())
           return false;
        // now we know otherObject is a non-null Employee
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values
        return name.equals(other.name)
           && salary == other.salary
           && hireDay.equals(other.hireDay);
    }
}

Body:
It's a logical short-circuiting and operator. It is a shorter (and faster) way to write

if (name.equals(other.name)) {
    if (salary == other.salary) {
        return hireDay.equals(other.hireDay);
    }
}
return false;

(note that the original does not involve branches). As for why it needs a cast for otherObject to Employee; it is precisely because it does not know that otherObject is an Employee - in fact, you have

public boolean equals(Object otherObject)

which means otherObject is an Object (as required by Object.equals(Object)). You need a cast to tell the compiler that at runtime otherObject is an Employee (or throw a class cast exception).

If you expected the compiler to "know" that after

// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass())
   return false;

It's safe to infer otherObject is an Employee, I'm sorry to inform you Java does not make any such inference (currently). Compilers aren't sentient (despite seeming like it sometimes).


问:
Return nonexistent right table values as NULL
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');
```

<p>I want to be able to select properties for a <code>thing</code> based on their names, and return <code>NULL</code> if such a property doesn't exist. Here is what I have attempted:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';
</code>```

I wanted the result to be

```<code>  name |   age | foo
---------------------
'John' | '123' | NULL
</code>```

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

答:
And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead

It is considered bad style to use old comma-separated joins. Comma-separated joins were used before explicit joins (INNER JOIN, LEFT OUTER JOIN, etc.) were invented in 1992. One reason for inventing these was that there was no standard syntax for outer joins before. Another was that comma-separated joins are prone to errors and very often less readable. They only exist for compatibility reasons now.

My opinion: Don't even consider using them.

select properties for a thing

You are dealing with a key/value table here. They are a nuisance to work with. Is there a reason for your data model not just to have tables with explicit columns? A data model containing a table things and another properties is about the worst I can think of.

The typical approach to get values from a key/value table is conditional aggregagtion:

```<code>select
  any_value(case when p.name = 'name' then p.value end) as name,
  any_value(case when p.name = 'age' then p.value end) as age,
  any_value(case when p.name = 'foo' then p.value end) as foo
from things as t
join properties p on p.thing_id = t.id
where t.id = 1;
</code>```

If this query is too slow because of too many properties in the table, add a WHERE clause:

```<code>where p.name in ('name', 'age', 'foo')
</code>```

and provide an appropriate index:

```<code>create unique index idx on properties (thing_id, name);
</code>```

in case you don't already have it.

If your MySQL version is old and doesn't support ANY_VALUE then you should consider upgrading. If you don't want to do this or cannot do this, then simply replace ANY_VALUE by MIN or MAX.)

Body:
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');

I want to be able to select properties for a thing based on their names, and return NULL if such a property doesn't exist. Here is what I have attempted:

SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';

I wanted the result to be

  name |   age | foo
---------------------
'John' | '123' | NULL

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

Body:
And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead

It is considered bad style to use old comma-separated joins. Comma-separated joins were used before explicit joins (INNER JOIN, LEFT OUTER JOIN, etc.) were invented in 1992. One reason for inventing these was that there was no standard syntax for outer joins before. Another was that comma-separated joins are prone to errors and very often less readable. They only exist for compatibility reasons now.

My opinion: Don't even consider using them.

select properties for a thing

You are dealing with a key/value table here. They are a nuisance to work with. Is there a reason for your data model not just to have tables with explicit columns? A data model containing a table things and another properties is about the worst I can think of.

The typical approach to get values from a key/value table is conditional aggregagtion:

select
  any_value(case when p.name = 'name' then p.value end) as name,
  any_value(case when p.name = 'age' then p.value end) as age,
  any_value(case when p.name = 'foo' then p.value end) as foo
from things as t
join properties p on p.thing_id = t.id
where t.id = 1;

If this query is too slow because of too many properties in the table, add a WHERE clause:

where p.name in ('name', 'age', 'foo')

and provide an appropriate index:

create unique index idx on properties (thing_id, name);

in case you don't already have it.

If your MySQL version is old and doesn't support ANY_VALUE then you should consider upgrading. If you don't want to do this or cannot do this, then simply replace ANY_VALUE by MIN or MAX.)


问:
coloring containers by tabbing with flutter
I have column with many ((Tabbed)) items, when I tab on one of them it should be colored and the others transparent, and here is my Tabbed classthis image for what I have now with my code</p>

```<code>class Tabbed extends StatefulWidget {
  @override
  _TabbedState createState() => _TabbedState();
}

class _TabbedState extends State<Tabbed> {
  Color color = Colors.transparent;
  @override
  void initState() {
    color = Colors.transparent;
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        print("tab");
        if (color == Colors.transparent){
          setState(() {
            color = Colors.purple;
          });
        }
        else{
          setState(() {
            color = Colors.transparent;
          });
        }
      },
      child: Container(
        height: 100,
        width: 100,
        decoration: BoxDecoration(
          color: color,
          border: Border.all(color: Colors.red,width: 1),
        ),
      ),
    );
  }
}
</code>```

答:
you can simply try creating a model for your boxes and have a boolean property and store the status of each box in a list to know whether the box is tapped or not ,you can also pefer a list of boolean but I prefer creating a list of model as it will allow you to add more properties, I have modified your code a little bit you can see it working here on dartpad as well

```<code>class Tabbed extends StatefulWidget {
  @override
  _TabbedState createState() => _TabbedState();
}

class _TabbedState extends State<Tabbed> {
  Color color = Colors.green;
  @override
  void initState() {
    for(int i=0;i<listLength;i++){
      list1.add(
      TabModel(isTapped: false)); // assigns initial value to false
    }
    for(int i=0;i<listLength;i++){
      list2.add(
      TabModel(isTapped: false)); // assigns initial value to false
    }
  }

  Widget column1(){
    return Column(
    children: List.generate(
          listLength,
          (index) =>GestureDetector(
          onTap: (){
            // this selects only one out of many and disables rest
            for(int i=0;i<list1.length;i++){
              if(i!=index){
                list1[i].isTapped=false;
              }
            };
            setState((){
              list1[index].isTapped = true;
            });
          },
          child:Container(
            margin:EdgeInsets.all(5),
            color: list1[index].isTapped? Colors.red:color,
          height:100,
          width:100
          ))
        ));
  }

  Widget column2(){
    return Column(
    children: List.generate(
          listLength,
          (index) =>GestureDetector(
          onTap: (){
            setState((){
              list2[index].isTapped = !list2[index].isTapped;
            });
          },
          child:Container(
            margin:EdgeInsets.all(5),
            color: list2[index].isTapped? Colors.red:color,
          height:100,
          width:100
          ))
        ));
  }

 List<TabModel> list1 =[];
 List<TabModel> list2 =[];

  int listLength=5;
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget>[
      column1(),
      column2()
    ],);
  }
}
class TabModel{
   bool isTapped = false;
  TabModel({this.isTapped});
}
</code>```

if this is not what you want or if you face any issue understanding any part of the code feel free to drop a comment I would love to help out
the bwlow output shows two independent columns in coumn1 you can select one out of many boxes and in other you can select multiple boxes

Body:
I have column with many ((Tabbed)) items, when I tab on one of them it should be colored and the others transparent, and here is my Tabbed classthis image for what I have now with my code

class Tabbed extends StatefulWidget {
  @override
  _TabbedState createState() => _TabbedState();
}

class _TabbedState extends State<Tabbed> {
  Color color = Colors.transparent;
  @override
  void initState() {
    color = Colors.transparent;
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        print("tab");
        if (color == Colors.transparent){
          setState(() {
            color = Colors.purple;
          });
        }
        else{
          setState(() {
            color = Colors.transparent;
          });
        }
      },
      child: Container(
        height: 100,
        width: 100,
        decoration: BoxDecoration(
          color: color,
          border: Border.all(color: Colors.red,width: 1),
        ),
      ),
    );
  }
}

Body:
you can simply try creating a model for your boxes and have a boolean property and store the status of each box in a list to know whether the box is tapped or not ,you can also pefer a list of boolean but I prefer creating a list of model as it will allow you to add more properties, I have modified your code a little bit you can see it working here on dartpad as well

class Tabbed extends StatefulWidget {
  @override
  _TabbedState createState() => _TabbedState();
}

class _TabbedState extends State<Tabbed> {
  Color color = Colors.green;
  @override
  void initState() {
    for(int i=0;i<listLength;i++){
      list1.add(
      TabModel(isTapped: false)); // assigns initial value to false
    }
    for(int i=0;i<listLength;i++){
      list2.add(
      TabModel(isTapped: false)); // assigns initial value to false
    }
  }

  Widget column1(){
    return Column(
    children: List.generate(
          listLength,
          (index) =>GestureDetector(
          onTap: (){
            // this selects only one out of many and disables rest
            for(int i=0;i<list1.length;i++){
              if(i!=index){
                list1[i].isTapped=false;
              }
            };
            setState((){
              list1[index].isTapped = true;
            });
          },
          child:Container(
            margin:EdgeInsets.all(5),
            color: list1[index].isTapped? Colors.red:color,
          height:100,
          width:100
          ))
        ));
  }

  Widget column2(){
    return Column(
    children: List.generate(
          listLength,
          (index) =>GestureDetector(
          onTap: (){
            setState((){
              list2[index].isTapped = !list2[index].isTapped;
            });
          },
          child:Container(
            margin:EdgeInsets.all(5),
            color: list2[index].isTapped? Colors.red:color,
          height:100,
          width:100
          ))
        ));
  }

 List<TabModel> list1 =[];
 List<TabModel> list2 =[];

  int listLength=5;
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget>[
      column1(),
      column2()
    ],);
  }
}
class TabModel{
   bool isTapped = false;
  TabModel({this.isTapped});
}

if this is not what you want or if you face any issue understanding any part of the code feel free to drop a comment I would love to help out
the bwlow output shows two independent columns in coumn1 you can select one out of many boxes and in other you can select multiple boxes


答: Your Original Code and Code 2 are the same. You need to check again what was your actual issue with Original Code that is was not working

Title: What is the right approach for state change?


问:
file renaming/deleting
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

```<code>import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)
</code>```

答:
In Unix you can use the following command in a Bourne shell (i.e. sh/bash):

```<code>for f in *_passive.sss; do mv -v $f `basename $f _passive.sss`.sss; done
</code>```

ContentLicense: CC BY-SA 3.0

Title: file renaming/deleting

Body:
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)

Body:
In Unix you can use the following command in a Bourne shell (i.e. sh/bash):

for f in *_passive.sss; do mv -v $f `basename $f _passive.sss`.sss; done


问:
Reset the input for shinyalert in R shiny
It will only append the first time I click because input$shinyalert is TRUE after I hit okay. Is there a way to reset the input for shinyalert so that it will re-trigger my observe when I hit action button the second/third.. time in a session.

I tried to assign NULL/FALSE/0 to input$shinyalert (input$shinyalert <- NULL) but it gave me this error.

Warning:
Error in $<-.reactivevalues:
Attempted to assign value to a read-only reactivevalues object
```

<p>Here is my code</p>

<pre class="lang-rb prettyprint-override"><code># observe event for my action button
observeEvent(input$action, {
      shinyalert("","Are you sure?", type="warning", showCancelButton = TRUE)
      })

observe({
      req(input$shinyalert)
      isolate({
        newrow <- data.frame(a = "fisrt",
                             b = "second",
                             c = "third")

      # appending to mytable in SQL server
      dbWriteTable(conn, "mytable", newrow, append = TRUE)
      })
    })
</code>```

答:
Can't you use a R callback function, like this:

```<code>library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),
  actionButton("btn", "Append row")
)

server <- function(input, output, session){

  appendTable <- function(){
    newrow <- data.frame(a = "fisrt",
                         b = "second",
                         c = "third")
    dbWriteTable(conn, "mytable", newrow, append = TRUE)
  }

  observeEvent(input[["btn"]], {
    shinyalert("", "Are you sure?", type = "warning", showCancelButton = TRUE,
               callbackR = function(x){
                 if(x) appendTable()
               })
  })

}

shinyApp(ui, server)
</code>```

Otherwise, to reset, you can use a JS callback:

```<code>  observeEvent(input[["btn"]], {
    shinyalert("", "Are you sure?", type = "warning", showCancelButton = TRUE,
               callbackJS = "function(x){
                 setTimeout(function(){Shiny.setInputValue('shinyalert', false);}, 0);
               }")
  })
</code>```

Body:
It will only append the first time I click because input$shinyalert is TRUE after I hit okay. Is there a way to reset the input for shinyalert so that it will re-trigger my observe when I hit action button the second/third.. time in a session.

I tried to assign NULL/FALSE/0 to input$shinyalert (input$shinyalert <- NULL) but it gave me this error.

Warning:
Error in $<-.reactivevalues:
Attempted to assign value to a read-only reactivevalues object

Here is my code

# observe event for my action button
observeEvent(input$action, {
      shinyalert("","Are you sure?", type="warning", showCancelButton = TRUE)
      })

observe({
      req(input$shinyalert)
      isolate({
        newrow <- data.frame(a = "fisrt",
                             b = "second",
                             c = "third")

      # appending to mytable in SQL server
      dbWriteTable(conn, "mytable", newrow, append = TRUE)
      })
    })

Body:
Can't you use a R callback function, like this:

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),
  actionButton("btn", "Append row")
)

server <- function(input, output, session){

  appendTable <- function(){
    newrow <- data.frame(a = "fisrt",
                         b = "second",
                         c = "third")
    dbWriteTable(conn, "mytable", newrow, append = TRUE)
  }

  observeEvent(input[["btn"]], {
    shinyalert("", "Are you sure?", type = "warning", showCancelButton = TRUE,
               callbackR = function(x){
                 if(x) appendTable()
               })
  })

}

shinyApp(ui, server)

Otherwise, to reset, you can use a JS callback:

  observeEvent(input[["btn"]], {
    shinyalert("", "Are you sure?", type = "warning", showCancelButton = TRUE,
               callbackJS = "function(x){
                 setTimeout(function(){Shiny.setInputValue('shinyalert', false);}, 0);
               }")
  })


问:
Departments not showing in Laravel
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

```<code>
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }
</code>```

create_departments_table

```<code>public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }
</code>```

Department.php

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

</code>```

User.php

```<code><?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}
</code>```

dashboard.blade.php

```<code> @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

<div class="row">
  <div class="col-md-12">
    <div class="card">
      @if (session('status'))
      <div class="alert alert-success" role="alert">
        {{ session('status') }}
      </div>
      @endif
      <div class="card-header">
        <h4 class="card-title"> DASHBOARD </h4>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table">
            <thead class=" text-primary">
              <th>ID</th>
              <th>Name</th>
              <th>Last Name</th>
              <th>Department</th>
            </thead>
            <tbody>
            @foreach($departments as $department)
              <td> {{$department->name}}</td>
              @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  @endsection

  @section('scripts')

  @endsection
</code>```

DashboardController.php

```<code>class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}
</code>```

web.php

```<code>
Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
</code>```

I have tried this too but still the same.

```<code><td> {{$department->name}}</td>

</code>```

```<code>@foreach($departments->name as $department)
<td> {{$department}}</td>
@endforeach
</code>```

答:
In your web.php,
replace this:

```<code>Route::get('/dashboard', function () {
    return view('admin.dashboard');
});
</code>```

with this:

```<code>Route::get('/dashboard', 'Admin\DashboardController@index' );
</code>```

In you Dashboard controller, replace this:

```<code>public function index()
{
    $users= User::all();
    $departments = Department::with('users')->first();
   // return view('admin.dashboard')->with('departments',$departments)->with('users',$users);
    // $departments = Department::with('users')->where('users.department_id','=','departments.id')->first();
    // dd($departments);
     dd($users);
    // return view('admin.dashboard',compact('departments','users'));
}
</code>```

with this:

```<code>public function index()
{
    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users'));
}
</code>```

Title: Departments not showing in Laravel

Body:
I have two tables ,departments and users.One department has many users.One user belongs to one department.Im trying to write a foreach loop to display the names of the departments with its users but i get this error.

Facade\Ignition\Exceptions\ViewException
  Undefined variable: departments (View: C:\xampp\htdocs\Laravel\blog2\resources\views\admin\dashboard.blade.php)

create_users_table

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }

create_departments_table

public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

Department.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{

    protected $table = 'departments';
    protected $fillable = [
        'name',
    ];
    protected $primaryKey = 'id';

public function department()
{
    return $this->belongsTo(Department::class);
}

}

User.php

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     public function department()
    {
        return $this->belongsTo(Department::class);
    }

}

dashboard.blade.php

 @extends ('layouts.master')

@section('title')
DASHBOARD | Admin
@endsection

@section('content')

      @if (session('status'))

        {{ session('status') }}

      @endif

 DASHBOARD

              ID
              Name
              Last Name
              Department

            @foreach($departments as $department)
               {{$department->name}}
              @endforeach

  @endsection

  @section('scripts')

  @endsection

DashboardController.php

class DashboardController extends Controller
{  public function index()
    {
      $users= User::all();
      foreach($users as $user)
      {
        echo $user->department->name;
        echo $user->name;
      }
   }
}

web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth','admin']], function  () {

    Route::get('/dashboard', function () {
        $users= User::all();
        $departments = Department::with('users')->get();
        dd($departments);
        return view('admin.dashboard',compact('departments','users'));
    });
    //Route::get('/dashboard', "Admin\DashboardController@index");
   // Route::get('/dashboard{id}', "Admin\DashboardController@index");
    Route::get('/role-register','Admin\DashboardController@registered');
    Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');
    Route::put('/role-register-update/{id}', 'Admin\DashboardController@registerupdate');
    Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');
    Route::post('/save-user', 'Admin\DashboardController@store');

    Route::get('/department', 'Admin\DepartmentController@index');
    Route::post('/save-department', 'Admin\DepartmentController@store');
    Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');
    Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
    Route::delete('/department-delete/{id}', 'Admin\DepartmentController@delete');

});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

I have tried this too but still the same.

 {{$department->name}}

@foreach($departments->name as $department)
 {{$department}}
@endforeach

Body:
In your web.php,
replace this:

Route::get('/dashboard', function () {
    return view('admin.dashboard');
});

with this:

Route::get('/dashboard', 'Admin\DashboardController@index' );

In you Dashboard controller, replace this:

public function index()
{
    $users= User::all();
    $departments = Department::with('users')->first();
   // return view('admin.dashboard')->with('departments',$departments)->with('users',$users);
    // $departments = Department::with('users')->where('users.department_id','=','departments.id')->first();
    // dd($departments);
     dd($users);
    // return view('admin.dashboard',compact('departments','users'));
}

with this:

public function index()
{
    $users= User::all();
    $departments = Department::with('users')->get();
    return view('admin.dashboard',compact('departments','users'));
}


问:
React-Redux Configuration with Typescript Error on Interface
Im trying to learn how to setup Typescript with React-Redux so that in the future i do everything with TS, just for the sake of learning.
I only want to have an action that will generate a bi dimensional array of numbers.
So this is what im doing:

My Action

```<code>import { GENERATE_PINS, AppActions } from '../types/actions';
import { generateAllPins } from '../utils/generatePins';
import { AppState } from '../configStore';
import { PinArr } from '../types/pinType';
import { Dispatch } from 'react';
// TypeScript infers that this function is returning SendMessageAction

export const getPin = (pins: PinArr): AppActions => ({
  type: GENERATE_PINS,
  pins
});

export const startGeneratePin = () => {
  return (dispatch: Dispatch<AppActions>, getState: () => AppState) => {
    const pins = generateAllPins();
    return dispatch(
      getPin({
        pins
      })
    );
  };
};
</code>```

My reducer

```<code>import { PinArr } from '../types/pinType';
import { GENERATE_PINS, PinActionTypes } from '../types/actions';

const initialState: PinArr = {
  pins: []
};

export function pinReducer(
  state = initialState,
  action: PinActionTypes
): PinArr {
  switch (action.type) {
    case GENERATE_PINS:
      return {
        pins: [...state.pins, ...action.pin]
      };
  }
}
</code>```

My types

```<code>import { PinArr } from './pinType';

export const GENERATE_PINS = 'GENERATE_PINS';

interface GeneratePin {
  type: typeof GENERATE_PINS;
  pin: PinArr;
}

export type PinActionTypes = GeneratePin;

export type AppActions = PinActionTypes;
</code>```

And my data interface

```<code>export interface PinArr {
  pins: Array<Array<number>>;
}
</code>```

My pins should be a result like [ [1,2,3,4], [2,3,4,5], [2,6,4,2]...]
So thats why im doing Array>

Right now i have two erros:
ON pin action

```<code>Type '{ type: "GENERATE_PINS"; pins: PinArr; }' is not assignable to type 'GeneratePin'.
  Object literal may only specify known properties, but 'pins' does not exist in type 'GeneratePin'. Did you mean to write 'pin'?
</code>```

On reducer

```<code>Type 'PinArr' is not an array type.
</code>```

Anyone can help me ? I feel like once i understand and solve this interface types (and this is why im using TS, to evolve as a developer overall) i will feel confortable using TS with React.
Please?

答:
You've confused yourself because of your naming convention (names matter)! What you have declared as PinsArray is actually the slice of state that PinReducer handles. I think it will make much more sense in your code if you name things like so:

type PinsArray = number[][]

interface PinState {
    pins: PinsArray
}
```

Body:
Im trying to learn how to setup Typescript with React-Redux so that in the future i do everything with TS, just for the sake of learning.
I only want to have an action that will generate a bi dimensional array of numbers.
So this is what im doing:

My Action

import { GENERATE_PINS, AppActions } from '../types/actions';
import { generateAllPins } from '../utils/generatePins';
import { AppState } from '../configStore';
import { PinArr } from '../types/pinType';
import { Dispatch } from 'react';
// TypeScript infers that this function is returning SendMessageAction

export const getPin = (pins: PinArr): AppActions => ({
  type: GENERATE_PINS,
  pins
});

export const startGeneratePin = () => {
  return (dispatch: Dispatch<AppActions>, getState: () => AppState) => {
    const pins = generateAllPins();
    return dispatch(
      getPin({
        pins
      })
    );
  };
};

My reducer

import { PinArr } from '../types/pinType';
import { GENERATE_PINS, PinActionTypes } from '../types/actions';

const initialState: PinArr = {
  pins: []
};

export function pinReducer(
  state = initialState,
  action: PinActionTypes
): PinArr {
  switch (action.type) {
    case GENERATE_PINS:
      return {
        pins: [...state.pins, ...action.pin]
      };
  }
}

My types

import { PinArr } from './pinType';

export const GENERATE_PINS = 'GENERATE_PINS';

interface GeneratePin {
  type: typeof GENERATE_PINS;
  pin: PinArr;
}

export type PinActionTypes = GeneratePin;

export type AppActions = PinActionTypes;

And my data interface

export interface PinArr {
  pins: Array<Array<number>>;
}

My pins should be a result like [ [1,2,3,4], [2,3,4,5], [2,6,4,2]...]
So thats why im doing Array>

Right now i have two erros:
ON pin action

Type '{ type: "GENERATE_PINS"; pins: PinArr; }' is not assignable to type 'GeneratePin'.
  Object literal may only specify known properties, but 'pins' does not exist in type 'GeneratePin'. Did you mean to write 'pin'?

On reducer

Type 'PinArr' is not an array type.

Anyone can help me ? I feel like once i understand and solve this interface types (and this is why im using TS, to evolve as a developer overall) i will feel confortable using TS with React.
Please?


答:
Route::get('/dashboard', function () {
    return view('admin.dashboard');
});
```

Here's your problem. You're returning the dashboard view without passing it the list of departments.

This route should be using the DashboardController@index ( and your commented code should be uncommented) - which gets the list of departments and returns the view while passing in the list.

Better yet if you used the URL /departments and a DepartmentsController...

Title: Departments not showing in Laravel

Body:
Route::get('/dashboard', function () {
    return view('admin.dashboard');
});

Here's your problem. You're returning the dashboard view without passing it the list of departments.

This route should be using the DashboardController@index ( and your commented code should be uncommented) - which gets the list of departments and returns the view while passing in the list.

Better yet if you used the URL /departments and a DepartmentsController...


问:
How to disable selection or grey out the for particular value in List of value items of drop down list (<ng-selectize> or <options> ) in anguarl 7
I have scenario where i need to populate list of values for a dropdown list in angular 7 app. But i should grey out the particular value from that list based on condition or flag.

Eg: I am populating alphabets in UI with drop down list (a to z letters)-> among them i need to disable letter "N" when user try to select that .

Can any one suggest me how we can do in angular 7

答:
It could be done by binding a dynamic value to [disabled] property.

Component:

```<code>export class AppComponent  {
  colors =  [
    {value: "Dark Green"},
    {value: "Red"},
    {value: "Dark Grey"},
    {value: "Beige"},
  ];

  fruits =  [
    {value: "Apple", disabled: false},
    {value: "Passion fruit", disabled: true},
    {value: "Dragon fruit", disabled: true},
    {value: "Orange", disabled: false},
  ];

  public ifColorDark(color: string): boolean {
    return color.indexOf('Dark' || 'dark') !== -1;
  }
}
</code>```

Template:

```<code><select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="ifColorDark(color.value)" *ngFor="let color of colors" [ngValue]="color.value">{{ color.value }}</option>
</select>

<select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="fruit.disabled" *ngFor="let fruit of fruits" [ngValue]="fruit.value">{{ fruit.value }}</option>
</select>
</code>```

Working example: Stackblitz

Body:
It could be done by binding a dynamic value to [disabled] property.

Component:

export class AppComponent  {
  colors =  [
    {value: "Dark Green"},
    {value: "Red"},
    {value: "Dark Grey"},
    {value: "Beige"},
  ];

  fruits =  [
    {value: "Apple", disabled: false},
    {value: "Passion fruit", disabled: true},
    {value: "Dragon fruit", disabled: true},
    {value: "Orange", disabled: false},
  ];

  public ifColorDark(color: string): boolean {
    return color.indexOf('Dark' || 'dark') !== -1;
  }
}

Template:

<select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="ifColorDark(color.value)" *ngFor="let color of colors" [ngValue]="color.value">{{ color.value }}</option>
</select>

<select type="number" [(ngModel)]="selectedItem">
  <option [disabled]="fruit.disabled" *ngFor="let fruit of fruits" [ngValue]="fruit.value">{{ fruit.value }}</option>
</select>

Working example: Stackblitz


问:
Need guidance understanding head first C# interfaces
I'd like some help understanding interface basics. Could someone please tell me if my comments below are accurate, and explain things further?</p>

```<code>static void Main(string[] args)
        {
            //Creating a new ScaryScary object. The value of FunnyFunny's funnyThingIHave is now "big
            //shoes". The value of ScaryScary's numberOfScaryThings is 14.
            ScaryScary fingersTheClown = new ScaryScary("big shoes", 14);

            //Creating a new reference called someFunnyClown and pointing it to the ScaryScary
            //object? We still have the fingersTheClown object's values in place. How can we still
            //use ScaryScary object's values if we are upcasting to FunnyFunny?
            FunnyFunny someFunnyClown = fingersTheClown;

            //Downcasting back to ScaryScary object (same as creating a new ScaryScary object)?
            //We can use IScaryClown interface reference because ScaryScary implements IScaryClown.
            //Why we first made a ScaryScary object, then cast it to FunnyFunny object, and then cast
            //back to ScaryScary object?
            IScaryClown someOtherScaryClown = someFunnyClown as ScaryScary;

            //Is this the FunnyFunny's Honk() method? Does someOtherScaryClown now have both
            //ScaryScary properties and methods and FunnyFunny's properties and methods?
            someOtherScaryClown.Honk();

            //Now calling the someOtherScaryClown(which is both ScaryScary and FunnyFunny object at
            //the same time?) ScaryThingIHave method.
            Console.WriteLine(someOtherScaryClown.ScaryThingIHave);

            //Calling the someOtherScaryClown ScareLittleChildren() method.
            //My question is why we need the second and third steps. Couldn't we get the same thing
            //done with just the ScaryScary fingersTheClown = new ScaryScary("big shoes", 14) line?
            someOtherScaryClown.ScareLittleChildren();
            Console.ReadKey();
        }

class FunnyFunny : IClown
    {
        public FunnyFunny(string funnyThingIHave)
        {
            this.funnyThingIHave = funnyThingIHave;
        }
        protected string funnyThingIHave;
        public string FunnyThingIHave
        {
            get { return "Hi kids! I have " + funnyThingIHave; }
        }
        public void Honk()
        {
            Console.WriteLine(this.FunnyThingIHave);
        }
    }

class ScaryScary : FunnyFunny, IScaryClown
    {
        public ScaryScary(string funnyThingIHave,
                          int numberOfScaryThings)
            : base(funnyThingIHave)
        {
            this.numberOfScaryThings = numberOfScaryThings;
        }
        private int numberOfScaryThings;
        public string ScaryThingIHave
        {
            get { return "I have " + numberOfScaryThings + " spiders"; }
        }
        public void ScareLittleChildren()
        {
            Console.WriteLine("You can’t have my "
                             + base.funnyThingIHave);
        }
    }

interface IClown
    {
        string FunnyThingIHave { get; }
        void Honk();
    }

interface IScaryClown : IClown
    {
        string ScaryThingIHave { get; }
        void ScareLittleChildren();
    }
</code>```

答:
Your code and implementation looks fine, you can insert a break point and run in debug mode and navigate using Step into in Visual studio, that will help you understand the flow

Here's the notes that I had maintain to understand interfaces better. Hope this would help clarify things

What ?

Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.

In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes

Now Why ?

Improves code re-usability

Lets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.

With Interface you isolate the different implementation from the Contract

Live Scenario Day 1

You were asked to create an App to Draw Circle and Triangle

```<code>interface IShapes
{
   void DrawShape();

 }

class Circle : IShapes
{

    public void DrawShape()
    {
        Console.WriteLine("Implementation to Draw a Circle");
    }
}

Class Triangle: IShapes
{
     public void DrawShape()
    {
        Console.WriteLine("Implementation to draw a Triangle");
    }
}
</code>```

```<code>static void Main()
{
     List <IShapes> shapes = new List<IShapes>();
        shapes.Add(new Circle());
        shapes.Add(new Triangle());

        foreach(var shape in shapes)
        {
            shape.DrawShape();
        }
}
</code>```

Live Scenario Day 2

If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());

Body:
I'd like some help understanding interface basics. Could someone please tell me if my comments below are accurate, and explain things further?

static void Main(string[] args)
        {
            //Creating a new ScaryScary object. The value of FunnyFunny's funnyThingIHave is now "big
            //shoes". The value of ScaryScary's numberOfScaryThings is 14.
            ScaryScary fingersTheClown = new ScaryScary("big shoes", 14);

            //Creating a new reference called someFunnyClown and pointing it to the ScaryScary
            //object? We still have the fingersTheClown object's values in place. How can we still
            //use ScaryScary object's values if we are upcasting to FunnyFunny?
            FunnyFunny someFunnyClown = fingersTheClown;

            //Downcasting back to ScaryScary object (same as creating a new ScaryScary object)?
            //We can use IScaryClown interface reference because ScaryScary implements IScaryClown.
            //Why we first made a ScaryScary object, then cast it to FunnyFunny object, and then cast
            //back to ScaryScary object?
            IScaryClown someOtherScaryClown = someFunnyClown as ScaryScary;

            //Is this the FunnyFunny's Honk() method? Does someOtherScaryClown now have both
            //ScaryScary properties and methods and FunnyFunny's properties and methods?
            someOtherScaryClown.Honk();

            //Now calling the someOtherScaryClown(which is both ScaryScary and FunnyFunny object at
            //the same time?) ScaryThingIHave method.
            Console.WriteLine(someOtherScaryClown.ScaryThingIHave);

            //Calling the someOtherScaryClown ScareLittleChildren() method.
            //My question is why we need the second and third steps. Couldn't we get the same thing
            //done with just the ScaryScary fingersTheClown = new ScaryScary("big shoes", 14) line?
            someOtherScaryClown.ScareLittleChildren();
            Console.ReadKey();
        }

class FunnyFunny : IClown
    {
        public FunnyFunny(string funnyThingIHave)
        {
            this.funnyThingIHave = funnyThingIHave;
        }
        protected string funnyThingIHave;
        public string FunnyThingIHave
        {
            get { return "Hi kids! I have " + funnyThingIHave; }
        }
        public void Honk()
        {
            Console.WriteLine(this.FunnyThingIHave);
        }
    }

class ScaryScary : FunnyFunny, IScaryClown
    {
        public ScaryScary(string funnyThingIHave,
                          int numberOfScaryThings)
            : base(funnyThingIHave)
        {
            this.numberOfScaryThings = numberOfScaryThings;
        }
        private int numberOfScaryThings;
        public string ScaryThingIHave
        {
            get { return "I have " + numberOfScaryThings + " spiders"; }
        }
        public void ScareLittleChildren()
        {
            Console.WriteLine("You can’t have my "
                             + base.funnyThingIHave);
        }
    }

interface IClown
    {
        string FunnyThingIHave { get; }
        void Honk();
    }

interface IScaryClown : IClown
    {
        string ScaryThingIHave { get; }
        void ScareLittleChildren();
    }

Body:
Your code and implementation looks fine, you can insert a break point and run in debug mode and navigate using Step into in Visual studio, that will help you understand the flow

Here's the notes that I had maintain to understand interfaces better. Hope this would help clarify things

What ?

Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.

In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes

Now Why ?

Improves code re-usability

Lets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.

With Interface you isolate the different implementation from the Contract

Live Scenario Day 1

You were asked to create an App to Draw Circle and Triangle

interface IShapes
{
   void DrawShape();

 }

class Circle : IShapes
{

    public void DrawShape()
    {
        Console.WriteLine("Implementation to Draw a Circle");
    }
}

Class Triangle: IShapes
{
     public void DrawShape()
    {
        Console.WriteLine("Implementation to draw a Triangle");
    }
}

static void Main()
{
     List <IShapes> shapes = new List<IShapes>();
        shapes.Add(new Circle());
        shapes.Add(new Triangle());

        foreach(var shape in shapes)
        {
            shape.DrawShape();
        }
}

Live Scenario Day 2

If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());


问:
Calculating Pearson correlation
I'm trying to calculate the Pearson correlation coefficient of two variables. These variables are to determine if there is a relationship between number of postal codes to a range of distances. So I want to see if the number of postal codes increases/decreases as the distance ranges changes.

I'll have one list which will count the number of postal codes within a distance range and the other list will have the actual ranges.

Is it ok to have a list that contain a range of distances? Or would it be better to have a list like this [50, 100, 500, 1000] where each element would then contain ranges up that amount. So for example the list represents up to 50km, then from 50km to 100km and so on.

答:
try this: </p>

```<code> val=Top15[['Energy Supply per Capita','Citable docs per Capita']].rank().corr(method='pearson')
</code>```

Title: Calculating Pearson correlation

Body:
try this:

 val=Top15[['Energy Supply per Capita','Citable docs per Capita']].rank().corr(method='pearson')


问:
convert model class in dotnet core to json
I need to convert my entity framework entities for which I have created a model classes to json.

In other words i need to generate a json model from my entities. Is that possible please?

I have searched in internet, all I found is about serializing objects, but that does not serve my need, I don't to get the objects on json, I need the class it self to be converted to JSON.

enter image description here

Code:

```<code>class :
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public ICollection<Enrollment> Enrollments { get; set; }
    }
</code>```

What I need :

```<code>key : CourseID,
name : Course,
Properties:
{
CourseID: Int,
Title: String,
credits: Int
...
}
</code>```

答:
This will work with simple properties like strings and int, direct reference types, arrays and generics. Although the generic will just be an object and not indicate whether it's a collection or something else.

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;

namespace ClassObject
{
    public class Course
    {
        public Collection<Enrollment> EnrollmentsGeneric { get; set; }
        public Enrollment[] EnrollmentsArray { get; set; }
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
    }

    public class Enrollment
    {
        public int Id { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dict = GetProps(typeof(Course));
            Console.WriteLine(JsonConvert.SerializeObject(dict));
        }

        private static Dictionary<string, object> GetProps(Type type)
        {
            var dict = new Dictionary<string, object> {["name"] = type.Name};
            var props = new Dictionary<string, object>();
            dict["properties"] = props;
            var p = type.GetProperties();

            foreach (var prop in p)
            {
                if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
                    props[prop.Name] = prop.PropertyType.ToString();
                else if (prop.PropertyType.IsArray)
                {
                    props[prop.Name] = new[]
                    {
                        GetProps(prop.PropertyType)
                    };
                }
                else if (prop.PropertyType.IsGenericType)
                {
                    var itemType = prop.PropertyType.GetGenericArguments()[0];
                    props[prop.Name] = GetProps(itemType);
                }
                else
                {
                    props[prop.Name] = GetProps(prop.PropertyType);
                }
            }

            return dict;
        }
    }
}
</code>```

Output

```<code>{
    "name": "Course",
    "properties": {
        "EnrollmentsGeneric": {
            "name": "Enrollment",
            "properties": {
                "Id": "System.Int32"
            }
        },
        "EnrollmentsArray": [
            {
                "name": "Enrollment[]",
                "properties": {
                    "Length": "System.Int32",
                    "LongLength": "System.Int64",
                    "Rank": "System.Int32",
                    "SyncRoot": {
                        "name": "Object",
                        "properties": {}
                    },
                    "IsReadOnly": "System.Boolean",
                    "IsFixedSize": "System.Boolean",
                    "IsSyn\r\nchronized": "System.Boolean"
                }
            }
        ],
        "CourseID": "System.Int32",
        "Title": "System.String",
        "Credits": "System.Int32"
    }
}
</code>```

Body:
I need to convert my entity framework entities for which I have created a model classes to json.

In other words i need to generate a json model from my entities. Is that possible please?

I have searched in internet, all I found is about serializing objects, but that does not serve my need, I don't to get the objects on json, I need the class it self to be converted to JSON.

enter image description here

Code:

class :
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public ICollection<Enrollment> Enrollments { get; set; }
    }

What I need :

key : CourseID,
name : Course,
Properties:
{
CourseID: Int,
Title: String,
credits: Int
...
}

Body:
This will work with simple properties like strings and int, direct reference types, arrays and generics. Although the generic will just be an object and not indicate whether it's a collection or something else.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;

namespace ClassObject
{
    public class Course
    {
        public Collection<Enrollment> EnrollmentsGeneric { get; set; }
        public Enrollment[] EnrollmentsArray { get; set; }
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
    }

    public class Enrollment
    {
        public int Id { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dict = GetProps(typeof(Course));
            Console.WriteLine(JsonConvert.SerializeObject(dict));
        }

        private static Dictionary<string, object> GetProps(Type type)
        {
            var dict = new Dictionary<string, object> {["name"] = type.Name};
            var props = new Dictionary<string, object>();
            dict["properties"] = props;
            var p = type.GetProperties();

            foreach (var prop in p)
            {
                if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
                    props[prop.Name] = prop.PropertyType.ToString();
                else if (prop.PropertyType.IsArray)
                {
                    props[prop.Name] = new[]
                    {
                        GetProps(prop.PropertyType)
                    };
                }
                else if (prop.PropertyType.IsGenericType)
                {
                    var itemType = prop.PropertyType.GetGenericArguments()[0];
                    props[prop.Name] = GetProps(itemType);
                }
                else
                {
                    props[prop.Name] = GetProps(prop.PropertyType);
                }
            }

            return dict;
        }
    }
}

Output

{
    "name": "Course",
    "properties": {
        "EnrollmentsGeneric": {
            "name": "Enrollment",
            "properties": {
                "Id": "System.Int32"
            }
        },
        "EnrollmentsArray": [
            {
                "name": "Enrollment[]",
                "properties": {
                    "Length": "System.Int32",
                    "LongLength": "System.Int64",
                    "Rank": "System.Int32",
                    "SyncRoot": {
                        "name": "Object",
                        "properties": {}
                    },
                    "IsReadOnly": "System.Boolean",
                    "IsFixedSize": "System.Boolean",
                    "IsSyn\r\nchronized": "System.Boolean"
                }
            }
        ],
        "CourseID": "System.Int32",
        "Title": "System.String",
        "Credits": "System.Int32"
    }
}


问:
C# DTLS implementation that uses X509Certificate2 certificates
I am trying to create a CoAP server that uses certificate-based DTLS to encrypt the data in transmission.  I am using the CoAP-CSharp Nuget package to set up the server, however, I am not having much joy in getting our RSA X509 certificates to work with it. There does not seem to be much documentation on how to translate the X509Certificate2 object into the required OneKeys for the DTLSEndPoint.

Has anyone managed to do this?

答:
```<code>public TlsKeyPair(byte[] certificate, OneKey privateKey)

public TlsKeyPair(X509CertificateStructure[] certificateArray, OneKey privateKey)
</code>```

The one key seems to be the private key for your certificate, not the certificate itself. Ensure, that you have access to that private key, otherwise it will not be possible to execute such an handshake.

Body:
public TlsKeyPair(byte[] certificate, OneKey privateKey)

public TlsKeyPair(X509CertificateStructure[] certificateArray, OneKey privateKey)

The one key seems to be the private key for your certificate, not the certificate itself. Ensure, that you have access to that private key, otherwise it will not be possible to execute such an handshake.


问:
JavaScript get one property from an object inside of an array
I have an array of movies objects with the properties: movieName, grade, and position. For example these objects look like:

```<code>var movies = [ { movieName: "bee movie", grade: 3, position 1},
               { movieName: "Shrek", grade: 5, position: 2} ];
</code>```

I want to get the movieName property of an object. To decide which object from the movies array I want the movieName from I create a variable named arrayPosition which is a random number between 0 and the length of the array - 1:

```<code>arrayPosition = Math.floor(Math.random() * movies.length );
</code>```

For example:

var movies = [{
    movieName: "Incredibles",
    grade: 4,
    position: 1
  },
  {
    movieName: "Bolt",
    grade: 5,
    position: 2
  }
];

const arrayPosition = Math.floor(Math.random() * movies.length);

console.log(movies[arrayPosition].movieName);```

In this case I would like it to console either "Incredibles" or "Bolt" depending on if arrayPosition is 0 or 1 but it only consoles undefined.

I have seen solutions to similar problems but in those cases the position of the object in the array was not a variable but a decided number. For some reason this difference make it not work. How do I get only the movieName property from an object in the array?

答:
Your example code works correctly.

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1},
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = Math.floor(Math.random() * movies.length)
console.log(movies[arrayPosition].movieName)```
</div>
</div>
</p>
<p>If you knew that you always wanted to <code>console.log</code> the title of the 2nd movie in the array, you could instead do:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1},
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = 1

console.log(movies[arrayPosition].movieName)</code>```

Remember that:

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.

Using an invalid index number returns undefined.

Body:
I have an array of movies objects with the properties: movieName, grade, and position. For example these objects look like:

var movies = [ { movieName: "bee movie", grade: 3, position 1},
               { movieName: "Shrek", grade: 5, position: 2} ];

I want to get the movieName property of an object. To decide which object from the movies array I want the movieName from I create a variable named arrayPosition which is a random number between 0 and the length of the array - 1:

arrayPosition = Math.floor(Math.random() * movies.length );

For example:

var movies = [{
    movieName: "Incredibles",
    grade: 4,
    position: 1
  },
  {
    movieName: "Bolt",
    grade: 5,
    position: 2
  }
];

const arrayPosition = Math.floor(Math.random() * movies.length);

console.log(movies[arrayPosition].movieName);

In this case I would like it to console either "Incredibles" or "Bolt" depending on if arrayPosition is 0 or 1 but it only consoles undefined.

I have seen solutions to similar problems but in those cases the position of the object in the array was not a variable but a decided number. For some reason this difference make it not work. How do I get only the movieName property from an object in the array?

Body:
Your example code works correctly.

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1},
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = Math.floor(Math.random() * movies.length)
console.log(movies[arrayPosition].movieName)

If you knew that you always wanted to console.log the title of the 2nd movie in the array, you could instead do:

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1},
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = 1

console.log(movies[arrayPosition].movieName)

Remember that:

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.

Using an invalid index number returns undefined.


问:
For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves
I have this test of nodejs when testing I get a error of done function not declared.

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
My test code is, I have the done call back but still getting the error to call the done();

```<code>    it('remove existing subdocument', (done) => {
    const Vic = new User({
      name: 'Vic',
      posts: [{ title: 'Leaning Nodejs' }]
    });

    vic.save()
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        const post = user.posts[0];
        post.remove();
        return user.save();
      })
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        assert(user.posts.length === 0);
        done();
      });
  });
</code>```

答:
Happe with me when I returned back maintaining an old node-module from Node6 to Node 13. The fix is simple :

adding a file mocha.opts under the folder of tests.

The content of this file is one line : --timeout 10000

Body:
I have this test of nodejs when testing I get a error of done function not declared.

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
My test code is, I have the done call back but still getting the error to call the done();

    it('remove existing subdocument', (done) => {
    const Vic = new User({
      name: 'Vic',
      posts: [{ title: 'Leaning Nodejs' }]
    });

    vic.save()
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        const post = user.posts[0];
        post.remove();
        return user.save();
      })
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        assert(user.posts.length === 0);
        done();
      });
  });