问:
Delete items from a dict list containing google drive flies
I need to delete some items from a dict list. This list is produced by a call to Google Drive Rest Api.

I've tried several code samples but I can't make it work. I'm a Python newbie.

```<code>#this is the Google Api call
theFiles = drive_service.files().list(fields="files(id,name,modifiedTime, size, fileExtension)").execute()

#here I am trying to iterate the results and delete all items that refer to a "temp" file:

for k, v in theFiles.items():
    if v[4]=="tmp":
        del theFiles[k]
</code>```

I was expecting that records containing a "tmp" extension would be deleted from this list, however I can't make it work.

I thought that v[4] whould refer to the "fileExtension" field of the dictionary. However, when I debug I see that v[4] contains the whole item, for example:

```<code>{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC', 'modifiedTime': '2019-05-03T18:59:19.000Z', 'name': '~$ LENGUA PROG.docx', 'size': '162'}
</code>```

Please help me understand how to write the right code to delete items with the ".tmp" extension.

答:
Thank you guys for your help, that gave me a clue on how to do this.
After some research I ended up using comprehension:

```<code>dicFiles[:]  = [x for x in dicFiles if x['name'].endswith('.tmp')]
</code>```

That does the job.

Body:
I need to delete some items from a dict list. This list is produced by a call to Google Drive Rest Api.

I've tried several code samples but I can't make it work. I'm a Python newbie.

#this is the Google Api call
theFiles = drive_service.files().list(fields="files(id,name,modifiedTime, size, fileExtension)").execute()

#here I am trying to iterate the results and delete all items that refer to a "temp" file:

for k, v in theFiles.items():
    if v[4]=="tmp":
        del theFiles[k]

I was expecting that records containing a "tmp" extension would be deleted from this list, however I can't make it work.

I thought that v[4] whould refer to the "fileExtension" field of the dictionary. However, when I debug I see that v[4] contains the whole item, for example:

{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC', 'modifiedTime': '2019-05-03T18:59:19.000Z', 'name': '~$ LENGUA PROG.docx', 'size': '162'}

Please help me understand how to write the right code to delete items with the ".tmp" extension.

Body:
Thank you guys for your help, that gave me a clue on how to do this.
After some research I ended up using comprehension:

dicFiles[:]  = [x for x in dicFiles if x['name'].endswith('.tmp')]

That does the job.


来源: stackexchange

问:
How to get all elements in nested collection with streams
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

```<code>    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }
</code>```

I am looking for a way to fill the pointList with the stream functionality.

答:
If you're concerned about side-effects, this will do it (but both the other answers at the time of writing are infinitely more readable):

```<code>    Entry<Integer, List<StrokePoint>> summary = //
            strokesData.getListOfSessions()
                       .stream()
                       .flatMap(session -> session.getListOfStrokes().stream())
                       .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                       .reduce((l1, l2) -> {
                           int count = l1.getKey() + l2.getKey();

                           List<StrokePoint> list = l1.getValue();
                           list.addAll(l2.getValue());

                           return new SimpleEntry<>(count, list);
                       })
                       .orElse(new SimpleEntry<>(0, Collections.emptyList()));

    strokesCounter = summary.getKey();
    pointList = summary.getValue();
</code>```

EDITING to add validation:

```<code>public class Scratch {
    public static void main(String[] args) {
        int strokesCounter = 0;
        List<StrokePoint> pointList = new ArrayList<>();
        StrokesData strokesData = new StrokesData();

        SessionStrokes sessionStrokes = new SessionStrokes();
        strokesData.sessionStrokes.add(sessionStrokes);

        Strokes s1 = new Strokes();
        sessionStrokes.strokesList.add(s1);

        s1.strokePoints.add(new StrokePoint());
        s1.strokePoints.add(new StrokePoint());

        Strokes s2 = new Strokes();
        sessionStrokes.strokesList.add(s2);

        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());

        Entry<Integer, List<StrokePoint>> summary = //
                strokesData.getListOfSessions()
                           .stream()
                           .flatMap(session -> session.getListOfStrokes()
                                                      .stream())
                           .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                           .reduce((l1, l2) -> {
                               int count = l1.getKey() + l2.getKey();

                               List<StrokePoint> list = l1.getValue();
                               list.addAll(l2.getValue());

                               return new SimpleEntry<>(count, list);
                           })
                           .orElse(new SimpleEntry<>(0, Collections.emptyList()));

        strokesCounter = summary.getKey();
        pointList = summary.getValue();

        System.out.println(strokesCounter);
        System.out.println(pointList);
    }
}

class StrokesData {

    List<SessionStrokes> sessionStrokes = new ArrayList<>();

    public List<SessionStrokes> getListOfSessions() {
        return sessionStrokes;
    }
}

class SessionStrokes {

    List<Strokes> strokesList = new ArrayList<>();

    public List<Strokes> getListOfStrokes() {
        return strokesList;
    }

}

class Strokes {

    List<StrokePoint> strokePoints = new ArrayList<>();

    public List<StrokePoint> getListOfStrokePoints() {
        return strokePoints;
    }
}

class StrokePoint {
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }

I am looking for a way to fill the pointList with the stream functionality.

Body:
If you're concerned about side-effects, this will do it (but both the other answers at the time of writing are infinitely more readable):

    Entry<Integer, List<StrokePoint>> summary = //
            strokesData.getListOfSessions()
                       .stream()
                       .flatMap(session -> session.getListOfStrokes().stream())
                       .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                       .reduce((l1, l2) -> {
                           int count = l1.getKey() + l2.getKey();

                           List<StrokePoint> list = l1.getValue();
                           list.addAll(l2.getValue());

                           return new SimpleEntry<>(count, list);
                       })
                       .orElse(new SimpleEntry<>(0, Collections.emptyList()));

    strokesCounter = summary.getKey();
    pointList = summary.getValue();

EDITING to add validation:

public class Scratch {
    public static void main(String[] args) {
        int strokesCounter = 0;
        List<StrokePoint> pointList = new ArrayList<>();
        StrokesData strokesData = new StrokesData();

        SessionStrokes sessionStrokes = new SessionStrokes();
        strokesData.sessionStrokes.add(sessionStrokes);

        Strokes s1 = new Strokes();
        sessionStrokes.strokesList.add(s1);

        s1.strokePoints.add(new StrokePoint());
        s1.strokePoints.add(new StrokePoint());

        Strokes s2 = new Strokes();
        sessionStrokes.strokesList.add(s2);

        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());
        s2.strokePoints.add(new StrokePoint());

        Entry<Integer, List<StrokePoint>> summary = //
                strokesData.getListOfSessions()
                           .stream()
                           .flatMap(session -> session.getListOfStrokes()
                                                      .stream())
                           .map(strokes -> new SimpleEntry<>(1, strokes.getListOfStrokePoints()))
                           .reduce((l1, l2) -> {
                               int count = l1.getKey() + l2.getKey();

                               List<StrokePoint> list = l1.getValue();
                               list.addAll(l2.getValue());

                               return new SimpleEntry<>(count, list);
                           })
                           .orElse(new SimpleEntry<>(0, Collections.emptyList()));

        strokesCounter = summary.getKey();
        pointList = summary.getValue();

        System.out.println(strokesCounter);
        System.out.println(pointList);
    }
}

class StrokesData {

    List<SessionStrokes> sessionStrokes = new ArrayList<>();

    public List<SessionStrokes> getListOfSessions() {
        return sessionStrokes;
    }
}

class SessionStrokes {

    List<Strokes> strokesList = new ArrayList<>();

    public List<Strokes> getListOfStrokes() {
        return strokesList;
    }

}

class Strokes {

    List<StrokePoint> strokePoints = new ArrayList<>();

    public List<StrokePoint> getListOfStrokePoints() {
        return strokePoints;
    }
}

class StrokePoint {
}


问:
ASP.net adding row in database
I have a asp.net mvc3 web application.
I have a list of items with images queried from db.
From time to time I need to add new item to db and specify image.
I'm thinking to add authentication and create special view only for admins for this purpose.
Is it Ok?

What are the best practices for doing this?
Thanks.

答:
Best practices for this... Well lets see.

Answer some questions -

Q: Is manually adding the record via sql management console good enough along with manually uploading the file?
A: Then no don't fix problems that don't exist

Q: Is this site publicly accessible?
A: Then yes, authentication to post following all security guidelines for keeping script kiddies at bay,

And since your using ms mvc. Make use of the built in security attributes to control access to controller classes methods; for example; [Authorize(Roles = "Administrators")] ect, ect.

Should be fairly simple to set up;

Edit web.config and turn on membership and roles, as well as login page

Could possibly use the .net membership framework to hold users and roles

Lock down controllers or methods with the [Authorize] attribute

Good luck,

ContentLicense: CC BY-SA 3.0

Title: ASP.net adding row in database


问:
BMI Calculator with name, weight, height, BMI and text using Array and for cycle
I would like to ask how do I do that when the cycle starts and go over again, the string variable name will increase by 1. This program is supposed to ask you how many patients are you going to write. If you write for ex. 10, then the cycle will go for 10 times and it will ask all those information I want and then add them to the array which I have already created called BMI. This whole program is supposed to print you a table which contains Name, Height in meters, weight in Kg, your calculated BMI and then text in what state of BMI are you ATM. The problem is how do I do it? I just started learning arrays and stuff like that and my teacher gave me this homework. I don't think that this homework is hard but just hard to understand what to do.

Things I already tried is creating a for cycle with String called name something like this: String name(); but that obviously did not work.

```<code>import java.util.Scanner;
class Pacient {
    public static void main(String args[]){
        int pole;
        Scanner input = new Scanner(System.in);
        String pacient;

        System.out.print("Zadej kolik bude pacientu: "); //How many patients do you want? For ex. 10

        pacient = input.nextLine();
        input.nextLine();
        pole = Integer.parseInt(pacient);

        String[][] bmi = new String[4][pole]; //This is supposed to make an array with my patients.

        double vaha; //weight
        double vyska; //height
        String jmeno; //name
        double telo1, telo2; //body for calc.
        String vysledek; //result
        int i,x=0,j, pa=0, k=0; //some variables

        bmi[0][0] = "Jmeno"; //First line of final table NAME
        bmi[0][1] = "Vaha"; // WEIGHT
        bmi[0][2] = "Vyska"; //HEIGHT
        bmi[0][3] = "BMI"; //BMI based on calc.
        bmi[0][4] = "Text"; //Final result

        for(int y=1;y<pole;y++){
            pa++;
            x++;

            System.out.print("Zadej svoje krestni jmeno: ");
            jmeno = input.nextLine();

            System.out.print("Zadej svoji vahu v Kg: ");
            vaha = input.nextDouble();

            System.out.print("Zadej svoji vysku v m: ");
            vyska = input.nextDouble();

            System.out.println("Vase informace byly uspesne ulozeny! ");

            bmi[1][0] = jmeno; //These values should somehow increase but idk
                                 how atm and be assign with the patient which
                                 will be printed at the end.
            bmi[1][1] = vaha2;
            bmi[1][2] = vyska2;
            bmi[1][3] = telo3;
            bmi[1][4] = vysledek;

        }

        // System.out.println("Tisknu tabulku");

        // telo1 = vyska * vyska; //Some calc. of BMI
        // telo2 = vaha / telo1;

        // if (telo2 < 18.5) { //Adding text to the result variable
        //     vysledek = "mate podvahu";
        // } else if (telo2 < 25) {
        //     vysledek = "Jste v normach";
        // } else if (telo2 < 30) {
        //     vysledek = "Nadvaha";
        // } else {
        //     vysledek = "Obezita";
        // }

        // String telo3 = String.valueOf(telo2); //Converting to strings
        // String vyska2 = String.valueOf(vyska);
        // String vaha2 = String.valueOf(vaha);

        System.out.println("--------------------------------------------------");

        for(i=0;i<pole;i++) {
            for(j = 0; j<5; j++) System.out.print(bmi[i][j] + " ");
                System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}
</code>```

Atm the program is just printing most of the time NULL NULL NULL NULL, and it does not match with the patient number. How do add all this code to for cycle and make it automatic convert int and double to strings and then print them correctly and assign them to the BMI Array. If you have any further questing, feel free to ask.

答:
I have corrected the issues in code. Everything is explained step-by-step in comments. I have converted variable name in English for my understanding. If you have questions. Please ask.</p>

```<code>import java.util.Scanner;

class Pacient {
    private static Scanner input;

    public static void main(String args[]) {
        int numberOfPatients; // Variables that saves number of patient
        // Asking user the number of patients
        input = new Scanner(System.in);
        System.out.print("How many patients do you want?: ");
        // I have change this to nextInt
        // From javadoc "Scans the next token of the input as an int"
        // It is essentially next() + parseInt()
        numberOfPatients = input.nextInt();
        // nextInt() does not move cursor to next line
        // using nextLine() here would move it to next line and close
        // previous line otherwise it creates issue when you will use next/nextLine again
        input.nextLine();

        // String[][] array = new String[Rows][Columns];
        // For each patient there is a row. Since in the code there is header
        // as well that's why we need numberOfPatients + 1
        String[][] bmi = new String[numberOfPatients + 1][5];

        // All corresponding columns
        bmi[0][0] = "Name"; // First line of final table NAME
        bmi[0][1] = "Weight"; // WEIGHT
        bmi[0][2] = "Height"; // HEIGHT
        bmi[0][3] = "BMI"; // BMI based on calc.
        bmi[0][4] = "Result"; // Final result

        // Starting from 1. Skipping header
        for (int y = 1; y <= numberOfPatients; y++) {
            // Using y instead of an int. This way the loop will
            // automatically move to next row

            // Instead of saving it to variable and then to array
            // I am saving it directly
            System.out.print("Enter your first name: ");
            bmi[y][0] = input.nextLine();

            System.out.print("Enter your weight in Kg: ");
            bmi[y][1] = input.nextLine();

            System.out.print("Enter your height in m: ");
            bmi[y][2] = input.nextLine();

            // Using the information from above to calculate BMI
            // Basically I am storing and calculating at the same time
            // parseDouble converts String into double
            // Math.pow(a,b) is powber function. a is base and b is exponent
            double weight = Double.parseDouble(bmi[y][1]);
            double heightSquare = Math.pow(Double.parseDouble(bmi[y][2]), 2);
            double bmiCalculated = weight / heightSquare;

            // Based on BMI assigning result in result column
            bmi[y][3] = bmiCalculated + "";
            if (bmiCalculated < 18.5) {
                bmi[y][4] = "You are underweight";
            } else if (bmiCalculated > 18.5 && bmiCalculated < 25) {
                bmi[y][4] = "You are normal";
            } else if (bmiCalculated > 25 && bmiCalculated < 30) {
                bmi[y][4] = "You are overweight";
            } else {
                bmi[y][4] = "You are obese";
            }
            System.out.println("Your information has been saved successfully!");
        }

        System.out.println("--------------------------------------------------");

        // In java 2D arrays are multiple 1D array stacked on each other
        // bmi.length gives the number of rows
        // Basically you iterate through each row and print each individual row
        // like 1D array
        for (int i = 0; i < bmi.length; i++) {
        // bmi[i] gives ith row. Which is 1D array. So you can print it like normal array
            for (int j = 0; j < bmi[i].length; j++)
                System.out.print(bmi[i][j] + " ");
            System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}
</code>```

Body:
I would like to ask how do I do that when the cycle starts and go over again, the string variable name will increase by 1. This program is supposed to ask you how many patients are you going to write. If you write for ex. 10, then the cycle will go for 10 times and it will ask all those information I want and then add them to the array which I have already created called BMI. This whole program is supposed to print you a table which contains Name, Height in meters, weight in Kg, your calculated BMI and then text in what state of BMI are you ATM. The problem is how do I do it? I just started learning arrays and stuff like that and my teacher gave me this homework. I don't think that this homework is hard but just hard to understand what to do.

Things I already tried is creating a for cycle with String called name something like this: String name(); but that obviously did not work.

import java.util.Scanner;
class Pacient {
    public static void main(String args[]){
        int pole;
        Scanner input = new Scanner(System.in);
        String pacient;

        System.out.print("Zadej kolik bude pacientu: "); //How many patients do you want? For ex. 10

        pacient = input.nextLine();
        input.nextLine();
        pole = Integer.parseInt(pacient);

        String[][] bmi = new String[4][pole]; //This is supposed to make an array with my patients.

        double vaha; //weight
        double vyska; //height
        String jmeno; //name
        double telo1, telo2; //body for calc.
        String vysledek; //result
        int i,x=0,j, pa=0, k=0; //some variables

        bmi[0][0] = "Jmeno"; //First line of final table NAME
        bmi[0][1] = "Vaha"; // WEIGHT
        bmi[0][2] = "Vyska"; //HEIGHT
        bmi[0][3] = "BMI"; //BMI based on calc.
        bmi[0][4] = "Text"; //Final result

        for(int y=1;y<pole;y++){
            pa++;
            x++;

            System.out.print("Zadej svoje krestni jmeno: ");
            jmeno = input.nextLine();

            System.out.print("Zadej svoji vahu v Kg: ");
            vaha = input.nextDouble();

            System.out.print("Zadej svoji vysku v m: ");
            vyska = input.nextDouble();

            System.out.println("Vase informace byly uspesne ulozeny! ");

            bmi[1][0] = jmeno; //These values should somehow increase but idk
                                 how atm and be assign with the patient which
                                 will be printed at the end.
            bmi[1][1] = vaha2;
            bmi[1][2] = vyska2;
            bmi[1][3] = telo3;
            bmi[1][4] = vysledek;

        }

        // System.out.println("Tisknu tabulku");

        // telo1 = vyska * vyska; //Some calc. of BMI
        // telo2 = vaha / telo1;

        // if (telo2 < 18.5) { //Adding text to the result variable
        //     vysledek = "mate podvahu";
        // } else if (telo2 < 25) {
        //     vysledek = "Jste v normach";
        // } else if (telo2 < 30) {
        //     vysledek = "Nadvaha";
        // } else {
        //     vysledek = "Obezita";
        // }

        // String telo3 = String.valueOf(telo2); //Converting to strings
        // String vyska2 = String.valueOf(vyska);
        // String vaha2 = String.valueOf(vaha);

        System.out.println("--------------------------------------------------");

        for(i=0;i<pole;i++) {
            for(j = 0; j<5; j++) System.out.print(bmi[i][j] + " ");
                System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}

Atm the program is just printing most of the time NULL NULL NULL NULL, and it does not match with the patient number. How do add all this code to for cycle and make it automatic convert int and double to strings and then print them correctly and assign them to the BMI Array. If you have any further questing, feel free to ask.

Body:
I have corrected the issues in code. Everything is explained step-by-step in comments. I have converted variable name in English for my understanding. If you have questions. Please ask.

import java.util.Scanner;

class Pacient {
    private static Scanner input;

    public static void main(String args[]) {
        int numberOfPatients; // Variables that saves number of patient
        // Asking user the number of patients
        input = new Scanner(System.in);
        System.out.print("How many patients do you want?: ");
        // I have change this to nextInt
        // From javadoc "Scans the next token of the input as an int"
        // It is essentially next() + parseInt()
        numberOfPatients = input.nextInt();
        // nextInt() does not move cursor to next line
        // using nextLine() here would move it to next line and close
        // previous line otherwise it creates issue when you will use next/nextLine again
        input.nextLine();

        // String[][] array = new String[Rows][Columns];
        // For each patient there is a row. Since in the code there is header
        // as well that's why we need numberOfPatients + 1
        String[][] bmi = new String[numberOfPatients + 1][5];

        // All corresponding columns
        bmi[0][0] = "Name"; // First line of final table NAME
        bmi[0][1] = "Weight"; // WEIGHT
        bmi[0][2] = "Height"; // HEIGHT
        bmi[0][3] = "BMI"; // BMI based on calc.
        bmi[0][4] = "Result"; // Final result

        // Starting from 1. Skipping header
        for (int y = 1; y <= numberOfPatients; y++) {
            // Using y instead of an int. This way the loop will
            // automatically move to next row

            // Instead of saving it to variable and then to array
            // I am saving it directly
            System.out.print("Enter your first name: ");
            bmi[y][0] = input.nextLine();

            System.out.print("Enter your weight in Kg: ");
            bmi[y][1] = input.nextLine();

            System.out.print("Enter your height in m: ");
            bmi[y][2] = input.nextLine();

            // Using the information from above to calculate BMI
            // Basically I am storing and calculating at the same time
            // parseDouble converts String into double
            // Math.pow(a,b) is powber function. a is base and b is exponent
            double weight = Double.parseDouble(bmi[y][1]);
            double heightSquare = Math.pow(Double.parseDouble(bmi[y][2]), 2);
            double bmiCalculated = weight / heightSquare;

            // Based on BMI assigning result in result column
            bmi[y][3] = bmiCalculated + "";
            if (bmiCalculated < 18.5) {
                bmi[y][4] = "You are underweight";
            } else if (bmiCalculated > 18.5 && bmiCalculated < 25) {
                bmi[y][4] = "You are normal";
            } else if (bmiCalculated > 25 && bmiCalculated < 30) {
                bmi[y][4] = "You are overweight";
            } else {
                bmi[y][4] = "You are obese";
            }
            System.out.println("Your information has been saved successfully!");
        }

        System.out.println("--------------------------------------------------");

        // In java 2D arrays are multiple 1D array stacked on each other
        // bmi.length gives the number of rows
        // Basically you iterate through each row and print each individual row
        // like 1D array
        for (int i = 0; i < bmi.length; i++) {
        // bmi[i] gives ith row. Which is 1D array. So you can print it like normal array
            for (int j = 0; j < bmi[i].length; j++)
                System.out.print(bmi[i][j] + " ");
            System.out.println();
        }
        System.out.println("--------------------------------------------------");
    }
}


问:
select column of a dataframe using udf
I use spark-shell and want to create a dataframe (df2) from another dataframe (df1) using select and udf. But there is an error when I want to show the df2 ==> df2.show(1)

```<code>  var df1 = sql(s"select * from table_1")
  val slice = udf ((items: Array[String]) => if (items == null) items
  else {
     if (items.size <= 20)
       items
     else
       items.slice(0, 20)
  })
  var df2 = df1.select($"col1", slice($"col2"))

</code>```

and the df1 schema is:

```<code>scala> df1.printSchema
root
  |-- col1: string (nullable = true)
  |-- col2: array (nullable = true)
  |    |-- element: string (containsNull = true)

 scala> df2.printSchema
 root
   |-- col1: string (nullable = true)
   |-- UDF(col2): array (nullable = true)
   |    |-- element: string (containsNull = true)
</code>```

error:

```<code> Failed to execute user defined function($anonfun$1: (array<string>) => array<string>)
</code>```

答: Used Seq[String] instead of Array[String] in the udf and the issue is resolved.</p>

Title: select column of a dataframe using udf

Body:
I use spark-shell and want to create a dataframe (df2) from another dataframe (df1) using select and udf. But there is an error when I want to show the df2 ==> df2.show(1)

  var df1 = sql(s"select * from table_1")
  val slice = udf ((items: Array[String]) => if (items == null) items
  else {
     if (items.size <= 20)
       items
     else
       items.slice(0, 20)
  })
  var df2 = df1.select($"col1", slice($"col2"))

and the df1 schema is:

scala> df1.printSchema
root
  |-- col1: string (nullable = true)
  |-- col2: array (nullable = true)
  |    |-- element: string (containsNull = true)

 scala> df2.printSchema
 root
   |-- col1: string (nullable = true)
   |-- UDF(col2): array (nullable = true)
   |    |-- element: string (containsNull = true)

error:

 Failed to execute user defined function($anonfun$1: (array<string>) => array<string>)


问:
Correct gradients for word2vec negative sampling skip gram model
I am trying to implement skip-gram word2vec in python using negative sampling.
From my understanding, I should be maximizing the equation (4) from the paper by Mikolov Et al.

I have taken the gradients of this equation with respect to Vc, U, and U_rand. Where Vc is the center vector corresponding to the center word, U is the context vector corresponding to a word in the context of the center word and U_rand is the context vector of a randomly sampled word.

I am then calculating the cost function for each combination of word and context word adding them up and printing out the total sum of the whole corpus. I am running this a few times and I do not see an improvement on the whole corpus sum of costs. The cost goes up and then down repeatedly.

I got the following gradients

grad J with respect to Vc = (1-sigma(V•U))*U - Summation over random
  vectors (1-sigma(-V•U_rand))*U_rand

grad J with respect to U = (1-sigma(V•U))*V

grad J with respect to U_rand = (1-sigma(-V•U_rand))*-V

So with that being said, I have a few questions:

Are these gradients correct?

Should I be taking a step in the direction of the gradient? (as opposed to the negative of the gradient) To me, I should be as we are maximizing the cost function

for the randomly sampled word are we using its center word representation or context work representation. From the Stanford lecture I watched on youtube it seems to be its context vector. But this source seems to differ.

Is adding all the cost function results for the whole corpus a valid way to see improvement? (I do not see why not)

答:
I didn't understand your question 2-4. It seems that you don't know what you don't know.

First of all, Skip-Gram (both SG and SGNS) has the following cost function (derivation of cost function):

The above equation is for Batch Gradient Descent - one update is made after scanning through the entire corpus of size T. This is inefficient because T is very large in NLP applications. Therefore, we use Stochastic Gradient Descent (SGD) to update weights for each training sample:

SGNS uses sigmoid function to compute binary probability distribution. Equation (4) of mikolove's paper replaces the above cost function: :

w is the input word, and h is the hidden layer. h is equivalent to the word vector for w, because the input layer is one-hot encoded. c_pos is the word vector for positive word, and c_neg is the word vector for randomly drawn negative word from the noise distribution. W_neg denotes for all K word vectors for negative words.

A general update equation for any machine learning model is:

Taking the derivative to the SGNS cost function with respect to theta:

From this point, we need to calculate gradient with respect to the input weight matrix and output weight matrix:

Gradient for Input weight matrix

In both SG and SGNS, only one word vector in the input weight matrix that corresponds to the input word is updated. Since the word vector for the input word is equivalent to the hidden layer, we take the derivative of the cost function J with respect to h:

The update equation is then:

Gradient for output weight matrix

Both c_pos and c_neg are word vectors from the output weight matrix, We take gradient with respect to both of them, separately:

Here, σ(c_j⋅h)−t_j is called the prediction error. As the model optimizes the weights, this prediction error will be minimized.

Do I maximize or minimize?

The convention in machine learning is to minimize the cost function J. But many paper say that they maximize the probability of ... bla bla bla. Why is that?

The initial idea of negative sampling is to maximize the probability of observing positive pairs and minimizing the probability of observing negative pairs. Mathematically, it can be translated as:

argmax theta means that we maximize the following probability by adjusting theta. In machine learning, it is a common practice to take a natural log to the objective equation to simplify derivations (why take a natural log? read here). Then:

The authors say that they maximize probability. However, in machine learning, the convention is to minimize the cost function, not to maximize it. To stick to the convention, we add a negative sign to eq (11). This can be done because minimizing a negative log-likelihood is equivalent to maximizing a positive log-likelihood. After some mathematical manipulation (derivation), we then obtain the cost function we can minimize:


问:
SVG - How move img background but mask stay sticky
I'm trying to modify this demo

https://tympanus.net/codrops-playground/SaraSoueidan/UHhPmBzJ/editor

I would like to change the position of the image and move it inside the mask but without moving the mask.

"Mask-position" does not respond to what I'm trying to do.

Is there a solution ?

thank you in advance

答:
You can create a div containing the image you want to move. To move the image just change the bottom and right attributes.

https://next.plnkr.co/edit/LWctq6h3RBOk3Vos?open=lib%2Fscript.js


问:
How to create a switching function in Python?
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

```<code>def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)
</code>```

it outputs:

```<code>value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
</code>```

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

答:
Is this what you are looking for:

```<code>class switcher:
    def __init__(self):
        self.cnt = -1

    def switch(self):
        self.cnt += 1
        return '0' if self.cnt % 2 else '1'

mySwitch = switcher().switch

print(mySwitch())
print(mySwitch())
print(mySwitch())
print(mySwitch())
</code>```

This will print:

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

There are other methods to achieve this, like using decorators.

Body:
I'm having difficulty creating a program that switches between string "X" and "O" every time the function is ran.

So for example, the first time switcher() is ran, it prints "x," and the next time it runs, it prints "o," and third it prints "x," and so forth

I've been able to achieve this without a function and just using an if else loop, but I can't do it using a function

def switch(value):
    if value == 0:
        x = value
        x + 1
        print("value: " + str(x) + " | turn: x")
        return x
    else:
        print("o")
        return 0

x = 0
for i in range(4):
    switch(x)

it outputs:

value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x
value: 0 | turn: x

In order to achieve this, I make it so that when x = 0, it prints "X" and when it's 1 it prints "O," and then resets back to 0. It stays as 0 and only gives me x.

Body:
Is this what you are looking for:

class switcher:
    def __init__(self):
        self.cnt = -1

    def switch(self):
        self.cnt += 1
        return '0' if self.cnt % 2 else '1'

mySwitch = switcher().switch

print(mySwitch())
print(mySwitch())
print(mySwitch())
print(mySwitch())

This will print:

1
0
1
0

There are other methods to achieve this, like using decorators.


答:
Using cycle from itertools

I think a good approach is to use the function cycle in itertools

```<code>from itertools import cycle

def switch():
    return cycle(["X", "O"])

i = 0
for output in switch():
    i += 1
    print(output)
    if i == 5:
        break
</code>```

Output:

```<code>X
O
X
O
X
</code>```

Using a global variable

You can also use a global variable to keep track of the last generated value. However, it is not a good idea to use a global variable.

```<code>last_value = None

def switch():
    global last_value
    if last_value in (None, "O"):
        last_value = "X"
        return "X"
    last_value = "O"
    return "O"

for _ in range(5):
    print(switch())
</code>```

Output:

```<code>'X'
'O'
'X'
'O'
'X'
</code>```

Using a local variable

You can also pass a parameter that indicates the last value that was returned.

```<code>def switch(last_value):
    if last_value in (None, "O"):
        return "X"
    return "O"

last_value = None
for _ in range(5):
    last_value = switch(last_value)
    print(last_value)
</code>```

Output:

```<code>X
O
X
O
x
</code>```

Title: How to create a switching function in Python?

Body:
Using cycle from itertools

I think a good approach is to use the function cycle in itertools

from itertools import cycle

def switch():
    return cycle(["X", "O"])

i = 0
for output in switch():
    i += 1
    print(output)
    if i == 5:
        break

Output:

X
O
X
O
X

Using a global variable

You can also use a global variable to keep track of the last generated value. However, it is not a good idea to use a global variable.

last_value = None

def switch():
    global last_value
    if last_value in (None, "O"):
        last_value = "X"
        return "X"
    last_value = "O"
    return "O"

for _ in range(5):
    print(switch())

Output:

'X'
'O'
'X'
'O'
'X'

Using a local variable

You can also pass a parameter that indicates the last value that was returned.

def switch(last_value):
    if last_value in (None, "O"):
        return "X"
    return "O"

last_value = None
for _ in range(5):
    last_value = switch(last_value)
    print(last_value)

Output:

X
O
X
O
x


问:
Particles do not appear on the particles div
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <div id="particles-js"></div>
    <script type="text/javascript" src="./particles.js-master/demo/js/app.js"></script>
    <script type="text/javascript" src="./particles.js-master/particles.js"></script>
</body>
</html>
</code>```

style.css

```<code>body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</code>```

I know that particles-js is present because changing its background color makes an affect on the page.

答: Thanks so much for your detailed responses. But in case anyone ever sees this problem again, the problem was that my adblocker was not allowing the particles javascript.</p>

Body:
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>

style.css

body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

I know that particles-js is present because changing its background color makes an affect on the page.


问:
How do I use window.location.href in codesandbox.io?
I'd like to use window.location.href in the tool codesandbox.io.  This is because I want to do a test with a hard page load occurring.  I'm running into an issue however.

```<code>location.href = "http://www.google.com"
</code>```

I get this error:

```<code>Mixed Content: The page at 'https://codesandbox.io/s/lingering-bird-nyvfi' was loaded over HTTPS, but requested an insecure resource 'http://www.google.com/'. This request has been blocked; the content must be served over HTTPS.
</code>```

Example: https://codesandbox.io/s/locationhref-usage-nyvfi (see src/index.ts and open Dev Console)

How do I accomplish this the ability to simulate a page load, in the fake virtual browser?

答:
I think it may be possible once the security criteria are met; which is limiting.

Use HTTPS (Avoid mixed content)

Use same origin

Thus this works:

```<code>window.location.href = "https://www.codesandbox.io/docs";
</code>```

Body:
I'd like to use window.location.href in the tool codesandbox.io.  This is because I want to do a test with a hard page load occurring.  I'm running into an issue however.

location.href = "http://www.google.com"

I get this error:

Mixed Content: The page at 'https://codesandbox.io/s/lingering-bird-nyvfi' was loaded over HTTPS, but requested an insecure resource 'http://www.google.com/'. This request has been blocked; the content must be served over HTTPS.

Example: https://codesandbox.io/s/locationhref-usage-nyvfi (see src/index.ts and open Dev Console)

How do I accomplish this the ability to simulate a page load, in the fake virtual browser?

Body:
I think it may be possible once the security criteria are met; which is limiting.

Use HTTPS (Avoid mixed content)

Use same origin

Thus this works:

window.location.href = "https://www.codesandbox.io/docs";


问:
Is there any way in SQL or function in MYSQL that sums up all the increments in a column?
I want to find a way to sum up all the increments in the value of a column.

We provide delivery services to our customers. A customer can pay as he go, but if he pays an upfront fee, he gets a better deal. There is a table that has the balance of the customer across the time. So I want to sum all the increments to the balance. I can't change the way the payment is recorded.

I have alredy coded an stored procedure that works, but is kind slow, so I'm looking for alternatives. I think that, maybe, an sql statement that can do this task, can outperform my stored procedure that has loops.

My stored procedure makes a select of the customer in a given date range, and insert the result in a temp table X. After that, it starts to pop rows from X table, comparing the balance value in that row against the previous row, and detects if there is an increment. If there is not increment, pops another row and do the same routine, if there is an increment, it calculates the difference between that row and the previous, and the result is inserted in another temp table Y.

When there are no rows left, the stored procedure performs a SUM in the temp table Y, and thus, you can know how much the customer has "refilled" its balance.

This is an example of the table X, and the expected result:

```<code>DATE        BALANCE
----        -------
2019-02-01  200
2019-02-02  195    //from 200 to 195 there is a decrement, so it doesn't matter
2019-02-03  180
2019-02-04  150
2019-02-05  175    //there is an increment from 150 to 175, it's 25 that must be inserted in the temp table
2019-02-06  140
2019-02-07  180    //there is another increment, from 140 to 180, it's 40
</code>```

So the resulting temp table Y must be something like this:

```<code>REFILL
------
25
40
</code>```

The expected result is 65. My stored procedure returns this value, but as I said, is kind slow (it takes about 22 seconds to process 3900 rows, equivalent to 3 days, aprox), I think is because the loops. I would like to explore another alternatives. Because some details that I don't mention here, for a single costumer, I can have 1300 rows per day (the example is given in days, but I have rows by the minute). My tables are indexed, I think properly. I can't post my stored procedure, but it works as described (I know that "The devil is in the detail"). So any suggestion will be appreciated.

答:
Use a user-defined variable to hold the balance from the previous row, and then subtract it from the current row's balance.</p>

```<code>SELECT SUM(refill) AS total_refill
FROM (
  SELECT GREATEST(0, balance - @prev_balance) AS refill, @prev_balance := balance
  FROM (
    SELECT balance
    FROM tableX
    ORDER BY date) AS t
  CROSS JOIN (SELECT @prev_balance := NULL) AS ars
) AS t
</code>```

Body:
I want to find a way to sum up all the increments in the value of a column.

We provide delivery services to our customers. A customer can pay as he go, but if he pays an upfront fee, he gets a better deal. There is a table that has the balance of the customer across the time. So I want to sum all the increments to the balance. I can't change the way the payment is recorded.

I have alredy coded an stored procedure that works, but is kind slow, so I'm looking for alternatives. I think that, maybe, an sql statement that can do this task, can outperform my stored procedure that has loops.

My stored procedure makes a select of the customer in a given date range, and insert the result in a temp table X. After that, it starts to pop rows from X table, comparing the balance value in that row against the previous row, and detects if there is an increment. If there is not increment, pops another row and do the same routine, if there is an increment, it calculates the difference between that row and the previous, and the result is inserted in another temp table Y.

When there are no rows left, the stored procedure performs a SUM in the temp table Y, and thus, you can know how much the customer has "refilled" its balance.

This is an example of the table X, and the expected result:

DATE        BALANCE
----        -------
2019-02-01  200
2019-02-02  195    //from 200 to 195 there is a decrement, so it doesn't matter
2019-02-03  180
2019-02-04  150
2019-02-05  175    //there is an increment from 150 to 175, it's 25 that must be inserted in the temp table
2019-02-06  140
2019-02-07  180    //there is another increment, from 140 to 180, it's 40

So the resulting temp table Y must be something like this:

REFILL
------
25
40

The expected result is 65. My stored procedure returns this value, but as I said, is kind slow (it takes about 22 seconds to process 3900 rows, equivalent to 3 days, aprox), I think is because the loops. I would like to explore another alternatives. Because some details that I don't mention here, for a single costumer, I can have 1300 rows per day (the example is given in days, but I have rows by the minute). My tables are indexed, I think properly. I can't post my stored procedure, but it works as described (I know that "The devil is in the detail"). So any suggestion will be appreciated.

Body:
Use a user-defined variable to hold the balance from the previous row, and then subtract it from the current row's balance.

SELECT SUM(refill) AS total_refill
FROM (
  SELECT GREATEST(0, balance - @prev_balance) AS refill, @prev_balance := balance
  FROM (
    SELECT balance
    FROM tableX
    ORDER BY date) AS t
  CROSS JOIN (SELECT @prev_balance := NULL) AS ars
) AS t


问:
Get list of all loaded python packages & versions, and variables
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

```<code>library(dplyr)
x=3;
y=4;
</code>```

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

```<code>ls()
</code>```

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.

答:
You can get the currently loaded modules with sys.modules. This means you can use the following code to print the currently loaded modules and their versions:

```<code>import sys

for module in sys.modules.values():
    if hasattr(module, "__version__"):
        print(module.__name__, module.__version__)
    else:
        print(module.__name__)
</code>```

Modules aren't obliged to provide a __version__ attribute, so you have to check whether it exists before you use it. Most modules in the standard library don't provide a version, although interestingly, some provide versions that are different from the current version of Python.

A caveat is that you can use importlib to load modules without adding them to sys.modules, so there is no guarantee that sys.modules will be accurate 100% of the time.

Body:
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

library(dplyr)
x=3;
y=4;

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

ls()

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.

Body:
You can get the currently loaded modules with sys.modules. This means you can use the following code to print the currently loaded modules and their versions:

import sys

for module in sys.modules.values():
    if hasattr(module, "__version__"):
        print(module.__name__, module.__version__)
    else:
        print(module.__name__)

Modules aren't obliged to provide a __version__ attribute, so you have to check whether it exists before you use it. Most modules in the standard library don't provide a version, although interestingly, some provide versions that are different from the current version of Python.

A caveat is that you can use importlib to load modules without adding them to sys.modules, so there is no guarantee that sys.modules will be accurate 100% of the time.


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
No, unfortunately C# is not PHP.

On the bright side though, C# is not PHP.

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.


问:
Conditional rendering within loops in React JS
I have data coming from an external API that I am trying to display in a table. The data comes back with date time stamps.

I'd like to render the data in a table, but with an extra row in that displays the date when the date changes.

What I've tried

I've attempted updating a lastDate prop value.

I've attempted conditional rendering with the (condition) ? expected : other syntax and a variable in the render() method.

I can't figure out how to keep track of the current date variable and update it on every loop iteration.

I've tried splitting the DateRow and the DataRow into seperate components and passing the date, but the state is not persisted.

I'm not sure what is best practice for doing this. Or if it's just a bad idea.

```<code>
import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';

import * as helpers from '../../common/helpers';

export default class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch(`https://api.example.com`)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            data: result
          });
        }
      )
  }

  render() {
    const { data } = this.state;
    return (
      <>
        <h4>Most Recent</h4>
        <Table>
          <thead>
            <tr>
              <th>Time</th>
              <th>Column 1</th>
              <th>Column 2</th>
            </tr>
          </thead>
          <tbody>
            {data.map(newRow => (

              // Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
              // ie. if previousDate != currentDate
              // <tr>
              //   <td>{helpers.getFormattedDate(newRow.time)}</td>
              //   <td></td>
              //   <td></td>
              // </tr>
              // Then render the following :

              <tr key={newRow.id}>

                <td>
                  {helpers.getFormattedTime(newRow.time)}
                </td>

                <td>
                  <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
                </td>

                <td>
                  {/* Some more content here */}
                </td>

              </tr>
            ))}
          </tbody>
        </Table>

      </>
    );
  }
}

</code>```

Any help here would be appreciated, I'm more than a bit lost on this one.

Thanks!

答:
You can do conditional rendering in React by combining two features:

JavaScript stops evaluating expressions with boolean operators like && and || as soon as the value of the expression can be determined. For example, in func1() && func2(), the function func2 is never called if func1 returns a falsey (null, undefined, false, 0) value. Similarly, in func1() || func2(), func2 is never called if func1 returns a truthy value.

React does not render falsey (except 0) values.

So a common way to do conditional rendering in React is to do something like:

    { isTrue && (
        <MyConditionalComponent/>
    )}

```

<p>Where <code>MyConditionalComponent</code> will only be rendered if <code>isTrue</code> is truthy.</p>

<p>In your case, since you're using a <code>map</code>, you'll probably also want to use the <code>Fragment</code> component which basically allows you to return more than a single component for an element of the <code>map</code>. Alternatively you could use a <code>reduce</code>, but for simplicity I'll just show an example with the <code>map</code>:</p>

<pre class="lang-js prettyprint-override"><code><tbody>
  {data.map((newRow, i) => (

    <React.Fragment>
      (i !== 0 && (getDate(newRow.time) !== getDate(data[i - 1].time))) && (
        <tr>
          <td>{helpers.getFormattedDate(newRow.time)}</td>
          <td></td>
          <td></td>
        </tr>
      )

      <tr key={newRow.id}>

        <td>
          {helpers.getFormattedTime(newRow.time)}
        </td>

        <td>
          <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
        </td>

        <td>
          {/* Some more content here */}
        </td>

      </tr>
    </React.Fragment>
  ))}
</tbody>
</code>```

Where getDate would be some function that returns just the date part from a Date object.

Note we also make use of the second argument (i) of the map callback, which is the index of the current element to check  on the date of the previous element.

Body:
I have data coming from an external API that I am trying to display in a table. The data comes back with date time stamps.

I'd like to render the data in a table, but with an extra row in that displays the date when the date changes.

What I've tried

I've attempted updating a lastDate prop value.

I've attempted conditional rendering with the (condition) ? expected : other syntax and a variable in the render() method.

I can't figure out how to keep track of the current date variable and update it on every loop iteration.

I've tried splitting the DateRow and the DataRow into seperate components and passing the date, but the state is not persisted.

I'm not sure what is best practice for doing this. Or if it's just a bad idea.

import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';

import * as helpers from '../../common/helpers';

export default class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch(`https://api.example.com`)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            data: result
          });
        }
      )
  }

  render() {
    const { data } = this.state;
    return (
      <>

Most Recent

              Time
              Column 1
              Column 2

            {data.map(newRow => (

              // Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
              // ie. if previousDate != currentDate
              //

              //   {helpers.getFormattedDate(newRow.time)}
              //
              //
              //

              // Then render the following :

                  {helpers.getFormattedTime(newRow.time)}

                  <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>

                  {/* Some more content here */}

            ))}

      </>
    );
  }
}

Any help here would be appreciated, I'm more than a bit lost on this one.

Thanks!

Body:
You can do conditional rendering in React by combining two features:

JavaScript stops evaluating expressions with boolean operators like && and || as soon as the value of the expression can be determined. For example, in func1() && func2(), the function func2 is never called if func1 returns a falsey (null, undefined, false, 0) value. Similarly, in func1() || func2(), func2 is never called if func1 returns a truthy value.

React does not render falsey (except 0) values.

So a common way to do conditional rendering in React is to do something like:

<div>
    { isTrue && (
        <MyConditionalComponent/>
    )}
</div>

Where MyConditionalComponent will only be rendered if isTrue is truthy.

In your case, since you're using a map, you'll probably also want to use the Fragment component which basically allows you to return more than a single component for an element of the map. Alternatively you could use a reduce, but for simplicity I'll just show an example with the map:

<tbody>
  {data.map((newRow, i) => (

    <React.Fragment>
      (i !== 0 && (getDate(newRow.time) !== getDate(data[i - 1].time))) && (
        <tr>
          <td>{helpers.getFormattedDate(newRow.time)}</td>
          <td></td>
          <td></td>
        </tr>
      )

      <tr key={newRow.id}>

        <td>
          {helpers.getFormattedTime(newRow.time)}
        </td>

        <td>
          <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
        </td>

        <td>
          {/* Some more content here */}
        </td>

      </tr>
    </React.Fragment>
  ))}
</tbody>

Where getDate would be some function that returns just the date part from a Date object.

Note we also make use of the second argument (i) of the map callback, which is the index of the current element to check  on the date of the previous element.


问:
Aws Lambda display progress
I want to have a lambda function to run batch payment jobs.

When the user send the batch job. I want the user to see the progress of batch payment. So I want the Lambda function to send the messages back to the client. The user needs to see what payment was successful too.

I expect the lambda function will take around 3-5 minutes to run.

What should I use to for Lambda to communicate with the client side code? Sockets? The client side is written in Vuejs.

Thanks

答:
An AWS Lambda function cannot 'return' information while it is running.

It can, however, periodically 'send' information if you write the code to do so.

So, it really depends on how your client is capable of receiving a 'message', such as providing a REST endpoint that the Lambda function can call.

Alternatively, the Lambda function could store status information 'somewhere' and the client could poll that location for status.

For example:

When the client invokes the Lambda function (or calls something that invokes the function), it can pass a randomized unique string

The Lambda function could periodically update an Amazon S3 object, stored in a particular bucket with that randomized string as the Key

The client can periodically poll the S3 object, using the same Key, to retrieve status information

Title: Aws Lambda display progress


问:
ActiveRecord: doing a join with unscoped doesn't skip the default_scope
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end
```

<p>I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching <code>Client</code>s.</p>

<pre class="lang-rb prettyprint-override"><code>Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
</code>```

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

<p>Again, I got the same result, even when using <code>unscoped</code> with the block.</p>

<p>Then I decided to add a new association to the model, with the <code>unscoped</code> scope:</p>

<pre class="lang-rb prettyprint-override"><code>class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end
</code>```

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

答:
You can do it manually:</p>

```<code>Client.joins('inner join company on companies.id = clients.company_id')
</code>```

Body:
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end

I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching Clients.

Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

Again, I got the same result, even when using unscoped with the block.

Then I decided to add a new association to the model, with the unscoped scope:

class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

Body:
You can do it manually:

Client.joins('inner join company on companies.id = clients.company_id')


答:
There is a quite well-known mechanism to deal with these: Use a variable inside a field.</p>

```<code>SELECT @result:=0;
SELECT @lastbalance:=9999999999; -- whatever value is sure to be highe than any real balance
SELECT SUM(increments) AS total FROM (
  SELECT
    IF(balance>@lastbalance, balance-@lastbalance, 0) AS increments,
    @lastbalance:=balance AS ignore
  FROM X -- insert real table name here
  WHERE
    -- insert selector here
  ORDER BY
    -- insert real chronological sorter here
) AS baseview;
</code>```

Title: Is there any way in SQL or function in MYSQL that sums up all the increments in a column?

Body:
There is a quite well-known mechanism to deal with these: Use a variable inside a field.

SELECT @result:=0;
SELECT @lastbalance:=9999999999; -- whatever value is sure to be highe than any real balance
SELECT SUM(increments) AS total FROM (
  SELECT
    IF(balance>@lastbalance, balance-@lastbalance, 0) AS increments,
    @lastbalance:=balance AS ignore
  FROM X -- insert real table name here
  WHERE
    -- insert selector here
  ORDER BY
    -- insert real chronological sorter here
) AS baseview;


问:
Error when passing setState in a React class component to an external function?
Assume data has already been cached in sessionStorage. I have hydrateStateWithSessionStorage in an external CacheService.js file. I import this file. When I try to pass this.setState to this function, I get this error:

Uncaught TypeError: Cannot read property 'updater' of undefined

How can I solve this? I could possibly use a the React hook useState and pass the setter function, but what if I want to use a class component instead of functional component? Or am I simply unable to pass setState because it implicitly uses the 'this' keyword in its implementation?

```<code>   hydrateStateWithSessionStorage(state, setState) {
    // for all items in state
    for (let key in state) {

        // if the key exists in localStorage
        if (sessionStorage.hasOwnProperty(key)) {
            // get the key's value from localStorage
            let value = sessionStorage.getItem(key);
            // console.log(value)
            // parse the localStorage string and setState
            try {
                value = JSON.parse(value);
                console.log('before')
                setState({ [key]: value });
                console.log('after')
            } catch (e) {
                // handle empty string
                setState({ [key]: value });
            }
        }
    }
}

//in the component consuming CacheService
//this.Cache = new CacheService(); //in the constructor

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this.state, this.setState);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}
</code>```

答:
How about this?

```<code>componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}
</code>```

And then using setState like so...

```<code>hydrateStateWithSessionStorage(ReactComp) {
    for (let key in ReactComp.state) {
        ...
        ReactComp.setState({ [key]: value });
        ....
    }
}
</code>```

FYI, this is not a React specific issue. The reason you are getting that error is, you are passing just a method that internally uses "this" (of that particular class) to the hydrateStateWithSessionStorage function. By the time, that method is called in the function, the scope has changed and "this" is not defined or not the same anymore.

Body:
Assume data has already been cached in sessionStorage. I have hydrateStateWithSessionStorage in an external CacheService.js file. I import this file. When I try to pass this.setState to this function, I get this error:

Uncaught TypeError: Cannot read property 'updater' of undefined

How can I solve this? I could possibly use a the React hook useState and pass the setter function, but what if I want to use a class component instead of functional component? Or am I simply unable to pass setState because it implicitly uses the 'this' keyword in its implementation?

   hydrateStateWithSessionStorage(state, setState) {
    // for all items in state
    for (let key in state) {

        // if the key exists in localStorage
        if (sessionStorage.hasOwnProperty(key)) {
            // get the key's value from localStorage
            let value = sessionStorage.getItem(key);
            // console.log(value)
            // parse the localStorage string and setState
            try {
                value = JSON.parse(value);
                console.log('before')
                setState({ [key]: value });
                console.log('after')
            } catch (e) {
                // handle empty string
                setState({ [key]: value });
            }
        }
    }
}

//in the component consuming CacheService
//this.Cache = new CacheService(); //in the constructor

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this.state, this.setState);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}

Body:
How about this?

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}

And then using setState like so...

hydrateStateWithSessionStorage(ReactComp) {
    for (let key in ReactComp.state) {
        ...
        ReactComp.setState({ [key]: value });
        ....
    }
}

FYI, this is not a React specific issue. The reason you are getting that error is, you are passing just a method that internally uses "this" (of that particular class) to the hydrateStateWithSessionStorage function. By the time, that method is called in the function, the scope has changed and "this" is not defined or not the same anymore.


问:
htaccess regex wildcard redirects overriding other redirects
I currently have the following redirects in htaccess, and I need to add two new redirects. Though it appears the last wildcard redirect is overriding the two new redirects which I am trying to add. How do I correct this? Any suggestions? Thank you.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^mydomain.com

RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]

RewriteRule ^.*.(jpe?g|gif|png|bmp|ico|swf|gz|xml|htm?l|pem|txt)$ - [L]

RewriteCond %{SCRIPT_FILENAME} !^apanel/*

RewriteRule ^(.*) process.php [L]

And the new redirects I am trying to add are as follows:

RewriteRule ^cs/(.*.css) /shared.php?type=css&files=$1

RewriteRule ^jscript/(.*.js) /shared.php?type=js&files=$1

答:
Well as I read it your last RewriteCond/RewriteRule says "if the filename isn't in the 'apanel' folder redirect it to process.php and stop".  Both of your new rules would match that rule first and mod_rewrite would stop processing further directives.

If you put your two new rules above your last Cond/Rule combo and use the [L] flag they should work properly....


问:
Multiple cron jobs in a chef recipe
I want to schedule 2 cron jobs using my chef recipe. Here are my entries

```<code>#Rotate the error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my command>"
end

#Rotate the Quantico error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my second command>"
end
</code>```

When I run this chef recipe, I always see the only one entry in my crontab -l output. Am I missing anything?

答:
Well, after going through the chef logs, I found this out. Cron creates the schedules based on the name you specify in the recipe and it doesn't create two separate jobs with the same name, instead, it updates them, which made sense (after looking at the logs). This is what I found in the logs:

```<code>[2019-05-31T15:27:02-07:00] INFO: cron[logrotate every 5 minutes] added crontab entry
.
.
[2019-05-31T15:27:03-07:00] INFO: cron[logrotate every 5 minutes] updated crontab entry
</code>```

So, the only thing I had to do was rename the second cron job to make my life easier and get back my Friday evening.

```<code>#Rotate the error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my command>"
end

#Rotate the Quantico error logs
cron "logrotate another file every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my second command>"
end
</code>```

Title: Multiple cron jobs in a chef recipe

Body:
I want to schedule 2 cron jobs using my chef recipe. Here are my entries

#Rotate the error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my command>"
end

#Rotate the Quantico error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my second command>"
end

When I run this chef recipe, I always see the only one entry in my crontab -l output. Am I missing anything?

Body:
Well, after going through the chef logs, I found this out. Cron creates the schedules based on the name you specify in the recipe and it doesn't create two separate jobs with the same name, instead, it updates them, which made sense (after looking at the logs). This is what I found in the logs:

[2019-05-31T15:27:02-07:00] INFO: cron[logrotate every 5 minutes] added crontab entry
.
.
[2019-05-31T15:27:03-07:00] INFO: cron[logrotate every 5 minutes] updated crontab entry

So, the only thing I had to do was rename the second cron job to make my life easier and get back my Friday evening.

#Rotate the error logs
cron "logrotate every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my command>"
end

#Rotate the Quantico error logs
cron "logrotate another file every 5 minutes" do
  action :create
  user "root"
  minute "*/5"
  command "<my second command>"
end


问:
How to capitalize every word including in the beginning of a quote?
For example, this sentence:

```<code>say "mosquito!"
</code>```

I try to capitalize with the following code:

```<code>'say "mosquito!"'.capitalize()
</code>```

Which returns this:

```<code>'Say "mosquito!"’
</code>```

However, the desired result is:

```<code>'Say "Mosquito!"’
</code>```

答:
You can use str.title:

```<code>print('say "mosquito!"'.title())

# Output: Say "Mosquito!"
</code>```

Looks like Python has a built-in method for this!

Body:
For example, this sentence:

say "mosquito!"

I try to capitalize with the following code:

'say "mosquito!"'.capitalize()

Which returns this:

'Say "mosquito!"’

However, the desired result is:

'Say "Mosquito!"’

Body:
You can use str.title:

print('say "mosquito!"'.title())

# Output: Say "Mosquito!"

Looks like Python has a built-in method for this!


问:
How do i create a function that creates list and adds members to those list based on user input?
I've created a Class call groups- The user is suppose to give the "group" a name and add members to it as they see fit. Its a Class function that would create a list and add members to that list.
The code i currently have does produce an empty list.

I've tried using .append(), .join(), .insert()

```<code>class group:
    def __init__(self, name, member):
        self.name = name =[]
        self.member = member.join(name)

test_one = group("church", "john")
print (test_one.name)
print(test_one.member)
</code>```

I expected the output of
Church = ["john"]

答:
You shouldn't be assigning a list to name, you should assign the list to self.member.

```<code>class group:
    def __init__(self, name, member):
        self.name = name
        self.member = []
        self.add_member(member)

    def add_member(self, member):
        self.member.append(member)

test_one = group("church", "john")
print (test_one.name)
print(test_one.member)
</code>```

DEMO

You could also write self.member = [member] in __init__(), but this is more modular -- only one method needs to know how to add a member.

Body:
I've created a Class call groups- The user is suppose to give the "group" a name and add members to it as they see fit. Its a Class function that would create a list and add members to that list.
The code i currently have does produce an empty list.

I've tried using .append(), .join(), .insert()

class group:
    def __init__(self, name, member):
        self.name = name =[]
        self.member = member.join(name)

test_one = group("church", "john")
print (test_one.name)
print(test_one.member)

I expected the output of
Church = ["john"]

Body:
You shouldn't be assigning a list to name, you should assign the list to self.member.

class group:
    def __init__(self, name, member):
        self.name = name
        self.member = []
        self.add_member(member)

    def add_member(self, member):
        self.member.append(member)

test_one = group("church", "john")
print (test_one.name)
print(test_one.member)

DEMO

You could also write self.member = [member] in __init__(), but this is more modular -- only one method needs to know how to add a member.


问:
appendChild() and createElement() Javascript question
When I use appendChild() and createElement() in my code, the subsequent styles for the defined CSS IDs are not applied. Can someone tell me why? Here's my code:

```<code>function searchDone(results) {
    var result = null;
    var parent = document.getElementById('postWrap');
    var child = null;
    parent.innerHTML = '';
    var insertHTML =" ";

    //Paginating Results Links
    resultNum = results.SearchResponse.Web.Total;
    resultNum = resultNum/10;
    child = document.createElement('div');
    child.id = "paging";
    if(results.SearchResponse.Web.Offset != 0){
        insertHTML ='<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset-10)+'"><</a></span>';
    }
    if(results.SearchResponse.Web.Offset == 0){
        insertHTML += '<span>1</span>';
    }else{
        insertHTML +='<span><a class="jsonp" href="#" rev="0">1</a></span>';
    }
    for(var i = 1; i <= resultNum; i++){
        if((results.SearchResponse.Web.Offset/10) == i){
            insertHTML += '<span>'+(i+1)+'</span>';
        }else{
            insertHTML += '<span><a class="jsonp b" href="#" rev="'+i*10+'">'+(i+1)+'</a></span>';
        }
    }
    if(results.SearchResponse.Web.Total - results.SearchResponse.Web.Offset > 10){
        insertHTML += '<span><a class="jsonp b" href="#" rev="'+(results.SearchResponse.Web.Offset+10)+'">></a></span>';
    }
    child.innerHTML = insertHTML;
    parent.appendChild(child);
</code>```

I then have some other code which processes my search query via API to Bing (only because Google now charges... )

Next, I use the same methods to insert another div:

```<code>//Insert Paginating results again
    child = null;
    child = document.createElement('div');
    child.innerHTML = insertHTML;
    child.id = "searchResultsPages";
    parent.appendChild(child);
</code>```

Now I'd like to apply some styles to these numbers. However, when I apply a style to searchResultsPage, like

```<code>#searchResultsPages{
 float: right;
}
</code>```

I don't get the style being passed on. The curious thing is that if I only insert one of these two elements, everything goes as planned and the style shows up fine. The problem is that I'd like pages displayed at the top and bottom of the search.

Any ideas why this is happening? I think it might have something to do with an element being used twice, but I don't know why this would effect anything if the objects are different.

Thanks.

答:
IDs should be unique within the page so if you have two elements with id="searchResultsPage" the behaviour can get a bit screwy and the HTML is invalid.  Instead, use a class="searchResultsPage" if there will be multiple elements.

The issue of the missing 's' the other commenters point out is also quite important though hopefully that was just a typo in the question.

Body:
When I use appendChild() and createElement() in my code, the subsequent styles for the defined CSS IDs are not applied. Can someone tell me why? Here's my code:

function searchDone(results) {
    var result = null;
    var parent = document.getElementById('postWrap');
    var child = null;
    parent.innerHTML = '';
    var insertHTML =" ";

    //Paginating Results Links
    resultNum = results.SearchResponse.Web.Total;
    resultNum = resultNum/10;
    child = document.createElement('div');
    child.id = "paging";
    if(results.SearchResponse.Web.Offset != 0){
        insertHTML ='<';
    }
    if(results.SearchResponse.Web.Offset == 0){
        insertHTML += '1';
    }else{
        insertHTML +='1';
    }
    for(var i = 1; i <= resultNum; i++){
        if((results.SearchResponse.Web.Offset/10) == i){
            insertHTML += ''+(i+1)+'';
        }else{
            insertHTML += ''+(i+1)+'';
        }
    }
    if(results.SearchResponse.Web.Total - results.SearchResponse.Web.Offset > 10){
        insertHTML += '>';
    }
    child.innerHTML = insertHTML;
    parent.appendChild(child);

I then have some other code which processes my search query via API to Bing (only because Google now charges... )

Next, I use the same methods to insert another div:

//Insert Paginating results again
    child = null;
    child = document.createElement('div');
    child.innerHTML = insertHTML;
    child.id = "searchResultsPages";
    parent.appendChild(child);

Now I'd like to apply some styles to these numbers. However, when I apply a style to searchResultsPage, like

#searchResultsPages{
 float: right;
}

I don't get the style being passed on. The curious thing is that if I only insert one of these two elements, everything goes as planned and the style shows up fine. The problem is that I'd like pages displayed at the top and bottom of the search.

Any ideas why this is happening? I think it might have something to do with an element being used twice, but I don't know why this would effect anything if the objects are different.

Thanks.


问:
How to get alarms from Bacnet using c#
I am trying to access alarms from PLC which is running on Bacnet protocol. I am using Windows 10 IoT platform (running on RPI). I can read all Bacnet object "properties" such as event state, alarm etc but I need to get all alarms of all objects.

I know that GetAlarmSummary and GetEnrollmentSummary is deprecated and I should use GetEventInformation service but when I am browsing through objects I can find notification class objects but I do not know how they are connected with binary or analog objects.

I also know that Bacnet object like (binary, analog, multistateValue) has notification class number which indicates number of notification class connected to the object but I really don't know how they are reacting on each other and how is error message generated. I have noticed that objects with error has event state set to alarm but I do not know how they are cooperating with notification classes because when I try to browse notification class I only get type and priority but nothing about connected objects. Could anyone provide some sample of code that I could use or give me some points to finish this issue?

Thanks

答:
Whether it helps or not; here's an example of the 'Get Alarm Summary' output:</p>

```<code>    Items - Count = '5' -

            Idx = '0' -

                    Obj Id = '12582946' ('0xC00022')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '34' ('0x22')
                            - N  = 'diagVasUnableToDriveMax|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '1' -

                    Obj Id = '12582947' ('0xC00023')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '35' ('0x23')
                            - N  = 'diagVasSourceTempFailure|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '2' -

                    Obj Id = '12582948' ('0xC00024')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '36' ('0x24')
                            - N  = 'diagVasSystemFailure|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '3' -

                    Obj Id = '54525954' ('0x3400002')
                            - T  = 'MULTI_STATE_INPUT' ('13' / '0xD')
                            - I# = '2' ('0x2')
                            - N  = 'Communication Status|generic-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '4' -

                    Obj Id = '54526017' ('0x3400041')
                            - T  = 'MULTI_STATE_INPUT' ('13' / '0xD')
                            - I# = '65' ('0x41')
                            - N  = 'Communication Status|vav-28'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )
</code>```

Title: How to get alarms from Bacnet using c#

Body:
Whether it helps or not; here's an example of the 'Get Alarm Summary' output:

    Items - Count = '5' -

            Idx = '0' -

                    Obj Id = '12582946' ('0xC00022')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '34' ('0x22')
                            - N  = 'diagVasUnableToDriveMax|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '1' -

                    Obj Id = '12582947' ('0xC00023')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '35' ('0x23')
                            - N  = 'diagVasSourceTempFailure|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '2' -

                    Obj Id = '12582948' ('0xC00024')
                            - T  = 'BINARY_INPUT' ('3' / '0x3')
                            - I# = '36' ('0x24')
                            - N  = 'diagVasSystemFailure|VAHU-01 VAS-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '3' -

                    Obj Id = '54525954' ('0x3400002')
                            - T  = 'MULTI_STATE_INPUT' ('13' / '0xD')
                            - I# = '2' ('0x2')
                            - N  = 'Communication Status|generic-2'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )

            Idx = '4' -

                    Obj Id = '54526017' ('0x3400041')
                            - T  = 'MULTI_STATE_INPUT' ('13' / '0xD')
                            - I# = '65' ('0x41')
                            - N  = 'Communication Status|vav-28'
                    Alarm State = 'OFFNORMAL' ('2')
                    Ack Transitions = '111' ( 'To Off-Normal'; 'To Fault'; 'To Normal' )


问:
How to test an object class inherit from a certain abstract class
In Python when you want to test that an object foo is an instance of Foo you do this :

```<code>if isinstance(foo, Foo):
    # do something
</code>```

Now, imagine that Foo class is a specialized class inherited from Bar and that there is a lot of other classes that inherit from it: I've Foo1, Foo2, ..., FooX, that inherit from Bar class.

foo could be an instance from any of these Foox class. What's interest me is to know that foo come from a class that inherited one day from Bar. Did you know a simple / canonical way to do it ?

答:
The correct approach is probably to test if foo is a Bar object, which shows that Foo inherited from Bar.

```<code>class Bar:
    pass

class Foo(Bar):
    pass

foo = Foo()

isinstance(foo, Bar)
</code>```

output:

```<code>True
</code>```

You could also check if the class Foo is a subclass of the class Bar:

```<code>issubclass(Foo, Bar)   # notice Foo, the class, not the instance foo
</code>```

Body:
In Python when you want to test that an object foo is an instance of Foo you do this :

if isinstance(foo, Foo):
    # do something

Now, imagine that Foo class is a specialized class inherited from Bar and that there is a lot of other classes that inherit from it: I've Foo1, Foo2, ..., FooX, that inherit from Bar class.

foo could be an instance from any of these Foox class. What's interest me is to know that foo come from a class that inherited one day from Bar. Did you know a simple / canonical way to do it ?

Body:
The correct approach is probably to test if foo is a Bar object, which shows that Foo inherited from Bar.

class Bar:
    pass

class Foo(Bar):
    pass

foo = Foo()

isinstance(foo, Bar)

output:

True

You could also check if the class Foo is a subclass of the class Bar:

issubclass(Foo, Bar)   # notice Foo, the class, not the instance foo


答:
You can use .map's 2nd argument, the index:

```<code>{data.map((newRow, index) => {
  const prevRow = data[index - 1];
  return (
    // Fragment is necessary because you will
    // now potentially render 2 elements
    <React.Fragment key={newRow.id}>
      {prevRow && newRow.date !== prevRow.date && (
        <tr>
          <td>{helpers.getFormattedDate(newRow.time)}</td>
          <td></td>
          <td></td>
        </tr>
      )}
      <tr>
        // The rest of your component
      </tr>
    <React.Fragment>
  )
}}
</code>```

Title: Conditional rendering within loops in React JS

Body:
I have data coming from an external API that I am trying to display in a table. The data comes back with date time stamps.

I'd like to render the data in a table, but with an extra row in that displays the date when the date changes.

What I've tried

I've attempted updating a lastDate prop value.

I've attempted conditional rendering with the (condition) ? expected : other syntax and a variable in the render() method.

I can't figure out how to keep track of the current date variable and update it on every loop iteration.

I've tried splitting the DateRow and the DataRow into seperate components and passing the date, but the state is not persisted.

I'm not sure what is best practice for doing this. Or if it's just a bad idea.

import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';

import * as helpers from '../../common/helpers';

export default class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch(`https://api.example.com`)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            data: result
          });
        }
      )
  }

  render() {
    const { data } = this.state;
    return (
      <>

Most Recent

              Time
              Column 1
              Column 2

            {data.map(newRow => (

              // Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
              // ie. if previousDate != currentDate
              //

              //   {helpers.getFormattedDate(newRow.time)}
              //
              //
              //

              // Then render the following :

                  {helpers.getFormattedTime(newRow.time)}

                  <Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>

                  {/* Some more content here */}

            ))}

      </>
    );
  }
}

Any help here would be appreciated, I'm more than a bit lost on this one.

Thanks!

Body:
You can use .map's 2nd argument, the index:

{data.map((newRow, index) => {
  const prevRow = data[index - 1];
  return (
    // Fragment is necessary because you will
    // now potentially render 2 elements
    <React.Fragment key={newRow.id}>
      {prevRow && newRow.date !== prevRow.date && (
        <tr>
          <td>{helpers.getFormattedDate(newRow.time)}</td>
          <td></td>
          <td></td>
        </tr>
      )}
      <tr>
        // The rest of your component
      </tr>
    <React.Fragment>
  )
}}