问:
Entering Strings of Bytes into C Program User Input
I'm working on a problem which involves performing a buffer overflow on a C program. The program asks for a command line input from the user, and I need to use this input to enter in my byte string including nops, shellcode, ret address, etc. The problem is the c program interprets everything I enter as a literal string, so if I enter in something like "\xff\xab\x12..." the program will interpret each separate character as a different byte. I can enter in separate bytes by creating a string of the corresponding ASCII characters for each byte, but this limits me to hex values 00-7F for my byte values. I'm wondering if there's some way I can use python to enter in the byte string, or possibly format the user input so that the C program interprets it the way I need it to. Please note that I don't know what the return address of the byte string will be until after I start running the program, so I can't make the byte string prior to running the C program I'm working on a Linux x86 shell, and I do not have the source code for the C program.

I've tried calling python to print the string I need into the input using commands like,

```<code>$(python -c 'print "\x41" * 205 + "\x34\x86")
</code>```

but the C program just interprets all these characters literally. I've also tried using extended ASCII characters but the C program doesn't seem to interpret them correctly, associating them all with an unknown character symbol and 0xc3 hex value. Is it possible there is some other character/hex mapping that the C program may be using?

If anyone knows a way I can enter the input the way I need to, your help would be very much appreciated.

thanks

答:
You were missing a semicolon (') in your shell call to python. Additionally:

If your executable takes its input in the form of a CLI argument:

$ ./yourprog $(python -c 'print "\x41" * 205 + "\x34\x86"')

If it takes its input in the form of STDIN:

$ python -c 'print "\x41" * 205 + "\x34\x86"' | ./yourprog

Replace "./yourprog" with the name of your executable.

Body:
I'm working on a problem which involves performing a buffer overflow on a C program. The program asks for a command line input from the user, and I need to use this input to enter in my byte string including nops, shellcode, ret address, etc. The problem is the c program interprets everything I enter as a literal string, so if I enter in something like "\xff\xab\x12..." the program will interpret each separate character as a different byte. I can enter in separate bytes by creating a string of the corresponding ASCII characters for each byte, but this limits me to hex values 00-7F for my byte values. I'm wondering if there's some way I can use python to enter in the byte string, or possibly format the user input so that the C program interprets it the way I need it to. Please note that I don't know what the return address of the byte string will be until after I start running the program, so I can't make the byte string prior to running the C program I'm working on a Linux x86 shell, and I do not have the source code for the C program.

I've tried calling python to print the string I need into the input using commands like,

$(python -c 'print "\x41" * 205 + "\x34\x86")

but the C program just interprets all these characters literally. I've also tried using extended ASCII characters but the C program doesn't seem to interpret them correctly, associating them all with an unknown character symbol and 0xc3 hex value. Is it possible there is some other character/hex mapping that the C program may be using?

If anyone knows a way I can enter the input the way I need to, your help would be very much appreciated.

thanks


来源: stackexchange

问:
How to generate an image using C code
The function below simply serves html when it is called, however

```<code>void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "<HTML><BODY><P>Hello World.</P></BODY></HTML>\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}
</code>```

My output on the web browser would by a simple Hello World message. However, I want to change it so that it will display a bitmap image instead. Let's use a 1x1 red pixel as our bmp.

I've modified this function so far by:

```<code>void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: image/bmp\r\n"
                "Content-Length: ???WTF???\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "BMF8\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = " "; //bmp file data goes here.
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}
</code>```

Quoting from Dan's answer, the data in hex looks like:

```<code>0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 130b 0000 130b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........
</code>```

However, I simply cannot place that inside the quotation marks. How would I do this?

答:
expanding on what @Dan D. said, you can use ImageMagick's "convert" command on a Linux (or possibly Windows also) box to convert raw data to an image. I tested with .png, you'll have to test the output on Windows yourself:</p>

```
jcomeau@intrepid:~$ echo -en "\0000" | convert -size 1x1 -depth 8 gray:- /tmp/1black.bmp
jcomeau@intrepid:~$ xxd /tmp/1black.bmp
0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 120b 0000 120b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........
```

ContentLicense: CC BY-SA 3.0

Title: How to generate an image using C code

Body:
The function below simply serves html when it is called, however

void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "
Hello World.
\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}

My output on the web browser would by a simple Hello World message. However, I want to change it so that it will display a bitmap image instead. Let's use a 1x1 red pixel as our bmp.

I've modified this function so far by:

void generateHTML (int socket) {
   char* message;

   // Sends HTTP response header

   message = "HTTP/1.0 200 OK\r\n"
                "Content-Type: image/bmp\r\n"
                "Content-Length: ???WTF???\r\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = "BMF8\n";
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));

   message = " "; //bmp file data goes here.
   printf ("about to send=> %s\n", message);
   write (socket, message, strlen (message));
}

Quoting from Dan's answer, the data in hex looks like:

0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 130b 0000 130b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........

However, I simply cannot place that inside the quotation marks. How would I do this?

Body:
expanding on what @Dan D. said, you can use ImageMagick's "convert" command on a Linux (or possibly Windows also) box to convert raw data to an image. I tested with .png, you'll have to test the output on Windows yourself:

jcomeau@intrepid:~$ echo -en "\0000" | convert -size 1x1 -depth 8 gray:- /tmp/1black.bmp
jcomeau@intrepid:~$ xxd /tmp/1black.bmp
0000000: 424d 3a00 0000 0000 0000 3600 0000 2800  BM:.......6...(.
0000010: 0000 0100 0000 0100 0000 0100 1800 0000  ................
0000020: 0000 0400 0000 120b 0000 120b 0000 0000  ................
0000030: 0000 0000 0000 0000 0000                 ..........


问:
Report Viewer didn't call sub Report method
I use following code to generate a PDF report:

```<code>public partial class Report{
 public void myMethode(DataTable DT){

        ReportViewer reportViewer1 = new ReportViewer();
        reportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));
        reportViewer1.LocalReport.ReportPath = @"Something" + ReportName + ".rdlc";
        reportViewer1.ProcessingMode = ProcessingMode.Local;

        reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", DT));
        reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubReportProcessing);

        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;
        string extension = string.Empty;
        reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

   }
 private static void SubReportProcessing(object sender, Microsoft.Reporting.WebForms.SubreportProcessingEventArgs e)
   {
        //do something
   }

}
</code>```

It's work fine for every main report but when it want to generate subreport it dosen't call SubReportProcessing method!!!

So can some one help me to find problem??

I am using Dot Net 4.7.2 also I used this as web api and I use Microsoft.ReportViewer.WebForms version 12.0.0.0

答:
I Use This Event For Call SubReports:

```<code>      // myMethode Function
        reportViewer.Reset();
        reportViewer.LocalReport.DataSources.Add(dataSource);
        reportViewer.LocalReport.ReportPath = "Report Path";
        reportViewer.LocalReport.SubreportProcessing +=
                                 LocalReportOnSubreportProcessing;
        reportViewer.LocalReport.Refresh();

   private void LocalReportOnSubreportProcessing(object sender,
                                                 SubreportProcessingEventArgs e)
        {
            //Following Code Is just a Sample
            switch (e.ReportPath)
            {
                case "ExamResult1To3Scores":
                    {
                        var ranksReportDataSource = new ReportDataSource
                        {
                            Name = "ExamResult1To3",
                            Value = GetCandidatesExamResultGuidanceRequest
                        };
                        e.DataSources.Add(ranksReportDataSource);
                        break;
                    }

                case "ExamResult1To3Chart":
                    {
                        var levelRank =
                            GetCandidatesRequest.First().Guidance1To3ChartData;

                        var chartReportDataSource = new ReportDataSource
                        {
                            Name = "ExamResult1To3Chart",
                            Value = levelRank
                        };
                        e.DataSources.Add(chartReportDataSource);
                        break;
                    }
                  }
</code>```

I Hope That You will Be Benefited From The Code.

ContentLicense: CC BY-SA 4.0

Body:
I use following code to generate a PDF report:

public partial class Report{
 public void myMethode(DataTable DT){

        ReportViewer reportViewer1 = new ReportViewer();
        reportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));
        reportViewer1.LocalReport.ReportPath = @"Something" + ReportName + ".rdlc";
        reportViewer1.ProcessingMode = ProcessingMode.Local;

        reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", DT));
        reportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubReportProcessing);

        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;
        string extension = string.Empty;
        reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

   }
 private static void SubReportProcessing(object sender, Microsoft.Reporting.WebForms.SubreportProcessingEventArgs e)
   {
        //do something
   }

}

It's work fine for every main report but when it want to generate subreport it dosen't call SubReportProcessing method!!!

So can some one help me to find problem??

I am using Dot Net 4.7.2 also I used this as web api and I use Microsoft.ReportViewer.WebForms version 12.0.0.0

Body:
I Use This Event For Call SubReports:

      // myMethode Function
        reportViewer.Reset();
        reportViewer.LocalReport.DataSources.Add(dataSource);
        reportViewer.LocalReport.ReportPath = "Report Path";
        reportViewer.LocalReport.SubreportProcessing +=
                                 LocalReportOnSubreportProcessing;
        reportViewer.LocalReport.Refresh();

   private void LocalReportOnSubreportProcessing(object sender,
                                                 SubreportProcessingEventArgs e)
        {
            //Following Code Is just a Sample
            switch (e.ReportPath)
            {
                case "ExamResult1To3Scores":
                    {
                        var ranksReportDataSource = new ReportDataSource
                        {
                            Name = "ExamResult1To3",
                            Value = GetCandidatesExamResultGuidanceRequest
                        };
                        e.DataSources.Add(ranksReportDataSource);
                        break;
                    }

                case "ExamResult1To3Chart":
                    {
                        var levelRank =
                            GetCandidatesRequest.First().Guidance1To3ChartData;

                        var chartReportDataSource = new ReportDataSource
                        {
                            Name = "ExamResult1To3Chart",
                            Value = levelRank
                        };
                        e.DataSources.Add(chartReportDataSource);
                        break;
                    }
                  }

I Hope That You will Be Benefited From The Code.


问:
React Native Component is undefined
I want to create a new StackNavigator with 'react-navigation' package
but when I initialize the screens for the StackNavigator i get an error -> undefined is not an object (evaluating '_TextUpload.TextUpload')

My TextUpload Component:

```<code>import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

export class TextUpload extends Component {
 constructor(props){
 super(props);
 this.state = {
   ready: false
 }
 }

 render() {
 return (
   <View style={styles.container}>
     <Text style={styles.welcome}>
       Text Upload
     </Text>
   </View>
 );
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});
</code>```

My StackNavigator Component:

```<code>import React from 'react';
import { createBottomTabNavigator, createAppContainer, createStackNavigator } from 'react-navigation';
import { Home, Profile, Feed, Upload, Notes, TextUpload, ImageScreen } from '../components';
import Icon from 'react-native-vector-icons/dist/FontAwesome';
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import {HOME_TAB_COLOR, FEED_TAB_COLOR, UPLOAD_TAB_COLOR, NOTE_TAB_COLOR, PROFILE_TAB_COLOR} from "../config";

const AppNavigator = createStackNavigator({
  Home: {
    screen: TextUpload
  }
});
</code>```

答:
You need import your pages on StackNavigator page. This is how i'm using;

```<code>import React, { Component } from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation';

import Device from "../pages/device";
import DeviceScreen from "../pages/devices";

const Project= createStackNavigator({
    Measures: {
        screen: Device
    },
    Devices: {
        screen: DeviceScreen
    }
});
export default createAppContainer(Project);
</code>```

its throw error when you import pages with curly brackets so don't use curly brackets.

Title: React Native Component is undefined

Body:
I want to create a new StackNavigator with 'react-navigation' package
but when I initialize the screens for the StackNavigator i get an error -> undefined is not an object (evaluating '_TextUpload.TextUpload')

My TextUpload Component:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

export class TextUpload extends Component {
 constructor(props){
 super(props);
 this.state = {
   ready: false
 }
 }

 render() {
 return (
   <View style={styles.container}>
     <Text style={styles.welcome}>
       Text Upload
     </Text>
   </View>
 );
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});

My StackNavigator Component:

import React from 'react';
import { createBottomTabNavigator, createAppContainer, createStackNavigator } from 'react-navigation';
import { Home, Profile, Feed, Upload, Notes, TextUpload, ImageScreen } from '../components';
import Icon from 'react-native-vector-icons/dist/FontAwesome';
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import {HOME_TAB_COLOR, FEED_TAB_COLOR, UPLOAD_TAB_COLOR, NOTE_TAB_COLOR, PROFILE_TAB_COLOR} from "../config";

const AppNavigator = createStackNavigator({
  Home: {
    screen: TextUpload
  }
});

Body:
You need import your pages on StackNavigator page. This is how i'm using;

import React, { Component } from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation';

import Device from "../pages/device";
import DeviceScreen from "../pages/devices";

const Project= createStackNavigator({
    Measures: {
        screen: Device
    },
    Devices: {
        screen: DeviceScreen
    }
});
export default createAppContainer(Project);

its throw error when you import pages with curly brackets so don't use curly brackets.


问:
Assign max value of group to all rows in that group
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)
```

<p>which gives</p>

<pre class="lang-r prettyprint-override"><code>    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5
</code>```

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23
```

<p>As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits. </p>

<p>In the end, this should be the result: </p>

<pre class="lang-r prettyprint-override"><code>Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23
</code>```

How do I go about this?

答:
Generate a sample dataset.

```<code>data <- as.data.frame(list(Appraisal.Type = c(rep("Final result", 2), rep("Grade supervisor", 2)),
                      Resits = rep(0, 4),
                      Credits = c(rep(6.5, 2), rep(0, 2)),
                      Course_code = rep(c("ABC1000", "ABC1003"), 2),
                      Student_ID = rep(10, 4)))
</code>```

Assign the max value of a group to all rows in this group and then delete rows that contain "Final results".

```<code>##Reassign the values of "Credits" column
for (i in 1: nlevels(as.factor(data$Course_code))) {
  Course_code <- unique(data$Course_code)[i]
  data$Credits [data$Course_code == Course_code] <- max (data$Credits [data$Course_code == Course_code])
}
##New dataset without "Final result" rows
data <- data[data$Appraisal.Type != "Final result",]
</code>```

Here is the result.

```<code>data
    Appraisal.Type Resits Credits Course_code Student_ID
3 Grade supervisor      0     6.5     ABC1000         10
4 Grade supervisor      0     6.5     ABC1003         10
</code>```

Body:
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)

which gives

    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23

As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits.

In the end, this should be the result:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23

How do I go about this?

Body:
Generate a sample dataset.

data <- as.data.frame(list(Appraisal.Type = c(rep("Final result", 2), rep("Grade supervisor", 2)),
                      Resits = rep(0, 4),
                      Credits = c(rep(6.5, 2), rep(0, 2)),
                      Course_code = rep(c("ABC1000", "ABC1003"), 2),
                      Student_ID = rep(10, 4)))

Assign the max value of a group to all rows in this group and then delete rows that contain "Final results".

##Reassign the values of "Credits" column
for (i in 1: nlevels(as.factor(data$Course_code))) {
  Course_code <- unique(data$Course_code)[i]
  data$Credits [data$Course_code == Course_code] <- max (data$Credits [data$Course_code == Course_code])
}
##New dataset without "Final result" rows
data <- data[data$Appraisal.Type != "Final result",]

Here is the result.

data
    Appraisal.Type Resits Credits Course_code Student_ID
3 Grade supervisor      0     6.5     ABC1000         10
4 Grade supervisor      0     6.5     ABC1003         10


问:
Why does Java allow only a single method X when implementing 2 interfaces that both declare X but which differ in their throws clauses?
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

```<code>import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}
</code>```

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

答:
First of all, I hope this is more of an academic question, than a problem that you are actually experiencing.  If not, the answer is most likely you are making a mistake by implementing the two interfaces in a single class.

But to answer your question... Lets say there is some code that wants an object of type ISomething1 because it needs to doSomething with it.  If your Impl class actually threw an exception the calling code would be utterly unprepared to handle the exception.

The opposite case is not true, therefore the compiler forces you to do it that way.

Body:
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.


问:
What should be the output of the custom loss function in Keras?
I am trying to build a custom loss function in Keras, but I am confused about the way it works. I am training the network on batches, and I am not sure if the output of the loss function should be an array with the same dimension as the batch or just a scalar.</p>

答:
As described in the documentation, keras loss, You can pass a function that returns a scalar for each data-point and takes the two arguments: y_true (True labels) and y_pred (Predictions).

Keras execute the mean over sample inside batch, so the output should just be a single scalar.


问:
How do I write a java method that adds the digits of each number in a string
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

```<code>import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}
</code>```

And this adds ALL the numbers in a string:

```<code>String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}
</code>```

I don't know how to combine this code with code that can add the numbers this method outputs together.

答:
I'm re-learning Java after a two decade hiatus, and evaluating BlueJ at the same time for possible use in my classroom.  This seemed like a great project to practice with, so thanks for the post!  Here's my take on it, without the use of Regular Expressions.

Class FindDigits:

```<code>import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FindDigits
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter string to analyze: ");
        String input = scan.nextLine();

        FindDigits fd = new FindDigits(input);
        System.out.println("Input: " + fd.getInput());
        List<NumberSum> results = fd.getSums();
        if (results.size() > 0)
        {
            for(NumberSum ns: results)
            {
                System.out.println("Number: " + ns.getNumber() + ", Sum: " + ns.getSum());
            }
        }
        else
        {
            System.out.println("No numbers found.");
        }
    }

    private String _input;
    public String getInput()
    {
        return _input;
    }

    public FindDigits(String input)
    {
        _input = input;
    }

    private List<String> getNumbers()
    {
        List<String> numbers = new ArrayList();
        String curNumber = "";
        for(Character c: getInput().toCharArray())
        {
            if(Character.isDigit(c))
            {
                curNumber = curNumber + c;
            }
            else
            {
                if (!curNumber.isEmpty())
                {
                    numbers.add(curNumber);
                    curNumber = "";
                }
            }
        }
        if (!curNumber.isEmpty())
        {
            numbers.add(curNumber);
        }
        return numbers;
    }

    public List<NumberSum> getSums()
    {
        List<NumberSum> sums = new ArrayList<NumberSum>();
        for(String number: getNumbers())
        {
            sums.add(new NumberSum(number));
        }
        return sums;
    }

}
</code>```

Class NumberSum:

```<code>public class NumberSum
{

        private String _number;
        public String getNumber()
        {
            return _number;
        }

        public NumberSum(String number)
        {
            _number = number;
            for(char c: number.toCharArray())
            {
                if(!Character.isDigit(c))
                {
                    _number = "";
                    break;
                }
            }
        }

        public int getSum()
        {
            return sum(getNumber());
        }

        private int sum(String number)
        {
            if (!getNumber().isEmpty())
            {
                int total = 0;
                for(char c: number.toCharArray())
                {
                    total = total + Character.getNumericValue(c);
                }
                return total;
            }
            else
            {
                return -1;
            }
        }

}
</code>```

Output:

Body:
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}

And this adds ALL the numbers in a string:

String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}

I don't know how to combine this code with code that can add the numbers this method outputs together.

Body:
I'm re-learning Java after a two decade hiatus, and evaluating BlueJ at the same time for possible use in my classroom.  This seemed like a great project to practice with, so thanks for the post!  Here's my take on it, without the use of Regular Expressions.

Class FindDigits:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FindDigits
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter string to analyze: ");
        String input = scan.nextLine();

        FindDigits fd = new FindDigits(input);
        System.out.println("Input: " + fd.getInput());
        List<NumberSum> results = fd.getSums();
        if (results.size() > 0)
        {
            for(NumberSum ns: results)
            {
                System.out.println("Number: " + ns.getNumber() + ", Sum: " + ns.getSum());
            }
        }
        else
        {
            System.out.println("No numbers found.");
        }
    }

    private String _input;
    public String getInput()
    {
        return _input;
    }

    public FindDigits(String input)
    {
        _input = input;
    }

    private List<String> getNumbers()
    {
        List<String> numbers = new ArrayList();
        String curNumber = "";
        for(Character c: getInput().toCharArray())
        {
            if(Character.isDigit(c))
            {
                curNumber = curNumber + c;
            }
            else
            {
                if (!curNumber.isEmpty())
                {
                    numbers.add(curNumber);
                    curNumber = "";
                }
            }
        }
        if (!curNumber.isEmpty())
        {
            numbers.add(curNumber);
        }
        return numbers;
    }

    public List<NumberSum> getSums()
    {
        List<NumberSum> sums = new ArrayList<NumberSum>();
        for(String number: getNumbers())
        {
            sums.add(new NumberSum(number));
        }
        return sums;
    }

}

Class NumberSum:

public class NumberSum
{

        private String _number;
        public String getNumber()
        {
            return _number;
        }

        public NumberSum(String number)
        {
            _number = number;
            for(char c: number.toCharArray())
            {
                if(!Character.isDigit(c))
                {
                    _number = "";
                    break;
                }
            }
        }

        public int getSum()
        {
            return sum(getNumber());
        }

        private int sum(String number)
        {
            if (!getNumber().isEmpty())
            {
                int total = 0;
                for(char c: number.toCharArray())
                {
                    total = total + Character.getNumericValue(c);
                }
                return total;
            }
            else
            {
                return -1;
            }
        }

}

Output:


问:
Vue component is rendring but page is blank.I can see the code by inspectinng the page
i'm making static site with laravel and vue.js. I make

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

this route enter code hereto load home page and

```<code>import VueRouter from 'vue-router'
import home from './components/home.vue'
import About from './components/About.vue'
import Contact from './components/Contact.vue'

Vue.use(VueRouter)

const routes = [

    { path: '/about', component: About },
    {
        path: '/',
        component: home
    },
    {
        path: '/contact',
        component: Contact
    }

]

const router = new VueRouter({
    mode: 'history',
    routes, // short for `routes: routes`,

})
</code>```

its my appp.js code. First time when page loaded on localhost:8000 the home page works fine but when i click to somme other route and come back it does not work it shows me blank page . but i can see html page by inspecting.

答:
It sounds like history mode is not configured correctly on the server side.

As a test, change this:

```<code>const router = new VueRouter({
    mode: 'history',
    routes, // short for `routes: routes`,

})
</code>```

...to this:

```<code>const router = new VueRouter({
    //mode: 'history',
    routes, // short for `routes: routes`,

})
</code>```

If it works, it means your server side is not set up properly for Vue History Mode and you'll need to configure your server side to allow for history mode.

Example 1

Example 2 - scroll down a little more than half way to "The Server-Side" section

Body:
i'm making static site with laravel and vue.js. I make

Route::get('/', function () {
    return view('layouts.master');
});

this route enter code hereto load home page and

import VueRouter from 'vue-router'
import home from './components/home.vue'
import About from './components/About.vue'
import Contact from './components/Contact.vue'

Vue.use(VueRouter)

const routes = [

    { path: '/about', component: About },
    {
        path: '/',
        component: home
    },
    {
        path: '/contact',
        component: Contact
    }

]

const router = new VueRouter({
    mode: 'history',
    routes, // short for `routes: routes`,

})

its my appp.js code. First time when page loaded on localhost:8000 the home page works fine but when i click to somme other route and come back it does not work it shows me blank page . but i can see html page by inspecting.

Body:
It sounds like history mode is not configured correctly on the server side.

As a test, change this:

const router = new VueRouter({
    mode: 'history',
    routes, // short for `routes: routes`,

})

...to this:

const router = new VueRouter({
    //mode: 'history',
    routes, // short for `routes: routes`,

})

If it works, it means your server side is not set up properly for Vue History Mode and you'll need to configure your server side to allow for history mode.

Example 1

Example 2 - scroll down a little more than half way to "The Server-Side" section


问:
EF Core adding discriminator column to owned entity
So my entity has two properties with an owned entity. For some reason EF Core is adding a discriminator column to one of them. It would be great if someone could help me figure out what I'm doing wrong or if there is some weird bug here.

This is the whole entity even though I suspect only Requested and Approved is relevant.

```<code>public class Absence
    {
        public Absence()
        {
            Requested = new AuditInfo();
            Approved = new AuditInfo();
        }

        public Guid Id { get; set; }

        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }

        public AbsenceType Type { get; set; }
        public AbsenceState State { get; set; }

        public AuditInfo Requested { get; set; }
        public AuditInfo Approved { get; set; }

        public Guid EmployeeId { get; set; }
        public Employee Employee { get; set; }

        public ICollection<AbsenceDay> Days { get; set; }

    }
</code>```

Absence doesn't have any special mappings but AuditInfo is mapped as

```<code>x.Owned<AuditInfo>();
</code>```

This mostly generate the expected SQL, except this weird item:

This also leads to the code failing at runtime with this message:

```<code>Message: Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ApprovedA_Discriminator', table 'bokio-test.dbo.Absences'; column does not allow nulls. INSERT fails.
The statement has been terminated.
</code>```

What I have tried:

I tried mapping the items like this which makes no difference:

```<code>        x.Entity<Absence>().OwnsOne(x1 => x1.Approved);
        x.Entity<Absence>().OwnsOne(x1 => x1.Requested);
</code>```

I tried renaming Approved to ApprovedA which made no difference.

I then tried a small repro like this which doesn't create a discriminator column:

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Address HomeAddress { get; set; }
    public Address WorkAddress { get; set; }

}
</code>```

Now I'm out of ideas and need some help.

Update 1:

Hold your hats, things are about to get really weird!

When I rename Approved to Donkey the discriminator column goes away

Almost stranger is that when I try to repro it with the name Approved in the small test I still don't get the discriminator column there.

Update 2:

So I tried a bunch of other names. Success means no discriminator column.

Xpproved = success
App = fail
Ap = fail
CrAp = success
A = fail
Axx = success
ApprovedXX = fail
XApproved = success

That inspired me to try this solution with XApproved which works

```<code>x.Entity<Absence>().OwnsOne(x1 => x1.XApproved, o =>
{
    o.Property(x2 => x2.Ip).HasColumnName("Approved_Ip");
    o.Property(x2 => x2.UserAgent).HasColumnName("Approved_UserAgent");
    o.Property(x2 => x2.UserId).HasColumnName("Approved_UserId");
    o.Property(x2 => x2.TimeUtc).HasColumnName("Approved_TimeUtc");
});
</code>```

Update 3:

AuditInfo only has these properties and no mappings beside being Owned. It does have a bunch of classes inheriting it though:

```<code>public DateTime TimeUtc { get; set; }
public Guid? UserId { get; set; }
public string Ip { get; set; }
public string UserAgent { get; set; }
</code>```

答:
While I don't fully understand the issue (why changing the name made the problem go away) I noticed that it didn't really solve the problem. But rather just moved it around. The comment comment from @philreed above was what really made it click.

AuditInfo was inherited by another Owned Entity ClosurePart. By changing from

```<code>public class AuditInfo {
...props here
}

public class ClosurePart : AuditInfo {}
</code>```

to

```<code>public class AuditInfoCommon {
...props here
}

public class AuditInfo : AuditInfoCommon {}

public class ClosurePart : AuditInfoCommon {}
</code>```

The problem went away fully without needing the hacks.

NOTE: AuditInfoCommon is not mapped into the model!

Body:
So my entity has two properties with an owned entity. For some reason EF Core is adding a discriminator column to one of them. It would be great if someone could help me figure out what I'm doing wrong or if there is some weird bug here.

This is the whole entity even though I suspect only Requested and Approved is relevant.

public class Absence
    {
        public Absence()
        {
            Requested = new AuditInfo();
            Approved = new AuditInfo();
        }

        public Guid Id { get; set; }

        public DateTime StartDate { get; set; }
        public DateTime? EndDate { get; set; }

        public AbsenceType Type { get; set; }
        public AbsenceState State { get; set; }

        public AuditInfo Requested { get; set; }
        public AuditInfo Approved { get; set; }

        public Guid EmployeeId { get; set; }
        public Employee Employee { get; set; }

        public ICollection<AbsenceDay> Days { get; set; }

    }

Absence doesn't have any special mappings but AuditInfo is mapped as

x.Owned<AuditInfo>();

This mostly generate the expected SQL, except this weird item:

This also leads to the code failing at runtime with this message:

Message: Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
---- System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ApprovedA_Discriminator', table 'bokio-test.dbo.Absences'; column does not allow nulls. INSERT fails.
The statement has been terminated.

What I have tried:

I tried mapping the items like this which makes no difference:

        x.Entity<Absence>().OwnsOne(x1 => x1.Approved);
        x.Entity<Absence>().OwnsOne(x1 => x1.Requested);

I tried renaming Approved to ApprovedA which made no difference.

I then tried a small repro like this which doesn't create a discriminator column:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Address HomeAddress { get; set; }
    public Address WorkAddress { get; set; }

}

Now I'm out of ideas and need some help.

Update 1:

Hold your hats, things are about to get really weird!

When I rename Approved to Donkey the discriminator column goes away

Almost stranger is that when I try to repro it with the name Approved in the small test I still don't get the discriminator column there.

Update 2:

So I tried a bunch of other names. Success means no discriminator column.

Xpproved = success
App = fail
Ap = fail
CrAp = success
A = fail
Axx = success
ApprovedXX = fail
XApproved = success

That inspired me to try this solution with XApproved which works

x.Entity<Absence>().OwnsOne(x1 => x1.XApproved, o =>
{
    o.Property(x2 => x2.Ip).HasColumnName("Approved_Ip");
    o.Property(x2 => x2.UserAgent).HasColumnName("Approved_UserAgent");
    o.Property(x2 => x2.UserId).HasColumnName("Approved_UserId");
    o.Property(x2 => x2.TimeUtc).HasColumnName("Approved_TimeUtc");
});

Update 3:

AuditInfo only has these properties and no mappings beside being Owned. It does have a bunch of classes inheriting it though:

public DateTime TimeUtc { get; set; }
public Guid? UserId { get; set; }
public string Ip { get; set; }
public string UserAgent { get; set; }

Body:
While I don't fully understand the issue (why changing the name made the problem go away) I noticed that it didn't really solve the problem. But rather just moved it around. The comment comment from @philreed above was what really made it click.

AuditInfo was inherited by another Owned Entity ClosurePart. By changing from

public class AuditInfo {
...props here
}

public class ClosurePart : AuditInfo {}

to

public class AuditInfoCommon {
...props here
}

public class AuditInfo : AuditInfoCommon {}

public class ClosurePart : AuditInfoCommon {}

The problem went away fully without needing the hacks.

NOTE: AuditInfoCommon is not mapped into the model!


问:
How to reference IdentityDbContext in database project shared across solution
I would like to take advantage of the IdentityDbContext that comes out of the box in Visual Studio templates for ASP.NET Core projects. However, I would like my entities and migrations to live in a shared project to be referenced by different components of the solution (Web, API, background services, etc.).

My shared database project was going to be a .NET Standard project, but it looks like I'll have to add a reference to Microsoft.AspNetCore.Identity.EntityFrameworkCore. It feels weird introducing to a Standard project a dependency on a Core assembly that is specifically for ASP.NET. Will that pose any problems?

答: Shouldnt be a problem going that way.. Its a problem if you tried to reference Net Framework libraries within a Net Core project</p>


问:
How to check whether Java plugins are installed or not in a browser using Code .?
How to check whether Java plugins are installed or not in a browser using java or javascript or JSP Code .?</p>

答:
Try this:

https://cdnjs.com/libraries/jqplugin

Eg.

```<code>jQuery.browser.java //Java
</code>```

Body:
Try this:

https://cdnjs.com/libraries/jqplugin

Eg.

jQuery.browser.java //Java


问:
Pass data from activity back to already created fragment
Bank app:

I have a NavigationDrawerActivity which has more fragments. Each fragment is created after menu item is clicked.

```<code>@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
    } else if (id == R.id.nav_transfer) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new TransferFragment()).commit();
    }
    return true;
}
</code>```

If I click on "transfer" menu item, TransferFragment is created. This fragment is responsible for simple money transferring from one bank account to another. I have a "choose account" button in this fragment which starts (using intent) new activity - ChooseAccountActivity. This activity is just a listView containing all accounts which can be used to transfer the money from.

After the user clicks on one of the accounts, the accountId (String) should be sent BACK to TransferFragment so the user is able to continue filling up other EditTexts (amount, receiver's account id, etc.)

method in "ChooseAccountActivity":

```<code>public void eventAfterClickOnListViewItem() {
    accountsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String accountId = allAccountsList.get(position);
            //PASS accountId back to TransferFragment
            finish();
        }
    });
}
</code>```

So I need to send the data (accountId) back to TransferFragment. But Intent doesn't work because I work with fragment. The TransferFragment is already created so only onStart, onResume,.. is called after coming back to the fragment.

Any tip or advice how I can pass the data from the activity to the already created fragment? Am I doing this right or should I change my thinking?

答:
You can use startActivityForResult in your TransferFragment to start ChooseAccountActivity and override onActivityResult at TransferFragment to get the accountId.
Make sure to read this to get the results in your fragment.

Body:
Bank app:

I have a NavigationDrawerActivity which has more fragments. Each fragment is created after menu item is clicked.

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.nav_home) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
    } else if (id == R.id.nav_transfer) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new TransferFragment()).commit();
    }
    return true;
}

If I click on "transfer" menu item, TransferFragment is created. This fragment is responsible for simple money transferring from one bank account to another. I have a "choose account" button in this fragment which starts (using intent) new activity - ChooseAccountActivity. This activity is just a listView containing all accounts which can be used to transfer the money from.

After the user clicks on one of the accounts, the accountId (String) should be sent BACK to TransferFragment so the user is able to continue filling up other EditTexts (amount, receiver's account id, etc.)

method in "ChooseAccountActivity":

public void eventAfterClickOnListViewItem() {
    accountsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String accountId = allAccountsList.get(position);
            //PASS accountId back to TransferFragment
            finish();
        }
    });
}

So I need to send the data (accountId) back to TransferFragment. But Intent doesn't work because I work with fragment. The TransferFragment is already created so only onStart, onResume,.. is called after coming back to the fragment.

Any tip or advice how I can pass the data from the activity to the already created fragment? Am I doing this right or should I change my thinking?


问:
Why SUM of column values return 1?
I m trying to get sum of user's
visits for current month. This is my code (if important to know,I use ORM RedBeanPHP):

```<code>$summ = R::exec('SELECT SUM(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);
</code>```

And $summ is always 1, even if its not true. ._.
My table statistic:
https://drive.google.com/open?id=1MFt-FtEtqkk7QWQC2oAtMBA0WAgOIV4h

P.S. Also, when I try get values only of row with max value of column I need,like this:

```<code>$summ = R::exec('SELECT MAX(amount),value FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);
</code>```

I run into error:
"Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'somesite.statistic.value'; this is incompatible with sql_mode=only_full_group_by"
I said ok, and tried add GROUP BY ID. But then I get just 1st row, but not only with actuall max value ._. I dunno what I did wrong

答:
In RedBeanPHP, you must use other function than R::exec for SELECT queries. The number you are getting is probably number of rows returned by select or a simple value indicating success.

Try

```<code>$summ = (int)R::getCell('SELECT SUM(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);
</code>```

For the second question, you might want to study SQL a bit, at least the very basics. Nested query like this may work for you.

```<code>SELECT value FROM statistic WHERE amount = (SELECT MAX(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month') LIMIT 1
</code>```

You will need to use it with R::getCell again (or R::getRow if you wanted to retrieve multiple columns).

Title: Why SUM of column values return 1?

Body:
I m trying to get sum of user's
visits for current month. This is my code (if important to know,I use ORM RedBeanPHP):

$summ = R::exec('SELECT SUM(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);

And $summ is always 1, even if its not true. ._.
My table statistic:
https://drive.google.com/open?id=1MFt-FtEtqkk7QWQC2oAtMBA0WAgOIV4h

P.S. Also, when I try get values only of row with max value of column I need,like this:

$summ = R::exec('SELECT MAX(amount),value FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);

I run into error:
"Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'somesite.statistic.value'; this is incompatible with sql_mode=only_full_group_by"
I said ok, and tried add GROUP BY ID. But then I get just 1st row, but not only with actuall max value ._. I dunno what I did wrong

Body:
In RedBeanPHP, you must use other function than R::exec for SELECT queries. The number you are getting is probably number of rows returned by select or a simple value indicating success.

Try

$summ = (int)R::getCell('SELECT SUM(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month',[':month'=>date('m')]);

For the second question, you might want to study SQL a bit, at least the very basics. Nested query like this may work for you.

SELECT value FROM statistic WHERE amount = (SELECT MAX(amount) FROM statistic WHERE type = "usuall_visit" AND month = :month') LIMIT 1

You will need to use it with R::getCell again (or R::getRow if you wanted to retrieve multiple columns).


问:
How to efficiently store pairs of numbers in a set?
In my program, I need to store pairs of numbers in range [1, 10**5) in a set and look them up many times. I can add them to the set as tuples:

```<code>seen = set()
seen.add((x, y))
(x, y) in seen  # True
</code>```

but is there a more efficient way, e.g. using a numeric/string key that is a combination of two numbers?

答:
While combining the numbers together (x*10**5+y) gives better performance, it may be harder to debug issues in your set.  An alternative that is faster than tuple sets but a bit slower than numeric combinations would be to use a dictionary of sets:

```<code>def f3():
    seen = dict()
    for x in range(1000):
        for y in range(1000):
            seen.setdefault(x,set()).add(y)   # insert a new pair
            assert x in seen and y in seen[x] # check if pair in dictionary
</code>```

This f3() function times at 0.284 sec vs f2() at 0.248 (so not a huge loss of performance).   It also gives you the added benefit of being able to easily list the y values of any given x.

EDIT

Using defaultdict does indeed make it faster. It's even faster than numeric combinations (0.126) and 4x faster than a set of tuples.

```<code>from collections import defaultdict
def f4():
    seen = defaultdict(set)
    for x in range(1000):
        for y in range(1000):
            seen[x].add(y)        # insert a new pair
            assert y in seen[x]   # check if pair in dictionary
</code>```

Body:
In my program, I need to store pairs of numbers in range [1, 10**5) in a set and look them up many times. I can add them to the set as tuples:

seen = set()
seen.add((x, y))
(x, y) in seen  # True

but is there a more efficient way, e.g. using a numeric/string key that is a combination of two numbers?

Body:
While combining the numbers together (x*10**5+y) gives better performance, it may be harder to debug issues in your set.  An alternative that is faster than tuple sets but a bit slower than numeric combinations would be to use a dictionary of sets:

def f3():
    seen = dict()
    for x in range(1000):
        for y in range(1000):
            seen.setdefault(x,set()).add(y)   # insert a new pair
            assert x in seen and y in seen[x] # check if pair in dictionary

This f3() function times at 0.284 sec vs f2() at 0.248 (so not a huge loss of performance).   It also gives you the added benefit of being able to easily list the y values of any given x.

EDIT

Using defaultdict does indeed make it faster. It's even faster than numeric combinations (0.126) and 4x faster than a set of tuples.

from collections import defaultdict
def f4():
    seen = defaultdict(set)
    for x in range(1000):
        for y in range(1000):
            seen[x].add(y)        # insert a new pair
            assert y in seen[x]   # check if pair in dictionary


问:
Component isn't re-rendering after state change in reducer
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

```<code>class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (
            <div>
            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&
                    <div>
                        <ul>
                            {this.state.queue.map((queuedItem, i) =>
                                <li key={i}>{queuedItem}</li>
                            )}
                        </ul>
                    </div>}

                <div>

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))
</code>```

QResults.js

```<code>export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (
            <ul>
                {this.props.allQueryResults.items.map((trackAlbum, i) =>
                    <li key={i}>
                        <a href='#'
                        onClick={
                            () => requestHandler(trackAlbum.name)}>
                            Some link
                        </a>
                    </li>
                )}
            </ul>
        )
    }
}
</code>```

actions.js

```<code>export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}
</code>```

reducers.js

```<code>import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer
</code>```

答:
this.state.queue refers to the state which is local to your Channel component. It is not the redux state. You initialize this.state.queue to an empty array, and then you never change it (ie, you never call this.setState).

If you want to interact with the state in redux, that's where mapStateToProps comes in. Since you've got a mapStateToProps that looks like this:

```<code>function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}
</code>```

The Channel component will get a prop named queue, and you can interact with it via this.props.queue.

So, the fix is to update Channel to interact with the prop. Most likely you'll want to delete this.state.queue, as it doesn't seem to serve a purpose and is causing confusion due to its name.

```<code>{this.props.queue &&
  this.props.queue.length > 0 &&
    <div>
      <ul>
        {this.state.queue.map((queuedItem, i) =>
          <li key={i}>{queuedItem}</li>
        )}
      </ul>
    </div>
  }
</code>```

Additionally, the way you've set up the root reducer has your redux state looking something like this:

```<code>{
  reducer1: {}, // not sure what this contains, since reducer 1 was omitted
  reducer2: {
    queue: [],
  }
}
</code>```

So if that's really what you want your redux state to look like, your map state to props will need to be updated to this:

```<code>function mapStateToProps(state) {
    const {queue} = state.reducer2;
    return {queue};
}
</code>```

Body:
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (

            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&

                            {this.state.queue.map((queuedItem, i) =>

{queuedItem}

                            )}

}

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />

        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))

QResults.js

export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (

                {this.props.allQueryResults.items.map((trackAlbum, i) =>

                         requestHandler(trackAlbum.name)}>
                            Some link

                )}

        )
    }
}

actions.js

export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}

reducers.js

import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer

Body:
this.state.queue refers to the state which is local to your Channel component. It is not the redux state. You initialize this.state.queue to an empty array, and then you never change it (ie, you never call this.setState).

If you want to interact with the state in redux, that's where mapStateToProps comes in. Since you've got a mapStateToProps that looks like this:

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

The Channel component will get a prop named queue, and you can interact with it via this.props.queue.

So, the fix is to update Channel to interact with the prop. Most likely you'll want to delete this.state.queue, as it doesn't seem to serve a purpose and is causing confusion due to its name.

{this.props.queue &&
  this.props.queue.length > 0 &&
    <div>
      <ul>
        {this.state.queue.map((queuedItem, i) =>
          <li key={i}>{queuedItem}</li>
        )}
      </ul>
    </div>
  }

Additionally, the way you've set up the root reducer has your redux state looking something like this:

{
  reducer1: {}, // not sure what this contains, since reducer 1 was omitted
  reducer2: {
    queue: [],
  }
}

So if that's really what you want your redux state to look like, your map state to props will need to be updated to this:

function mapStateToProps(state) {
    const {queue} = state.reducer2;
    return {queue};
}


问:
Why can't I center a SizeTransition horizontally in a Column in Flutter?
Please check the following code. Regardless what I tried, the SizeTransition is not centered horizontally in the Column. I tried to wrap Column in a Container and then provide infinite width. I tried to wrap SizeTransition in a Center. I tried to wrap SizeTransition in a Container which has center alignment property. I tried to wrap it in a Stack. I tried to give the container child with alignment center property etc... But none of them works...

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: AnimatedBox(),
    );
  }
}

class AnimatedBox extends StatefulWidget {
  @override
  createState() => _AnimatedBoxState();
}

class _AnimatedBoxState extends State<AnimatedBox> with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text('animate forward'),
          onPressed: () {_controller.forward();},
        ),
        RaisedButton(
          child: Text('animate reverse'),
          onPressed: () {_controller.reverse();},
        ),
        const SizedBox(height: 100.0,),
        SizeTransition(
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.blue,
          ),
          sizeFactor: CurvedAnimation(
            curve: Curves.fastOutSlowIn,
            parent: _controller,
          ),
        ),
      ],
    );
  }
}
```

<p>For instance, the following code does not work for <code>SizeTransition</code>, but works for <code>ScaleTransition</code>. I have no idea what's wrong with <code>SizeTransition</code>.</p>

<pre class="lang-dart prettyprint-override"><code>return Container(
      width: double.infinity,
      child: Column(
</code>```

答:
I can see that you tried many things already, here is some ideas I have:

#1

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: // ...
)
```

<p>or</p>

<p>#2</p>

<pre class="lang-dart prettyprint-override"><code>Column(
  crossAxisAlignment: CrossAxisAlignment.stretch, // critical
  children: <Widget>[
    // ...,
    Container(
      alignment: Alignment.center, // critical
      child: SizeTransition(
        child: Container(
          width: 200.0,
          height: 200.0,
          color: Colors.blue,
        ),
        sizeFactor: CurvedAnimation(
          curve: Curves.fastOutSlowIn,
          parent: _controller,
        ),
      ),
    ),
  ]
)
</code>```

Update

There is indeed a peculiar aspect of SizeTransition widget.

It has axis property that is set to Axis.vetical by default, which overrides the widget's horizontal alignment to -1.0 (start) and vertical alignment to 0.0 (center).

Changing that property to Axis.horizontal makes things work the other way around - aligning the widget horizontally to 0.0 (center) and vertically to -1.0 (start).

Solution:

SizeTransition(
  axis: Axis.horizontal,
  // ...,
)
```

Please let me know if this helped.

Body:
Please check the following code. Regardless what I tried, the SizeTransition is not centered horizontally in the Column. I tried to wrap Column in a Container and then provide infinite width. I tried to wrap SizeTransition in a Center. I tried to wrap SizeTransition in a Container which has center alignment property. I tried to wrap it in a Stack. I tried to give the container child with alignment center property etc... But none of them works...

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: AnimatedBox(),
    );
  }
}

class AnimatedBox extends StatefulWidget {
  @override
  createState() => _AnimatedBoxState();
}

class _AnimatedBoxState extends State<AnimatedBox> with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 400),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          child: Text('animate forward'),
          onPressed: () {_controller.forward();},
        ),
        RaisedButton(
          child: Text('animate reverse'),
          onPressed: () {_controller.reverse();},
        ),
        const SizedBox(height: 100.0,),
        SizeTransition(
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.blue,
          ),
          sizeFactor: CurvedAnimation(
            curve: Curves.fastOutSlowIn,
            parent: _controller,
          ),
        ),
      ],
    );
  }
}

For instance, the following code does not work for SizeTransition, but works for ScaleTransition. I have no idea what's wrong with SizeTransition.

return Container(
      width: double.infinity,
      child: Column(

Body:
I can see that you tried many things already, here is some ideas I have:

#1

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: // ...
)

or

#2

Column(
  crossAxisAlignment: CrossAxisAlignment.stretch, // critical
  children: <Widget>[
    // ...,
    Container(
      alignment: Alignment.center, // critical
      child: SizeTransition(
        child: Container(
          width: 200.0,
          height: 200.0,
          color: Colors.blue,
        ),
        sizeFactor: CurvedAnimation(
          curve: Curves.fastOutSlowIn,
          parent: _controller,
        ),
      ),
    ),
  ]
)

Update

There is indeed a peculiar aspect of SizeTransition widget.

It has axis property that is set to Axis.vetical by default, which overrides the widget's horizontal alignment to -1.0 (start) and vertical alignment to 0.0 (center).

Changing that property to Axis.horizontal makes things work the other way around - aligning the widget horizontally to 0.0 (center) and vertically to -1.0 (start).

Solution:

SizeTransition(
  axis: Axis.horizontal,
  // ...,
)

Please let me know if this helped.


问:
Why doesn't my String comparison code work?
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

```<code>int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}
</code>```

i want to print the statement. but it throws ArrayOutOfBoundary Error.

答:
The problem is the way you declared the character arrays.

```<code>char[] chr1 = {};
</code>```

The way you did it the array is defined with a size of 0.

In Java you need to specify the size of the array like this:

```<code>char[] chr1 = new char[3];
</code>```

What this does is it declares a char array with a predefined size of 3.

Body:
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}

i want to print the statement. but it throws ArrayOutOfBoundary Error.

Body:
The problem is the way you declared the character arrays.

char[] chr1 = {};

The way you did it the array is defined with a size of 0.

In Java you need to specify the size of the array like this:

char[] chr1 = new char[3];

What this does is it declares a char array with a predefined size of 3.


问:
How to add proxy to BoxApiConnection in box java sdk?
I need to set proxy in boxapiconnection. But could not get any reference code to use.Can anyone give me solution?</p>

答:
I had the same issue with BoxDeveloperEditionAPIConnection which does not have a proxy. I created the below code to overcome the issue which gives token which auto-refreshes after expiry time:</p>

```<code>import com.box.sdk.BoxConfig;
import com.box.sdk.BoxDeveloperEditionAPIConnection;
import com.box.sdk.DeveloperEditionEntityType;
import com.box.sdk.IAccessTokenCache;
import com.eclipsesource.json.JsonObject;

import java.net.Proxy;

public class MyBoxAPIConnection extends BoxDeveloperEditionAPIConnection {

private IAccessTokenCache accessTokenCache;
private String entityID;
private DeveloperEditionEntityType entityType;

public MyBoxAPIConnection(BoxConfig boxConfig, IAccessTokenCache accessTokenCache, Proxy proxy) {
    this(boxConfig.getEnterpriseId(), DeveloperEditionEntityType.ENTERPRISE, boxConfig, accessTokenCache);
    this.setProxy(proxy);
    this.tryRestoreUsingAccessTokenCache();
}

public MyBoxAPIConnection(String entityId, DeveloperEditionEntityType entityType, BoxConfig boxConfig,
        IAccessTokenCache accessTokenCache) {
    super(entityId, entityType, boxConfig, accessTokenCache);
}

private void tryRestoreUsingAccessTokenCache() {
    if (this.accessTokenCache == null) {
        // no cache specified so force authentication
        this.authenticate();
    } else {
        String cachedTokenInfo = this.accessTokenCache.get(this.getAccessTokenCacheKey());
        if (cachedTokenInfo == null) {
            // not found; probably first time for this client config so authenticate; info will then be cached
            this.authenticate();
        } else {
            // pull access token cache info; authentication will occur as needed (if token is expired)
            JsonObject json = JsonObject.readFrom(cachedTokenInfo);
            this.setAccessToken(json.get("accessToken").asString());
            this.setLastRefresh(json.get("lastRefresh").asLong());
            this.setExpires(json.get("expires").asLong());
        }
    }
}

private String getAccessTokenCacheKey() {
    return String.format("/%s/%s/%s/%s", this.getUserAgent(), this.getClientID(), this.entityType.toString(),
            this.entityID);
}

}
</code>```

Body:
I had the same issue with BoxDeveloperEditionAPIConnection which does not have a proxy. I created the below code to overcome the issue which gives token which auto-refreshes after expiry time:

import com.box.sdk.BoxConfig;
import com.box.sdk.BoxDeveloperEditionAPIConnection;
import com.box.sdk.DeveloperEditionEntityType;
import com.box.sdk.IAccessTokenCache;
import com.eclipsesource.json.JsonObject;

import java.net.Proxy;

public class MyBoxAPIConnection extends BoxDeveloperEditionAPIConnection {

private IAccessTokenCache accessTokenCache;
private String entityID;
private DeveloperEditionEntityType entityType;

public MyBoxAPIConnection(BoxConfig boxConfig, IAccessTokenCache accessTokenCache, Proxy proxy) {
    this(boxConfig.getEnterpriseId(), DeveloperEditionEntityType.ENTERPRISE, boxConfig, accessTokenCache);
    this.setProxy(proxy);
    this.tryRestoreUsingAccessTokenCache();
}

public MyBoxAPIConnection(String entityId, DeveloperEditionEntityType entityType, BoxConfig boxConfig,
        IAccessTokenCache accessTokenCache) {
    super(entityId, entityType, boxConfig, accessTokenCache);
}

private void tryRestoreUsingAccessTokenCache() {
    if (this.accessTokenCache == null) {
        // no cache specified so force authentication
        this.authenticate();
    } else {
        String cachedTokenInfo = this.accessTokenCache.get(this.getAccessTokenCacheKey());
        if (cachedTokenInfo == null) {
            // not found; probably first time for this client config so authenticate; info will then be cached
            this.authenticate();
        } else {
            // pull access token cache info; authentication will occur as needed (if token is expired)
            JsonObject json = JsonObject.readFrom(cachedTokenInfo);
            this.setAccessToken(json.get("accessToken").asString());
            this.setLastRefresh(json.get("lastRefresh").asLong());
            this.setExpires(json.get("expires").asLong());
        }
    }
}

private String getAccessTokenCacheKey() {
    return String.format("/%s/%s/%s/%s", this.getUserAgent(), this.getClientID(), this.entityType.toString(),
            this.entityID);
}

}


问:
Getting an error trying to make the range of a while loop above 10
I have a JSON object with different cars, I am relaying these cars to HTML with a loop, however whenever I try to make the condition (<=) above 10, it throws an error.

This is for a test I am making with a cars site.

Here is my function:

```<code>function dispCars(){
    let output = "";
    let i = 1;
    let maxNum = 10;
    while (i <= maxNum){
      const carName = cars["c" + i].name;
      const carMake = cars["c" + i].make;
      const carPrice = cars["c" + i].price;
      console.log(carName);
      output += "<div class='column'><div style='padding:0px;' class='ui segment'><a href='#'><img class='card-icon' src='../src/media/cars/" + i + ".jpg'></a><a href='#'><p class='heading'>"+ carMake + " " + carName + "</a><span class='price'>" + carPrice + "</span></p></div></div></div>";
      i++;
    }

    catalogue.innerHTML = output;
}
</code>```

Here is a little bit of JSON:

```<code>const cars = {
    "c1": {
        "id": 1,
        "name": "Sprinter Boxtruck",
        "make": "Mercedes",
        "price": "£500,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c2": {
        "id": 2,
        "name": "RS4 Avant",
        "make": "Audi",
        "price": "£300,000",
        "topspeed": "101mph",
        "vip": "false"
    },
    "c3": {
        "id": 3,
        "name": "250 GTO",
        "make": "Ferrari",
        "price": "£350,000",
        "topspeed": "92mph",
        "vip": "false"
    },
    "c4": {
        "id": 4,
        "name": "Enzo",
        "make": "Ferrari",
        "price": "£3,500,000",
        "topspeed": "130mph",
        "vip": "false"
    }
    ,
    "c5": {
        "id": 5,
        "name": "F350 Superduty",
        "make": "Ford",
        "price": "£500,000",
        "topspeed": "80mph",
        "vip": "false"
    },
    "c6": {
        "id": 6,
        "name": "Focus SVT",
        "make": "Ford",
        "price": "£250,000",
        "topspeed": "81mph",
        "vip": "false"
    },
    "c7": {
        "id": 7,
        "name": "Mustang GT",
        "make": "Ford",
        "price": "£800,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c8": {
        "id": 8,
        "name": "Raptor SVT",
        "make": "Ford",
        "price": "£500,000",
        "topspeed": "70mph",
        "vip": "false"
    },
    "c9": {
        "id": 9,
        "name": "Transit",
        "make": "Ford",
        "price": "£150,000",
        "topspeed": "87mph",
        "vip": "false"
    }
    ,
    "10": {
        "id": 10,
        "name": "E-Type",
        "make": "Jaguar",
        "price": "£250,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c11": {
        "id": 11,
        "name": "F-Type",
        "make": "Mercedes",
        "price": "£600,000",
        "topspeed": "99mph",
        "vip": "false"
    },
    "c12": {
        "id": 12,
        "name": "Gallardo",
        "make": "Lamborghini",
        "price": "£2,500,000",
        "topspeed": "111mph",
        "vip": "false"
    },
...
</code>```

Here is the error thrown:

```<code>index.js:29 Uncaught TypeError: Cannot read property 'name' of undefined
    at dispCars (index.js:29)
    at index.js:40
</code>```

My expected result is for the output to correspond with the input, e.g. if I make the condition <=12 I want it to relay 12 cars to HTML. It works like that perfectly well when the condition is below 10.
Actual result is an error thrown.

答:
Use an array, not an object:

```<code>const cars = [
    {
        "id": 1,
        "name": "Sprinter Boxtruck",
        "make": "Mercedes",
        "price": "£500,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    {
        "id": 2,
        "name": "RS4 Avant",
        "make": "Audi",
        "price": "£300,000",
        "topspeed": "101mph",
        "vip": "false"
    },
    // ...
];
</code>```

and then use a for loop, a for-of loop, forEach, map, or some other array looping construct. Since you're using ES2015+ features, for-of would be the minimal change. You can even use destructuring and perhaps a template literal:

```<code>function dispCars(){
    let output = "";
    for (const [index, {name, make, price}] of cars.entries()) {
      output += `<div class='column'><div style='padding:0px;' class='ui segment'><a href='#'><img class='card-icon' src='../src/media/cars/${index + 1}.jpg'></a><a href='#'><p class='heading'>${make} ${name}</a><span class='price'>${price}</span></p></div></div></div>`;
    }
    catalogue.innerHTML = output;
}
</code>```

but I'd probably go a bit further and use map and join:

```<code>function dispCars(){
    catalogue.innerHTML = cars.map((index, {name, make, price}) =>
      `<div class='column'><div style='padding:0px;' class='ui segment'><a href='#'><img class='card-icon' src='../src/media/cars/${index + 1}.jpg'></a><a href='#'><p class='heading'>${make} ${name}</a><span class='price'>${price}</span></p></div></div></div>`
    ).join("");
}
</code>```

Body:
I have a JSON object with different cars, I am relaying these cars to HTML with a loop, however whenever I try to make the condition (<=) above 10, it throws an error.

This is for a test I am making with a cars site.

Here is my function:

function dispCars(){
    let output = "";
    let i = 1;
    let maxNum = 10;
    while (i <= maxNum){
      const carName = cars["c" + i].name;
      const carMake = cars["c" + i].make;
      const carPrice = cars["c" + i].price;
      console.log(carName);
      output += "

"+ carMake + " " + carName + "" + carPrice + "

";
      i++;
    }

    catalogue.innerHTML = output;
}

Here is a little bit of JSON:

const cars = {
    "c1": {
        "id": 1,
        "name": "Sprinter Boxtruck",
        "make": "Mercedes",
        "price": "£500,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c2": {
        "id": 2,
        "name": "RS4 Avant",
        "make": "Audi",
        "price": "£300,000",
        "topspeed": "101mph",
        "vip": "false"
    },
    "c3": {
        "id": 3,
        "name": "250 GTO",
        "make": "Ferrari",
        "price": "£350,000",
        "topspeed": "92mph",
        "vip": "false"
    },
    "c4": {
        "id": 4,
        "name": "Enzo",
        "make": "Ferrari",
        "price": "£3,500,000",
        "topspeed": "130mph",
        "vip": "false"
    }
    ,
    "c5": {
        "id": 5,
        "name": "F350 Superduty",
        "make": "Ford",
        "price": "£500,000",
        "topspeed": "80mph",
        "vip": "false"
    },
    "c6": {
        "id": 6,
        "name": "Focus SVT",
        "make": "Ford",
        "price": "£250,000",
        "topspeed": "81mph",
        "vip": "false"
    },
    "c7": {
        "id": 7,
        "name": "Mustang GT",
        "make": "Ford",
        "price": "£800,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c8": {
        "id": 8,
        "name": "Raptor SVT",
        "make": "Ford",
        "price": "£500,000",
        "topspeed": "70mph",
        "vip": "false"
    },
    "c9": {
        "id": 9,
        "name": "Transit",
        "make": "Ford",
        "price": "£150,000",
        "topspeed": "87mph",
        "vip": "false"
    }
    ,
    "10": {
        "id": 10,
        "name": "E-Type",
        "make": "Jaguar",
        "price": "£250,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    "c11": {
        "id": 11,
        "name": "F-Type",
        "make": "Mercedes",
        "price": "£600,000",
        "topspeed": "99mph",
        "vip": "false"
    },
    "c12": {
        "id": 12,
        "name": "Gallardo",
        "make": "Lamborghini",
        "price": "£2,500,000",
        "topspeed": "111mph",
        "vip": "false"
    },
...

Here is the error thrown:

index.js:29 Uncaught TypeError: Cannot read property 'name' of undefined
    at dispCars (index.js:29)
    at index.js:40

My expected result is for the output to correspond with the input, e.g. if I make the condition <=12 I want it to relay 12 cars to HTML. It works like that perfectly well when the condition is below 10.
Actual result is an error thrown.

Body:
Use an array, not an object:

const cars = [
    {
        "id": 1,
        "name": "Sprinter Boxtruck",
        "make": "Mercedes",
        "price": "£500,000",
        "topspeed": "87mph",
        "vip": "false"
    },
    {
        "id": 2,
        "name": "RS4 Avant",
        "make": "Audi",
        "price": "£300,000",
        "topspeed": "101mph",
        "vip": "false"
    },
    // ...
];

and then use a for loop, a for-of loop, forEach, map, or some other array looping construct. Since you're using ES2015+ features, for-of would be the minimal change. You can even use destructuring and perhaps a template literal:

function dispCars(){
    let output = "";
    for (const [index, {name, make, price}] of cars.entries()) {
      output += `<div class='column'><div style='padding:0px;' class='ui segment'><a href='#'><img class='card-icon' src='../src/media/cars/${index + 1}.jpg'></a><a href='#'><p class='heading'>${make} ${name}</a><span class='price'>${price}</span></p></div></div></div>`;
    }
    catalogue.innerHTML = output;
}

but I'd probably go a bit further and use map and join:

function dispCars(){
    catalogue.innerHTML = cars.map((index, {name, make, price}) =>
      `<div class='column'><div style='padding:0px;' class='ui segment'><a href='#'><img class='card-icon' src='../src/media/cars/${index + 1}.jpg'></a><a href='#'><p class='heading'>${make} ${name}</a><span class='price'>${price}</span></p></div></div></div>`
    ).join("");
}


问:
Modifying data from graphql queries into react components using gatsbyjs works in gatsby develop but breaks in gatsby build
I'm using prismic as a CMS for a website built with gatsby.
I need to manipulate the data returned by graphql queries before rendering it in the react component.
The website works fine in dev but the build fails because the variables I'm using are not defined at build time.

I've tried using componentDidMount and the hooks equivalent to define my variables only at mount time but it didn't work. I've also tried assigning the variable to the state of the component at mount time but that failed as well. See the code below, where I tried to make a simple example, for a better idea:

```<code>import { graphql } from 'gatsby';

import Layout from "../components/layout"

export const data = graphql`
  query allData {
    allPrismicNews{
      edges {
        node {
          id
        }
      }
    }
  }
`;

class IndexPage extends Component {
    render() {
      return (
        <Layout>
            <p>{this.state.newsId ? this.state.newsId : null}</p>
        </Layout>
      );
    }
  componentDidMount() {
    if (typeof window === 'undefined') {
        return;
    }
    this.setState(() => ({ newsId: this.props.data.allPrismicNews.edges.map(article=>article.node.id).flat() }));
    }
  }
  export default IndexPage;```

For this example, I expect to see the ids of the news output in the template, this works in development but not in production.

What am I doing wrong?
```

答:
What you could do is set an initial state to your newsId so that this.state.newsID is never undefined:

```<code>class IndexPage extends Component {
  state = {
    newsId: null,
  }
  componentDidMount() {
    if (typeof window === "undefined") {
      return
    }
    this.setState({
      newsId: this.props.data.allPrismicNews.edges
        .map(article => article.node.id)
        .flat(),
    })
  }
  render() {
    return (
      <Layout>
        <p>{this.state.newsId ? this.state.newsId : null}</p>
      </Layout>
    )
  }
}
</code>```

Body:
I'm using prismic as a CMS for a website built with gatsby.
I need to manipulate the data returned by graphql queries before rendering it in the react component.
The website works fine in dev but the build fails because the variables I'm using are not defined at build time.

I've tried using componentDidMount and the hooks equivalent to define my variables only at mount time but it didn't work. I've also tried assigning the variable to the state of the component at mount time but that failed as well. See the code below, where I tried to make a simple example, for a better idea:

import { graphql } from 'gatsby';

import Layout from "../components/layout"

export const data = graphql`
  query allData {
    allPrismicNews{
      edges {
        node {
          id
        }
      }
    }
  }
`;

class IndexPage extends Component {
    render() {
      return (
        <Layout>

{this.state.newsId ? this.state.newsId : null}

        </Layout>
      );
    }
  componentDidMount() {
    if (typeof window === 'undefined') {
        return;
    }
    this.setState(() => ({ newsId: this.props.data.allPrismicNews.edges.map(article=>article.node.id).flat() }));
    }
  }
  export default IndexPage;```

For this example, I expect to see the ids of the news output in the template, this works in development but not in production.

What am I doing wrong?

Body:
What you could do is set an initial state to your newsId so that this.state.newsID is never undefined:

class IndexPage extends Component {
  state = {
    newsId: null,
  }
  componentDidMount() {
    if (typeof window === "undefined") {
      return
    }
    this.setState({
      newsId: this.props.data.allPrismicNews.edges
        .map(article => article.node.id)
        .flat(),
    })
  }
  render() {
    return (
      <Layout>
        <p>{this.state.newsId ? this.state.newsId : null}</p>
      </Layout>
    )
  }
}