问:
Arrange data in the table
I've been working to this kind of data in array

```<code>data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]
</code>```

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

```<code><table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>
                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <ng-container *ngFor= "let da of data; ">
            <tr *ngFor= "let s of da.details">
                  <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td>
                     {{s.date}}
                  </td>
                  <td>
                    <input type="time [value]="s.start_time">
                    <strong>/</strong>
                    <input type="time [value]="s.end_time">
                  </td>
            </tr>
            </ng-container>
      </tbody>
</table>
</code>```

can you help on how I should display my data in the table properly.
I'm using angular 2

答:
What about

```<code><table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>

                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <tr *ngFor= "let da of data; ">
                 <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td colspan="2">
                    <tr *ngFor= "let d of da.details; ">
                     <td>{{d.date | date}}</td>
                     <td>
                    <input type="time" [value]="d.start_time"/>
                    <strong>/</strong>
                    <input type="time" [value]="d.end_time"/>
                    </td>
                    </tr>
                  </td>

            </tr>
      </tbody>
</table>
</code>```

Working demo

Title: Arrange data in the table

Body:
I've been working to this kind of data in array

data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

                Employee
                Date
                Time In / Time Out

            <ng-container *ngFor= "let da of data; ">

                     {{da.name}}

                     {{s.date}}

                    <input type="time [value]="s.start_time">
                    /
                    <input type="time [value]="s.end_time">

            </ng-container>

can you help on how I should display my data in the table properly.
I'm using angular 2

Body:
What about

<table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>

                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <tr *ngFor= "let da of data; ">
                 <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td colspan="2">
                    <tr *ngFor= "let d of da.details; ">
                     <td>{{d.date | date}}</td>
                     <td>
                    <input type="time" [value]="d.start_time"/>
                    <strong>/</strong>
                    <input type="time" [value]="d.end_time"/>
                    </td>
                    </tr>
                  </td>

            </tr>
      </tbody>
</table>

Working demo


来源: stackexchange

问:
How do I do an F-test to compare nested linear models in Python?
I want to compare two nested linear models, call them m01, and m02 where m01 is the reduced model and m02 is the full model. I want to do a simple F-test to see if the full model adds significant utility over the reduced model.

This is very simple in R. For example:

```<code>mtcars <- read.csv("https://raw.githubusercontent.com/focods/WonderfulML/master/data/mtcars.csv")
m01 <- lm(mpg ~ am + wt, mtcars)
m02 <- lm(mpg ~ am + am:wt, mtcars)
anova(m01, m02)
</code>```

Gives me the following output:

Which tells me that adding the am: wt interaction term significantly improves the model. Is there a way to do something similar to this in Python/sklearn/statsmodels?

Edit: I looked at this question before posting this one and can not figure out how they are the same.  The other question is doing an F-test on two vectors.  This question is about comparing 2 nested linear models.

I think this is what I need:

http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html#sklearn.feature_selection.f_regression

but am not sure what exactly to pass this function.  If anyone could provide or point to an example, that would be extremely helpful.

答:
I found this book helpful ("An introduction to statistics with python" / Thomas Haslwanter)

Here is the relevant code sample:

```<code>import pandas as pd
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm

df = pd.DataFrame(data, columns=['value', 'treatment'])
model = ols('value ~ C(treatment)', data=df).fit()
anovaResults = anova_lm(model)
print(anovaResults)
</code>```

Look at the book link above for the print result.

Note: anova_lm sometimes used with the parameter 'typ', try its different possible values to see which suitable for you.

ContentLicense: CC BY-SA 3.0

Body:
I want to compare two nested linear models, call them m01, and m02 where m01 is the reduced model and m02 is the full model. I want to do a simple F-test to see if the full model adds significant utility over the reduced model.

This is very simple in R. For example:

mtcars <- read.csv("https://raw.githubusercontent.com/focods/WonderfulML/master/data/mtcars.csv")
m01 <- lm(mpg ~ am + wt, mtcars)
m02 <- lm(mpg ~ am + am:wt, mtcars)
anova(m01, m02)

Gives me the following output:

Which tells me that adding the am: wt interaction term significantly improves the model. Is there a way to do something similar to this in Python/sklearn/statsmodels?

Edit: I looked at this question before posting this one and can not figure out how they are the same.  The other question is doing an F-test on two vectors.  This question is about comparing 2 nested linear models.

I think this is what I need:

http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html#sklearn.feature_selection.f_regression

but am not sure what exactly to pass this function.  If anyone could provide or point to an example, that would be extremely helpful.

Body:
I found this book helpful ("An introduction to statistics with python" / Thomas Haslwanter)

Here is the relevant code sample:

import pandas as pd
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm

df = pd.DataFrame(data, columns=['value', 'treatment'])
model = ols('value ~ C(treatment)', data=df).fit()
anovaResults = anova_lm(model)
print(anovaResults)

Look at the book link above for the print result.

Note: anova_lm sometimes used with the parameter 'typ', try its different possible values to see which suitable for you.


问:
node promises.all() doesnt work as expected
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

Does someone know what I did wrong?

my code is :

```<code>var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
        console.log('---> foo i ' + i);
        resolve('done foo ' + i);

    });
}
</code>```

but the output is

```<code>push promise 0
---> foo i 0
push promise 1
---> foo i 1
push promise 2
---> foo i 2
done
</code>```

where I expect

```<code>push promise 0
push promise 1
push promise 2
---> foo i 0
---> foo i 1
---> foo i 2
done
</code>```

Thank you in advance.

答:
Your console.log('---> foo i ' + i); line is being executed on promise creation as it's outside of the resolve method, and instead inside the executor function that you supplied to the Promise constructor.

This should give you your expected output

```<code>var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
          for (var i = 0; i < data.length; i++) {
            console.log(data[i]);
          }
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
      resolve('--> foo i ' + i);
    });
}
</code>```

Body:
I'm trying to run a list of functions synchronously after a loop using promise.all() but my code doesn't work as expected.

Does someone know what I did wrong?

my code is :

var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
        console.log('---> foo i ' + i);
        resolve('done foo ' + i);

    });
}

but the output is

push promise 0
---> foo i 0
push promise 1
---> foo i 1
push promise 2
---> foo i 2
done

where I expect

push promise 0
push promise 1
push promise 2
---> foo i 0
---> foo i 1
---> foo i 2
done

Thank you in advance.

Body:
Your console.log('---> foo i ' + i); line is being executed on promise creation as it's outside of the resolve method, and instead inside the executor function that you supplied to the Promise constructor.

This should give you your expected output

var Promise = require('promise');
var promises = [];

for (var i = 0; i < 3; i++) {
    console.log('push promise ' + i);
    promises.push(foo(i));
}

Promise.all(promises)
        .then(function (data) {
          for (var i = 0; i < data.length; i++) {
            console.log(data[i]);
          }
            console.log("done");
        });

function foo(i) {
    return new Promise(function (resolve, reject) {
      resolve('--> foo i ' + i);
    });
}


问:
Evaluating a function call constructed from a string
Say I have two functions whose names are contained within a vector. I would like to test if each function works.

My approach, which I readily admit could be wrong, was to loop through the vector then paste () to the function name. But then I realized I have no idea how to evaluate the function call which is current stored as a string. Here is a reprex:

```<code>func1 <- function(){
  message("func1 works")
}

func2 <- function(){
  message("func2 works")
}

fv <- c("func1","func2")

for(i in seq_along(fv)){
  fv_func <- paste0(fv[i],"()")
  print(fv_func)
}
[1] "func1()"
[1] "func2()"
</code>```

So in this context I am asking how to evaluate func1() and func2() though the ultimate goal is to evaluate function whose names are stored in a vector - meaning i'm open to better solution.

答:
Try either of these:</p>

```<code>out <- lapply(fv, do.call, list())

out <- lapply(fv, function(f) match.fun(f)())
</code>```

Body:
Say I have two functions whose names are contained within a vector. I would like to test if each function works.

My approach, which I readily admit could be wrong, was to loop through the vector then paste () to the function name. But then I realized I have no idea how to evaluate the function call which is current stored as a string. Here is a reprex:

func1 <- function(){
  message("func1 works")
}

func2 <- function(){
  message("func2 works")
}

fv <- c("func1","func2")

for(i in seq_along(fv)){
  fv_func <- paste0(fv[i],"()")
  print(fv_func)
}
[1] "func1()"
[1] "func2()"

So in this context I am asking how to evaluate func1() and func2() though the ultimate goal is to evaluate function whose names are stored in a vector - meaning i'm open to better solution.

Body:
Try either of these:

out <- lapply(fv, do.call, list())

out <- lapply(fv, function(f) match.fun(f)())


问:
Register Button is not Working
I'm creating an android application, I want to send the user information to the database by clicking on Register Button and I want it to go to login page.I have created Intent to pass this activity to login activity. When I click register button the user input gets sent to the database but doesn't take you to Login activity. I check on the Logcat and it's not throwing any error. Anyone help me to figure this out, please?

here is my code:

```<code>registerbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("HELLO", "Register Button Clicked");
            //register();

            final String first_name = etfirstname.getText().toString();
            final String last_name = etlastname.getText().toString();
            final String email = etemail.getText().toString();
            final String password = etpass.getText().toString();
            //String Password2 = etpass2.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("HELLO Hello", "Register Button Clicked");
                    try{
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if(success){
                            Intent intent = new Intent(AppRegisterActivity.this, MainActivity.class);
                            //startActivity(intent);
                            AppRegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(AppRegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create().show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };
            RegisterRequest registerRequest = new RegisterRequest(first_name, last_name, email, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(AppRegisterActivity.this);
            queue.add(registerRequest);

        }

    });
</code>```

答: I guess your code going into catch exception. Check it first</p>

Title: Register Button is not Working

Body:
I'm creating an android application, I want to send the user information to the database by clicking on Register Button and I want it to go to login page.I have created Intent to pass this activity to login activity. When I click register button the user input gets sent to the database but doesn't take you to Login activity. I check on the Logcat and it's not throwing any error. Anyone help me to figure this out, please?

here is my code:

registerbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("HELLO", "Register Button Clicked");
            //register();

            final String first_name = etfirstname.getText().toString();
            final String last_name = etlastname.getText().toString();
            final String email = etemail.getText().toString();
            final String password = etpass.getText().toString();
            //String Password2 = etpass2.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("HELLO Hello", "Register Button Clicked");
                    try{
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if(success){
                            Intent intent = new Intent(AppRegisterActivity.this, MainActivity.class);
                            //startActivity(intent);
                            AppRegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(AppRegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create().show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };
            RegisterRequest registerRequest = new RegisterRequest(first_name, last_name, email, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(AppRegisterActivity.this);
            queue.add(registerRequest);

        }

    });


问:
Create a table in SQL where the Composite Primary Key is also a Foreign Key
I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.

: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
    Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number =  4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.```
</div>
</div>
</p>

<p>Tables Thanks in advance for all your help. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>CREATE TABLE LFM_Enroll (
    Student_ID         char(7),
    Section_Number     char(4),
    constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
    constraint FK_LFM_Enroll_Student_ID
      Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
    constraint FK_LFM_Enroll_Section_Number
      Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)

    );</code>```

答:
The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.

[Edit: For defining constraints refer lc.'s post]

Body:
I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.

: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
    Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number =  4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.

Tables Thanks in advance for all your help.

CREATE TABLE LFM_Enroll (
    Student_ID         char(7),
    Section_Number     char(4),
    constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
    constraint FK_LFM_Enroll_Student_ID
      Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
    constraint FK_LFM_Enroll_Section_Number
      Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)

    );


问:
How to detect colored patches in an image using OpenCV?
I am trying to detect if the picture(black and white sketch) is colored or not in the room conditions by a mobile camera.

I have been able to get this result

using following code

```<code>Mat dest = new Mat (sections[i].rows(),sections[i].cols(),CvType.CV_8UC3);
Mat hsv_image = new Mat (sections[i].rows(),sections[i].cols(),CvType.CV_8UC3);

Imgproc.cvtColor (sections[i],hsv_image,Imgproc.COLOR_BGR2HSV);

List <Mat> rgb = new List<Mat> ();
Core.split (hsv_image, rgb);
Imgproc.equalizeHist (rgb [1], rgb [2]);
Core.merge (rgb, sections[i]);
Imgproc.cvtColor (sections[i], dest, Imgproc.COLOR_HSV2BGR);

Core.split (dest, rgb);
</code>```

How can I sucessfully find out if the image is colored or not. The color can be any and it has room conditions. Please help me on this as I am beginner to it.

Thanks

答:
To process the colorful image in HSV color-space is a good direction. And I split the channels and find  the S channel is great. Because S is Saturation(饱和度) of color.

Then threshold the S with thresh of 100, you will get this.

It will be easy to separate the colorful region in the threshed binary image.

As @Mark suggest, we can use adaptive thresh other than the fixed one. So, add THRESH_OTSU in the flags.

Core python code is presented as follow:

```<code>##(1) read into  bgr-space
img = cv2.imread("test.png")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`)
th, threshed = cv2.threshold(s, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY)

##(4) print the thresh, and save the result
print("Thresh : {}".format(th))
cv2.imwrite("result.png", threshed)

## >>> Thresh : 85.0
</code>```

Related answers:

Detect Colored Segment in an image

Edge detection in opencv android

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Body:
I am trying to detect if the picture(black and white sketch) is colored or not in the room conditions by a mobile camera.

I have been able to get this result

using following code

Mat dest = new Mat (sections[i].rows(),sections[i].cols(),CvType.CV_8UC3);
Mat hsv_image = new Mat (sections[i].rows(),sections[i].cols(),CvType.CV_8UC3);

Imgproc.cvtColor (sections[i],hsv_image,Imgproc.COLOR_BGR2HSV);

List <Mat> rgb = new List<Mat> ();
Core.split (hsv_image, rgb);
Imgproc.equalizeHist (rgb [1], rgb [2]);
Core.merge (rgb, sections[i]);
Imgproc.cvtColor (sections[i], dest, Imgproc.COLOR_HSV2BGR);

Core.split (dest, rgb);

How can I sucessfully find out if the image is colored or not. The color can be any and it has room conditions. Please help me on this as I am beginner to it.

Thanks

Body:
To process the colorful image in HSV color-space is a good direction. And I split the channels and find  the S channel is great. Because S is Saturation(饱和度) of color.

Then threshold the S with thresh of 100, you will get this.

It will be easy to separate the colorful region in the threshed binary image.

As @Mark suggest, we can use adaptive thresh other than the fixed one. So, add THRESH_OTSU in the flags.

Core python code is presented as follow:

##(1) read into  bgr-space
img = cv2.imread("test.png")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`)
th, threshed = cv2.threshold(s, 100, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY)

##(4) print the thresh, and save the result
print("Thresh : {}".format(th))
cv2.imwrite("result.png", threshed)

## >>> Thresh : 85.0

Related answers:

Detect Colored Segment in an image

Edge detection in opencv android

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection


问:
read operator from file and perform operation C++
In this problem I have to ask for a filename in which data will be read, and if 'def' is answered use the default file provided, and count the number of lines in the file.
Then read the data file one line at a time and calculate the value of w as follows:
-if w is 'add', calculate x+y
-if w is 'sub', calculate x-y
-if w is 'mult', calculate x*y
-if w is 'div', calculate x/y

and then print the results to the screen on line at a time.

example of data in the file:

mult  4.25  4.56

div  7.64  1.01

div  6.51  2.46

mult  8.90  6.16

mult  7.40  8.53

sub  3.05  7.15

sub  9.51  6.16

sub  5.79  1.60

add  5.30  8.87

sub  8.09  1.65

And my code: I have the first 3 parts work but the while loop for performing the operations isn't working. Where am I going wrong? Thanks!

```<code>#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(){

    ifstream input;
    string filename;
    cout<<"Enter the file name. Enter 'def' to use default file: ";
    cin>>filename;

    if(filename == "def"){
        input.open("M2-P2-data2Read.dat");
    }
    else{
        input.open(filename.c_str());
    }

    int number_of_lines = 0;
    string line;

    while (getline(input, line))
        ++number_of_lines;
    cout << "Number of lines in file: " << number_of_lines;

    string w;
    double x, y;

    input >> w;

    while(input) {
    if(w == "add")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x+y << endl;
    if(w == "sub")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x-y << endl;
    if(w == "mult")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x*y << endl;
    if(w == "div")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x/y << endl;
    input >> w;

   }

}
</code>```

答:
Even though you have expressed your intent to create a block of code after the if statements, the code is really not blocked. The lines

```<code>if(w == "add")
    double x, y;
    input >> x >> y;
    cout << "Solution: " << x+y << endl;
</code>```

are equivalent to

```<code>if(w == "add")
{
    double x, y; // A declaration that does not have any impact on
                 // the rest of the lines.
}
input >> x >> y; // These variables are the x and y that were declared
                 // before the while statement.
cout << "Solution: " << x+y << endl;
</code>```

Now, if you transform the next if statement, you get

```<code>if(w == "sub")
{
    double x, y;
 }
 input >> x >> y;
 cout << "Solution: " << x-y << endl;
</code>```

Your code attempts to read into x and y the second time without reading the operation, which fails since there is no number to read. After that, all read operations fail.

You need to block the statements after the if.

```<code>if(w == "add")
{
    input >> x >> y;
    cout << "Solution: " << x+y << endl;
}
</code>```

You can simplify your code a bit by moving the lines that read x and y outside the if statements.

```<code>input >> x >> y;
if(w == "add")
{
    cout << "Solution: " << x+y << endl;
}

else if(w == "sub")  // Use else if instead of just if.
{
    cout << "Solution: " << x-y << endl;
}
</code>```

etc.

Body:
In this problem I have to ask for a filename in which data will be read, and if 'def' is answered use the default file provided, and count the number of lines in the file.
Then read the data file one line at a time and calculate the value of w as follows:
-if w is 'add', calculate x+y
-if w is 'sub', calculate x-y
-if w is 'mult', calculate x*y
-if w is 'div', calculate x/y

and then print the results to the screen on line at a time.

example of data in the file:

mult  4.25  4.56

div  7.64  1.01

div  6.51  2.46

mult  8.90  6.16

mult  7.40  8.53

sub  3.05  7.15

sub  9.51  6.16

sub  5.79  1.60

add  5.30  8.87

sub  8.09  1.65

And my code: I have the first 3 parts work but the while loop for performing the operations isn't working. Where am I going wrong? Thanks!

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(){

    ifstream input;
    string filename;
    cout<<"Enter the file name. Enter 'def' to use default file: ";
    cin>>filename;

    if(filename == "def"){
        input.open("M2-P2-data2Read.dat");
    }
    else{
        input.open(filename.c_str());
    }

    int number_of_lines = 0;
    string line;

    while (getline(input, line))
        ++number_of_lines;
    cout << "Number of lines in file: " << number_of_lines;

    string w;
    double x, y;

    input >> w;

    while(input) {
    if(w == "add")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x+y << endl;
    if(w == "sub")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x-y << endl;
    if(w == "mult")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x*y << endl;
    if(w == "div")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x/y << endl;
    input >> w;

   }

}

Body:
Even though you have expressed your intent to create a block of code after the if statements, the code is really not blocked. The lines

if(w == "add")
    double x, y;
    input >> x >> y;
    cout << "Solution: " << x+y << endl;

are equivalent to

if(w == "add")
{
    double x, y; // A declaration that does not have any impact on
                 // the rest of the lines.
}
input >> x >> y; // These variables are the x and y that were declared
                 // before the while statement.
cout << "Solution: " << x+y << endl;

Now, if you transform the next if statement, you get

if(w == "sub")
{
    double x, y;
 }
 input >> x >> y;
 cout << "Solution: " << x-y << endl;

Your code attempts to read into x and y the second time without reading the operation, which fails since there is no number to read. After that, all read operations fail.

You need to block the statements after the if.

if(w == "add")
{
    input >> x >> y;
    cout << "Solution: " << x+y << endl;
}

You can simplify your code a bit by moving the lines that read x and y outside the if statements.

input >> x >> y;
if(w == "add")
{
    cout << "Solution: " << x+y << endl;
}

else if(w == "sub")  // Use else if instead of just if.
{
    cout << "Solution: " << x-y << endl;
}

etc.


问:
Java: variable from parent class in child one isn't initialized and holds null
```<code>Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...
</code>```

Child class:

```<code>    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }
</code>```

The problem is that fileName is passed as null to frm in this line:

```<code>private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
</code>```

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

答:
Assuming that your "parent class" is the SomeClass class, overwrite the default constructor there:</p>

```<code>public Someclass(String fileName) {
   this.fileName = fileName;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...

Child class:

    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }

The problem is that fileName is passed as null to frm in this line:

private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

Body:
Assuming that your "parent class" is the SomeClass class, overwrite the default constructor there:

public Someclass(String fileName) {
   this.fileName = fileName;
}


问:
3D pointer seg error
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

```<code>int ***grid;
    grid=new int **[number];
</code>```

then I want to assign the 2D arrays to the 3D construct

```<code>for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);
</code>```

with

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}
</code>```

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

```<code>printf("%d",grid[1][1][1]);
</code>```

What is my mistake?

Best,
  Hannes

答:
Do you expect memset(grid,0x0,sizeof(grid)); not to zero the pointer values you've just assigned to grid[0] through to grid[599]? If so, you should test that theory by inspecting the pointer values of grid[0] through to grid[599] before and after that call to memset, to find out what memset does to true (more on that later) arrays.

Your program is dereferencing a null pointer which results directly from that line of code. Typically, a crash can be expected when you attempt to dereference a null pointer, because null pointers don't reference any objects. This explains your observation of a crash, and your observation of the crash disappearing when you comment out that call to memset. You can't expect good things to happen if you try to use the value of something which isn't an object, such as grid[1][... where grid[1] is a pointer consisting entirely of zero bits.

The term 3D array doesn't mean what you think it means, by the way. Arrays in C and C++ are considered to be a single allocation, where-as what your code is producing seems to be multiple allocations, associated in a hierarchical form; you've allocated a tree as opposed to an array, and memset isn't appropriate to zero a tree. Perhaps your experiments could be better guided from this point on by a book regarding algorithms, such as Algorithms in C, parts 1-4 by Robert Sedgewick.

For the meantime, in C, the following will get you a pointer to a 2D array which you can mostly use as though it's a 3D array:

```<code>void *make_grid(size_t x, size_t y, size_t z) {
    int (*grid)[y][z] = malloc(x * sizeof *grid);
    /* XXX: use `grid` as though it's a 3D array here.
     * i.e. grid[0][1][2] = 42;
     */
    return grid;
}
</code>```

Assuming make_grid returns something non-null, you can use a single call to memset to zero the entirety of the array pointed to by that function because there's a single call to malloc matching that a single call to memset... Otherwise, if you want to zero a tree, you'll probably want to call memset n times for n items.

In C++, I don't think you'll find many who discourage the use of std::vector in place of arrays. You might want to at least consider that option, as well as the other options you have (such as trees; it seems like you want to use a tree, which is fine because trees have perfectly appropriate usecases that arrays aren't valid for, and you haven't given us enough context to tell which would be most appropriate for you).

Title: 3D pointer seg error

Body:
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

int ***grid;
    grid=new int **[number];

then I want to assign the 2D arrays to the 3D construct

for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);

with

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

printf("%d",grid[1][1][1]);

What is my mistake?

Best,
  Hannes

Body:
Do you expect memset(grid,0x0,sizeof(grid)); not to zero the pointer values you've just assigned to grid[0] through to grid[599]? If so, you should test that theory by inspecting the pointer values of grid[0] through to grid[599] before and after that call to memset, to find out what memset does to true (more on that later) arrays.

Your program is dereferencing a null pointer which results directly from that line of code. Typically, a crash can be expected when you attempt to dereference a null pointer, because null pointers don't reference any objects. This explains your observation of a crash, and your observation of the crash disappearing when you comment out that call to memset. You can't expect good things to happen if you try to use the value of something which isn't an object, such as grid[1][... where grid[1] is a pointer consisting entirely of zero bits.

The term 3D array doesn't mean what you think it means, by the way. Arrays in C and C++ are considered to be a single allocation, where-as what your code is producing seems to be multiple allocations, associated in a hierarchical form; you've allocated a tree as opposed to an array, and memset isn't appropriate to zero a tree. Perhaps your experiments could be better guided from this point on by a book regarding algorithms, such as Algorithms in C, parts 1-4 by Robert Sedgewick.

For the meantime, in C, the following will get you a pointer to a 2D array which you can mostly use as though it's a 3D array:

void *make_grid(size_t x, size_t y, size_t z) {
    int (*grid)[y][z] = malloc(x * sizeof *grid);
    /* XXX: use `grid` as though it's a 3D array here.
     * i.e. grid[0][1][2] = 42;
     */
    return grid;
}

Assuming make_grid returns something non-null, you can use a single call to memset to zero the entirety of the array pointed to by that function because there's a single call to malloc matching that a single call to memset... Otherwise, if you want to zero a tree, you'll probably want to call memset n times for n items.

In C++, I don't think you'll find many who discourage the use of std::vector in place of arrays. You might want to at least consider that option, as well as the other options you have (such as trees; it seems like you want to use a tree, which is fine because trees have perfectly appropriate usecases that arrays aren't valid for, and you haven't given us enough context to tell which would be most appropriate for you).


问:
remove characters before and after character in java
I need to delete all characters before and after a specific character using java programming
for example:

input: ab*cd output:ad

input: ab**cd output:ad

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

public class Starstring {
    public static void main(String[] args) {
        String str1;
        String res="";
        int n,i=0;

        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string");
        str1=sc.next();
        res=str1;
        StringBuffer a = new StringBuffer(str1);
        n=str1.length()-1;
        for(i=0;i<n;i++)
        {
            if(str1.charAt(i)=='*')
            {
                res=a.delete(i-1, i+2).toString();
            }
        }
        System.out.println("The final string is"+res);
    }

}
</code>```

I am getting expected output for case 1 but case 2 wrong output with ac as output.I don't know where I am going wrong.Someone please help me.Thanks in advance:)

答:
Try this:</p>

```<code>public static void main(String[] args) {
    System.out.println("Enter the string");
    Scanner sc = new Scanner(System.in);
    String str1 = sc.nextLine();
    String[] separated = str1.split(".\\*+.");
    String result = "";
    for(String str : separated) {
        result += str;
    }
    System.out.println(result);
}
</code>```

Body:
I need to delete all characters before and after a specific character using java programming
for example:

input: ab*cd output:ad

input: ab**cd output:ad

import java.util.Scanner;

public class Starstring {
    public static void main(String[] args) {
        String str1;
        String res="";
        int n,i=0;

        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string");
        str1=sc.next();
        res=str1;
        StringBuffer a = new StringBuffer(str1);
        n=str1.length()-1;
        for(i=0;i<n;i++)
        {
            if(str1.charAt(i)=='*')
            {
                res=a.delete(i-1, i+2).toString();
            }
        }
        System.out.println("The final string is"+res);
    }

}

I am getting expected output for case 1 but case 2 wrong output with ac as output.I don't know where I am going wrong.Someone please help me.Thanks in advance:)

Body:
Try this:

public static void main(String[] args) {
    System.out.println("Enter the string");
    Scanner sc = new Scanner(System.in);
    String str1 = sc.nextLine();
    String[] separated = str1.split(".\\*+.");
    String result = "";
    for(String str : separated) {
        result += str;
    }
    System.out.println(result);
}


问:
how to safely reallocate memory in C++ for char *array (it's for CustomString class)
I think my teacher was mostly telling us what are  the wrong ways to allocate memory ...

But I wasn't totally sure what is the correct way to safely reallocate more memory to a pointer. Purpose of reallocating memory to my mind is  because the old memory allocation is not large enough (e.g. when doing an prefix increment operator overload such as append character 'X', presumably you would need large enough new allocation to accomodate the endresult?)

QUESTIONS:

So I was left rather puzzled by what exactly is the correct way to reallocate memory to a char*c_string, because the old memoryallocation is not large enough anymore, and we need the larger memoryallocation instead (this happens with prefix increment operator overload)?

does my existing code have memoryleaks in the prefix increment operator overload?

how can I find memoryleaks when coding C++ in Visual Studio 2017 on Windows?

Basic information about my project:
The goal was to create your own CustomString class, and have char*pointer as a private instance variable of the CustomString class.

I have created my own CustomString class already, and I was supposed to make some operator overloads, such as addition operator, prefix increment operator.

The main purpose with addition operator is of course naturally string concatenation. And with the prefix increment operator, you just add a character 'X' at the end.

I can post here below my definitions for my already existing code.

CustomString.h

```<code>#pragma once
#include <iostream>
#include <string.h>
using namespace std;

class CustomString
{
    friend ostream &operator<<(ostream &out, const CustomString &reference);//OUTPUT OPERATOR OVERLOADED as friend function

public:
    static const int MaxSize = 10;//classwide constant
    static int getNumberOfCustomStrings();

    CustomString(const char *namepointer="");// constructor
    //CustomString(char * pointer);//constructor w/parameters
    ~CustomString();//destructor
    CustomString(const CustomString &stringref);    //copy constructor w/dynamic datamember
    operator const char*() const; // IMPLICIT CONVERSION operator overloaded

     CustomString operator+( const CustomString &addedpart) const;  // PLUS OPERATOR OVERLOADED implemented as string concatenate
    const CustomString& operator=(const CustomString &ref); //ASSIGNMENT OPERATOR OVERLOADED works for dynamic strings as well
    const CustomString &operator++();//PREINCREMENT OPERATOR OVERLOADED
    CustomString operator++(int);//POSTINCREMENT OPERATOR OVERLOADEd
    char& operator[](int i) const;// INDEXING OPERATOR OVERLOADED

private:
    char * c_string;
    void list();
    static int numberOfCustomStrings;
};
</code>```

From CustomString.cpp, here is the prefix increment piece of code

```<code>const CustomString & CustomString::operator++()// PREFIX INCREMENT OVERLOADED, adds an 'X' character into the dynamic instance variable(char*c_string)
{

    if (  strlen(c_string) == (MaxSize-1)   ) {
        cout << "error cannot increment any further" << endl;
        return *this;
    }
    else {
        int oldlength = strlen(c_string) +1;
        char*newdata;
        newdata = new char[ oldlength+1  ]; //it has to be one char bigger allocation bevause one "X" soon will be added
        strcpy_s(newdata, oldlength+1, c_string);//put the old data into new allocation as the baseword
        newdata[oldlength-1] = 'X';
        newdata[oldlength] = '\0';
        delete c_string;//free the old memory
        c_string = newdata; //give  the new allocation to the dynamic instance variable
        return *this;

    }

}
</code>```

I believe that I already did destructor, constructor and copy-constructor correctly, but I can also give their code

Constructor from CustomString.cpp

```<code>CustomString::CustomString(const char *pointer)// constructor
{
    if(   (strlen(pointer)+1) <=MaxSize   ){
    c_string = new char[strlen(pointer) + 1];
    strcpy_s(c_string, (strlen(pointer) + 1), pointer);
    numberOfCustomStrings++;
    }
    else {
        c_string = new char[MaxSize];
        //printf("char at last index was == %c \n", c_string[MaxSize-1]);
        int j = 0;
        for (j = 0; j <= (MaxSize-2); j++) {
            c_string[j] = pointer[j];
        }
        //printf("the last truechar was %c \n",pointer[MaxSize-2]);
        c_string[MaxSize - 1] = '\0';
        //printf("the last char was %c\n", pointer[MaxSize-1]);
        numberOfCustomStrings++;
    }

}
</code>```

Here is copy-constructor from CustomString.cpp

```<code>CustomString::CustomString(const CustomString &ref)     //copy-constructor w/dynamic data member.
{
    c_string = new char[strlen(ref.c_string) + 1];
    strcpy_s(c_string, strlen(ref.c_string) + 1, ref.c_string);
    numberOfCustomStrings++;
}
</code>```

Here is destructor from CustomString.cpp

```<code>CustomString::~CustomString()   // destructor
{
    delete c_string;
    cout << "destructor called!" << endl;
    numberOfCustomStrings--;
}
</code>```

答:
Code:

```<code>char *a = new char;
delete a;

char *array = new char[100];
delete [] array;
</code>```

You can use visual leak detector to Locate a line

Body:
I think my teacher was mostly telling us what are  the wrong ways to allocate memory ...

But I wasn't totally sure what is the correct way to safely reallocate more memory to a pointer. Purpose of reallocating memory to my mind is  because the old memory allocation is not large enough (e.g. when doing an prefix increment operator overload such as append character 'X', presumably you would need large enough new allocation to accomodate the endresult?)

QUESTIONS:

So I was left rather puzzled by what exactly is the correct way to reallocate memory to a char*c_string, because the old memoryallocation is not large enough anymore, and we need the larger memoryallocation instead (this happens with prefix increment operator overload)?

does my existing code have memoryleaks in the prefix increment operator overload?

how can I find memoryleaks when coding C++ in Visual Studio 2017 on Windows?

Basic information about my project:
The goal was to create your own CustomString class, and have char*pointer as a private instance variable of the CustomString class.

I have created my own CustomString class already, and I was supposed to make some operator overloads, such as addition operator, prefix increment operator.

The main purpose with addition operator is of course naturally string concatenation. And with the prefix increment operator, you just add a character 'X' at the end.

I can post here below my definitions for my already existing code.

CustomString.h

#pragma once
#include <iostream>
#include <string.h>
using namespace std;

class CustomString
{
    friend ostream &operator<<(ostream &out, const CustomString &reference);//OUTPUT OPERATOR OVERLOADED as friend function

public:
    static const int MaxSize = 10;//classwide constant
    static int getNumberOfCustomStrings();

    CustomString(const char *namepointer="");// constructor
    //CustomString(char * pointer);//constructor w/parameters
    ~CustomString();//destructor
    CustomString(const CustomString &stringref);    //copy constructor w/dynamic datamember
    operator const char*() const; // IMPLICIT CONVERSION operator overloaded

     CustomString operator+( const CustomString &addedpart) const;  // PLUS OPERATOR OVERLOADED implemented as string concatenate
    const CustomString& operator=(const CustomString &ref); //ASSIGNMENT OPERATOR OVERLOADED works for dynamic strings as well
    const CustomString &operator++();//PREINCREMENT OPERATOR OVERLOADED
    CustomString operator++(int);//POSTINCREMENT OPERATOR OVERLOADEd
    char& operator[](int i) const;// INDEXING OPERATOR OVERLOADED

private:
    char * c_string;
    void list();
    static int numberOfCustomStrings;
};

From CustomString.cpp, here is the prefix increment piece of code

const CustomString & CustomString::operator++()// PREFIX INCREMENT OVERLOADED, adds an 'X' character into the dynamic instance variable(char*c_string)
{

    if (  strlen(c_string) == (MaxSize-1)   ) {
        cout << "error cannot increment any further" << endl;
        return *this;
    }
    else {
        int oldlength = strlen(c_string) +1;
        char*newdata;
        newdata = new char[ oldlength+1  ]; //it has to be one char bigger allocation bevause one "X" soon will be added
        strcpy_s(newdata, oldlength+1, c_string);//put the old data into new allocation as the baseword
        newdata[oldlength-1] = 'X';
        newdata[oldlength] = '\0';
        delete c_string;//free the old memory
        c_string = newdata; //give  the new allocation to the dynamic instance variable
        return *this;

    }

}

I believe that I already did destructor, constructor and copy-constructor correctly, but I can also give their code

Constructor from CustomString.cpp

CustomString::CustomString(const char *pointer)// constructor
{
    if(   (strlen(pointer)+1) <=MaxSize   ){
    c_string = new char[strlen(pointer) + 1];
    strcpy_s(c_string, (strlen(pointer) + 1), pointer);
    numberOfCustomStrings++;
    }
    else {
        c_string = new char[MaxSize];
        //printf("char at last index was == %c \n", c_string[MaxSize-1]);
        int j = 0;
        for (j = 0; j <= (MaxSize-2); j++) {
            c_string[j] = pointer[j];
        }
        //printf("the last truechar was %c \n",pointer[MaxSize-2]);
        c_string[MaxSize - 1] = '\0';
        //printf("the last char was %c\n", pointer[MaxSize-1]);
        numberOfCustomStrings++;
    }

}

Here is copy-constructor from CustomString.cpp

CustomString::CustomString(const CustomString &ref)     //copy-constructor w/dynamic data member.
{
    c_string = new char[strlen(ref.c_string) + 1];
    strcpy_s(c_string, strlen(ref.c_string) + 1, ref.c_string);
    numberOfCustomStrings++;
}

Here is destructor from CustomString.cpp

CustomString::~CustomString()   // destructor
{
    delete c_string;
    cout << "destructor called!" << endl;
    numberOfCustomStrings--;
}

Body:
Code:

char *a = new char;
delete a;

char *array = new char[100];
delete [] array;

You can use visual leak detector to Locate a line


问:
Laravel Scope and Search results
I'm working with laravel 5.5 and I made scope for my products in Product.php model:

```<code>public function scopeApproved($query)
{
    return $query->where('publish', 1);
}
</code>```

Taken from laravel website.

Then I have this code below to show my search results.

```<code>public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}
</code>```

The problem with that is even if my product publish column is set to 0 still will pop in search results.

same goes for products list, still shows in website.

How can I fix that?

答:
Try:</p>

```<code>public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}
</code>```

Title: Laravel Scope and Search results

Body:
I'm working with laravel 5.5 and I made scope for my products in Product.php model:

public function scopeApproved($query)
{
    return $query->where('publish', 1);
}

Taken from laravel website.

Then I have this code below to show my search results.

public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}

The problem with that is even if my product publish column is set to 0 still will pop in search results.

same goes for products list, still shows in website.

How can I fix that?

Body:
Try:

public function search()
{
    $search = request('search');
    $searchType = request('searchType');

    if (strcmp($searchType, "posts") == 0) {
        $posts = Post::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    } elseif (strcmp($searchType, "products") == 0) {
        $products = Product::approved()->where('title', 'like', "%{$search}%")
            ->orWhere('description', 'like', "%{$search}%")
            ->get();
    }

    return view('frontend.search', compact('posts', 'products'));
}


问:
How to filter the array by multiple element and find the sum in Swift?
I'm trying to filter my array by some element. I want recordtype is contain "Income" and createdAt equal to a date but $0.createdAt! is an date type so I can't use .contain(""), what can I use?

```<code>recordFilter = record.filter { $0.recordtype!.contains("Income") /*|| $0.createdAt! = recordItem.createdAt!*/}
</code>```

recordFilter output: (this result is not filter by createdAt yet)

```<code>[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), <Record: 0x600000099ff0> (entity: Record; id: 0xd000000000400000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p16> ; data: {
    accountbook = "first book";
    amount = "\U00a56.58";
    assest = nil;
    category = "\U5de5\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 16;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
})]
</code>```

After that, I trying to get all the amount string in array and sum it. But I found that it's all separate string when I use this code, how can I group it in array and sum it or have any other way to do it?

```<code>let sum = recordFilter.map({Int($0.amount!.dropFirst())})
//[nil, nil]

for i in 0..<recordFilter.count{
    if recordFilter[i].amount != nil{

        let amountList = recordFilter[i].amount!.dropFirst()
        print(amountList) // I found that it's separate string.
        //9.99
        //11.22
        // ...

        //let intArray = amountList.map { Int($0)!}
        //let sum = amountList.reduce(0, +)
        //print(sum)

    }
}
</code>```

答:
Well, If you want to fulfil two cases (recordtype == Income && createdAt == Your Date) so why you are not filtering using the &&?

```<code>recordFilter = record.filter { return $0.recordtype!.contains("Income") && $0.createdAt! == recordItem.createdAt!}
</code>```

Please give a try and let me know if I am missing something?

If you want to sum here you go:

```<code>recordFilter.map{($0["amount"] as! Float)}.reduce(0, +)
</code>```

Body:
I'm trying to filter my array by some element. I want recordtype is contain "Income" and createdAt equal to a date but $0.createdAt! is an date type so I can't use .contain(""), what can I use?

recordFilter = record.filter { $0.recordtype!.contains("Income") /*|| $0.createdAt! = recordItem.createdAt!*/}

recordFilter output: (this result is not filter by createdAt yet)

[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), <Record: 0x600000099ff0> (entity: Record; id: 0xd000000000400000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p16> ; data: {
    accountbook = "first book";
    amount = "\U00a56.58";
    assest = nil;
    category = "\U5de5\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 16;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
})]

After that, I trying to get all the amount string in array and sum it. But I found that it's all separate string when I use this code, how can I group it in array and sum it or have any other way to do it?

let sum = recordFilter.map({Int($0.amount!.dropFirst())})
//[nil, nil]

for i in 0..<recordFilter.count{
    if recordFilter[i].amount != nil{

        let amountList = recordFilter[i].amount!.dropFirst()
        print(amountList) // I found that it's separate string.
        //9.99
        //11.22
        // ...

        //let intArray = amountList.map { Int($0)!}
        //let sum = amountList.reduce(0, +)
        //print(sum)

    }
}

Body:
Well, If you want to fulfil two cases (recordtype == Income && createdAt == Your Date) so why you are not filtering using the &&?

recordFilter = record.filter { return $0.recordtype!.contains("Income") && $0.createdAt! == recordItem.createdAt!}

Please give a try and let me know if I am missing something?

If you want to sum here you go:

recordFilter.map{($0["amount"] as! Float)}.reduce(0, +)


问:
In TabBarController + NavigationController mix env, how to reset nav when tab changes?
I am building an app, which has TabBarController, and each tab view has navigation view controller. When user click tab, I'd like the relavent navigation view controller to "reset" to the root panel.

In my code, I uses the following way to initialize the tab and navigation controller.

```<code>viewController1 = [[MyFirstController alloc] init];
UINavigationController *tableNavController = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];

viewController2 = [[MySecondController alloc] init];
UINavigationController *table2NavController = [[[UINavigationController alloc] initWithRootViewController:viewController2] autorelease];

tabBarController.viewControllers = [NSArray arrayWithObjects:tableNavController, table2NavController, nil];

    Then appears that all the tab and navigation controller is working automatically. I am not sure where to cut in to let navigation controller view to reset when it is selected.
</code>```

Thanks.

答:
The navigation controller is sent a viewWillAppear message by the system, so you can implement the method to do the resetting..
Another option would be to use the tab bar controller's selectedViewController method to retrieve the selected navigation controller..
Hope that helps.. </p>

OwnerDisplayName: BlueDolphin

Body:
I am building an app, which has TabBarController, and each tab view has navigation view controller. When user click tab, I'd like the relavent navigation view controller to "reset" to the root panel.

In my code, I uses the following way to initialize the tab and navigation controller.

viewController1 = [[MyFirstController alloc] init];
UINavigationController *tableNavController = [[[UINavigationController alloc] initWithRootViewController:viewController1] autorelease];

viewController2 = [[MySecondController alloc] init];
UINavigationController *table2NavController = [[[UINavigationController alloc] initWithRootViewController:viewController2] autorelease];

tabBarController.viewControllers = [NSArray arrayWithObjects:tableNavController, table2NavController, nil];

    Then appears that all the tab and navigation controller is working automatically. I am not sure where to cut in to let navigation controller view to reset when it is selected.

Thanks.

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: iphonenoob


问:
How to change line colors succesively in a graph using matplotlib
so I have this lines being plotted

```<code>x=0.2
r_1=3
n=1000

for i in range (n):
        x_n1=r_1*x*(1 -x)
        plt.plot([x, x], [x, x_n1], color='green')
        plt.plot([x, x_n1], [x_n1, x_n1], color='green')
        x=x_n1
plt.show()
</code>```

they're all green. How can I make each of them change its color (as in the rainbow order of colors) in each iteration? What I want to achieve is something like this cobweb map

答:
color accepts multiple types of inputs, such as a tuple of RGB values. However, the best method to create a rainbow would be with HSV. Fortunately, matplotlib.colors has a hsv_to_rgb function:

```<code>import matplotlib.colors as colors
color = .5 #Value between 0 and 1, 0 and 1 being red
print(colors.hsv_to_rgb((color, 1, 1)) #[ 0.  1.  1.]
</code>```

Now, we just want to shift through all values as we iterate from 0 to n-1:

```<code>for i in range (n):
    color=colors.hsv_to_rgb((i/n, 1, 1))
    x_n1=r_1*x*(1 -x)
    plt.plot([x, x], [x, x_n1], color=color)
    plt.plot([x, x_n1], [x_n1, x_n1], color=color)
    x=x_n1
plt.show()
</code>```

You'll notice that almost all of lines are reddish. This is due to most of the prevalent lines being the first 50, which are all very close to red. You can adapt this as you see fit; one such option would be to have color=colors.hsv_to_rgb(((i/n)**(1/2), 1, 1)).

Body:
so I have this lines being plotted

x=0.2
r_1=3
n=1000

for i in range (n):
        x_n1=r_1*x*(1 -x)
        plt.plot([x, x], [x, x_n1], color='green')
        plt.plot([x, x_n1], [x_n1, x_n1], color='green')
        x=x_n1
plt.show()

they're all green. How can I make each of them change its color (as in the rainbow order of colors) in each iteration? What I want to achieve is something like this cobweb map

Body:
color accepts multiple types of inputs, such as a tuple of RGB values. However, the best method to create a rainbow would be with HSV. Fortunately, matplotlib.colors has a hsv_to_rgb function:

import matplotlib.colors as colors
color = .5 #Value between 0 and 1, 0 and 1 being red
print(colors.hsv_to_rgb((color, 1, 1)) #[ 0.  1.  1.]

Now, we just want to shift through all values as we iterate from 0 to n-1:

for i in range (n):
    color=colors.hsv_to_rgb((i/n, 1, 1))
    x_n1=r_1*x*(1 -x)
    plt.plot([x, x], [x, x_n1], color=color)
    plt.plot([x, x_n1], [x_n1, x_n1], color=color)
    x=x_n1
plt.show()

You'll notice that almost all of lines are reddish. This is due to most of the prevalent lines being the first 50, which are all very close to red. You can adapt this as you see fit; one such option would be to have color=colors.hsv_to_rgb(((i/n)**(1/2), 1, 1)).


问:
Python: Results printing in the wrong order
I am currently having a problem with my code. I have my results print first and then my words that are to print before that appear at the end.

```<code> #   program that converst C to F in a table
def main():
    print('The given table converst Celsius to Farenheit.');
    print('Celsius  \t  Farenheit');

for C in range(1,21):
    F=(9/5)*C+32;
    print( C,"  {0:.1f}".format(F));

main()
</code>```

Giving me the results

```<code>1   33.8
2   35.6
3   37.4
4   39.2
5   41.0
6   42.8
7   44.6
8   46.4
9   48.2
10   50.0
11   51.8
12   53.6
13   55.4
14   57.2
15   59.0
16   60.8
17   62.6
18   64.4
19   66.2
20   68.0

The given table convert Celsius to Fahrenheit.

Celsius       Fahrenheit
</code>```

If you could help me solve this Problem that would be very much appreciated.

答:
As for loop is outside main definition first for loop is getting executed and then the main(). After moving for loop inside main definition it should work properly. </p>

```<code>def main():
    print('The given table converst Celsius to Farenheit.');
    print('Celsius  \t  Farenheit');

    for C in range(1,21):
        F=(9/5)*C+32;
        print( C,"  {0:.1f}".format(F));

main()
</code>```

Body:
I am currently having a problem with my code. I have my results print first and then my words that are to print before that appear at the end.

 #   program that converst C to F in a table
def main():
    print('The given table converst Celsius to Farenheit.');
    print('Celsius  \t  Farenheit');

for C in range(1,21):
    F=(9/5)*C+32;
    print( C,"  {0:.1f}".format(F));

main()

Giving me the results

1   33.8
2   35.6
3   37.4
4   39.2
5   41.0
6   42.8
7   44.6
8   46.4
9   48.2
10   50.0
11   51.8
12   53.6
13   55.4
14   57.2
15   59.0
16   60.8
17   62.6
18   64.4
19   66.2
20   68.0

The given table convert Celsius to Fahrenheit.

Celsius       Fahrenheit

If you could help me solve this Problem that would be very much appreciated.

Body:
As for loop is outside main definition first for loop is getting executed and then the main(). After moving for loop inside main definition it should work properly.

def main():
    print('The given table converst Celsius to Farenheit.');
    print('Celsius  \t  Farenheit');

    for C in range(1,21):
        F=(9/5)*C+32;
        print( C,"  {0:.1f}".format(F));

main()


问:
Arrange data in the table
I've been working to this kind of data in array

```<code>data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]
</code>```

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

```<code><table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>
                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <ng-container *ngFor= "let da of data; ">
            <tr *ngFor= "let s of da.details">
                  <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td>
                     {{s.date}}
                  </td>
                  <td>
                    <input type="time [value]="s.start_time">
                    <strong>/</strong>
                    <input type="time [value]="s.end_time">
                  </td>
            </tr>
            </ng-container>
      </tbody>
</table>
</code>```

can you help on how I should display my data in the table properly.
I'm using angular 2

答:
try this

use parseDate custom function in your component

```<code>parseDate(dateString: string): Date {
    if (dateString) {
        return new Date(dateString);
    } else {
        return null;
    }
}
</code>```

and call the function where you want convert and the format by this way

```<code>{{parseDate(s.date) | date: 'MMM dd, yyyy'}}
</code>```

note: Also consider @Saurabh Agrawal  answer for your table format.

DEMO Result :

Title: Arrange data in the table

Body:
I've been working to this kind of data in array

data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

                Employee
                Date
                Time In / Time Out

            <ng-container *ngFor= "let da of data; ">

                     {{da.name}}

                     {{s.date}}

                    <input type="time [value]="s.start_time">
                    /
                    <input type="time [value]="s.end_time">

            </ng-container>

can you help on how I should display my data in the table properly.
I'm using angular 2

Body:
try this

use parseDate custom function in your component

parseDate(dateString: string): Date {
    if (dateString) {
        return new Date(dateString);
    } else {
        return null;
    }
}

and call the function where you want convert and the format by this way

{{parseDate(s.date) | date: 'MMM dd, yyyy'}}

note: Also consider @Saurabh Agrawal  answer for your table format.

DEMO Result :


问:
error: could not build Objective-C module 'Foundation'
I encounter this 2 errors while archiving my project. I don't know what happen on it. Need help to solve this issues.

Foundation framework already added into the project

答:
First try by full clean with,

```<code>(Command-Option-Shift-K)
</code>```

then if it will not done then

Once try like below,

Select your project name(top most row in left side panel) from navigator - > go to build settings -> Apple LLVM 8.1 - Languages - Modules -> set Enable modules(C and Objective-C) to NO.

Here 8.1 is your xcode version number if you are using xcode 9 then it will be Apple LLVM 9.0 instead of Apple LLVM 8.1.

Body:
First try by full clean with,

(Command-Option-Shift-K)

then if it will not done then

Once try like below,

Select your project name(top most row in left side panel) from navigator - > go to build settings -> Apple LLVM 8.1 - Languages - Modules -> set Enable modules(C and Objective-C) to NO.

Here 8.1 is your xcode version number if you are using xcode 9 then it will be Apple LLVM 9.0 instead of Apple LLVM 8.1.


问:
Program that reads multiple lines from a file and converts to a single line string
I'm trying to create a C program that takes a file path as a command line argument. My program then reads that file line by line, removing the endline character and adding it to a string so at the end the string is the input file but on only one line.

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100];
  char temp[200];

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
    line[strlen(line)-1] = '\0';
    strcat(temp, line);
    line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}
</code>```

I input a file with data:

```<code>This is Line 1
line 2
line 3
and this is line 4
</code>```

and expect the string to be
This is Line 1line 2line 3and this is line 4

but instead it is
and this is line 1

Any help is appreciated!

答:
The following program works for me.</p>

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100]={0};
  char temp[200]={0};

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
      strcat(temp, line);
      temp[strlen(temp)-1] = '\0';
      line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}
</code>```

Body:
I'm trying to create a C program that takes a file path as a command line argument. My program then reads that file line by line, removing the endline character and adding it to a string so at the end the string is the input file but on only one line.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100];
  char temp[200];

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
    line[strlen(line)-1] = '\0';
    strcat(temp, line);
    line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}

I input a file with data:

This is Line 1
line 2
line 3
and this is line 4

and expect the string to be
This is Line 1line 2line 3and this is line 4

but instead it is
and this is line 1

Any help is appreciated!

Body:
The following program works for me.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char **argv){

  FILE *input = fopen(argv[1], "r");
  char *line = NULL;
  char buffer[100]={0};
  char temp[200]={0};

  line = fgets(buffer, 100 *sizeof(char), input);

  while(line != NULL){
      strcat(temp, line);
      temp[strlen(temp)-1] = '\0';
      line = fgets(buffer, 100 *sizeof(char), input);
  }

  printf("%s\n", temp);
  fclose(input);
}


问:
Enter key press simulation jquery/js (chrome script)
I am doing a script for a little game i play and i want it to simulate enter keypress after executing this code... I researched a bit but couldn't find any thing :/ can any one help me?</p>

```<code>if(parseInt(document.getElementById("premium_exchange_stock_wood").innerHTML)>64)
            //document.forms[0].buy_wood.value=1;
            document.forms[0].buy_wood.value=parseInt(document.getElementById("premium_exchange_stock_wood").innerHTML) ;

        else if(parseInt(document.getElementById("premium_exchange_stock_stone").innerHTML)>64)
            document.forms[0].buy_stone.value=parseInt(document.getElementById("premium_exchange_stock_stone").innerHTML) ;

        else if(parseInt(document.getElementById("premium_exchange_stock_iron").innerHTML)>64)
            document.forms[0].buy_iron.value=parseInt(document.getElementById("premium_exchange_stock_iron").innerHTML) ;
    else(window.location = "https://br86.tribalwars.com.br/game.php?village=4317&screen=market&mode=exchange");

    jQuery(":submit").click();
</code>```

答:
Try:

Html  :

```<code><input type="text" id="test"/>
</code>```

Jquery:

```<code>    var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#test").trigger(e);
</code>```

Body:
I am doing a script for a little game i play and i want it to simulate enter keypress after executing this code... I researched a bit but couldn't find any thing :/ can any one help me?

if(parseInt(document.getElementById("premium_exchange_stock_wood").innerHTML)>64)
            //document.forms[0].buy_wood.value=1;
            document.forms[0].buy_wood.value=parseInt(document.getElementById("premium_exchange_stock_wood").innerHTML) ;

        else if(parseInt(document.getElementById("premium_exchange_stock_stone").innerHTML)>64)
            document.forms[0].buy_stone.value=parseInt(document.getElementById("premium_exchange_stock_stone").innerHTML) ;

        else if(parseInt(document.getElementById("premium_exchange_stock_iron").innerHTML)>64)
            document.forms[0].buy_iron.value=parseInt(document.getElementById("premium_exchange_stock_iron").innerHTML) ;
    else(window.location = "https://br86.tribalwars.com.br/game.php?village=4317&screen=market&mode=exchange");

    jQuery(":submit").click();

Body:
Try:

Html  :

<input type="text" id="test"/>

Jquery:

    var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#test").trigger(e);


问:
Scala convention for Future type if result doesn't matter
I have a future for which I care if it completes successfully, but the result is meaningless. One such example is a Future that saves or deletes a record from a DB.
What is the best way to represent such future? Future[Any]? Future[Unit]?</p>

答: Future[Unit] is the normal way. It shows a bit more intent than Future[Any]. ie. You know that there is nothing within the future that you care about.</p>


问:
Send data to JS when PHP is told to do so
Here's an example. One user connects to the website and does some stuff. JS sends changes to PHP and it's processed. Say another user that connected at the same time needs to be notified of this change. So PHP somehow tells the second users browser through JS or something to change some HTML to the second user is aware of said changes. Is there a way I can do this? Or is it a no can do?</p>

答: You need websocket (http://socketo.me/) to do that or use pusher (https://pusher.com/) to push something to client.</p>


问:
How do i return date with MMDDYYYY format as a valid date value in sql server?
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

```<code>SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';
</code>```

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

答:
You need to add the separators first, before using ISDATE function       </p>

```<code>DECLARE @DATE nvarchar(100) = '11202018'

IF ISDATE(SELECT(STUFF(STUFF(@DATE,3,0,'-'),6,0,'-')))
       PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';
</code>```

Body:
I am trying to validate the date field for the various combination. While trying to validate MMDDYYYY, the function does not return it as valid. also, it does not give proper input for MMDDYY, MMMDDYY, MMMDDYYYY.

SET DATEFORMAT mdy;

IF ISDATE('11202018') = 1
    PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';

The date in above example is a valid date field, still, it returns invalid. I doubt SQL server is considering the local date setting.

Can anyone share your thought?

Body:
You need to add the separators first, before using ISDATE function

DECLARE @DATE nvarchar(100) = '11202018'

IF ISDATE(SELECT(STUFF(STUFF(@DATE,3,0,'-'),6,0,'-')))
       PRINT 'Valida date field'
ELSE
    PRINT 'INVALID';


问:
R sample a raster with square polygons
I would like to sample a big raster by creating In small raster 100x100 cells.
I don't know how to do that so any ideas are welcome

My actual lead :

```<code>library(raster)
library(spatstat)
library(polyCub)

r <- raster(ncol=1000,nrow=1000) # create empty raster
r[] <- 1:(1000*1000)             # Raster for testing
e <- extent(r)                   # get extend
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')

nc <- as.owin.SpatialPolygons(p) #polyCub
pts <- rpoint(50, win = nc)
plot(pts)
</code>```

Now I need to generate 100x100 cell square around my 50 points and I would like to crop r using those square and stack each small raster individually ...

答:
If you want to use spatstat then you need to convert the raster object r into an object of class im supported by spatstat. You can do this conversion in the maptools package. Call this image object rim. Then you can do as follows

```<code>Box <- owin(c(-50,50) * rim$xstep, c(-50,50) * rim$ystep)
BoxesUnion <- MinkowskiSum(pts, Box)
W <- intersect.owin(as.mask(rim), BoxesUnion)
</code>```

This would give you the subset of the raster that is covered by the squares.
If you want to keep the squares separate, do something like

```<code>M <- as.mask(rim)
BoxList <- solapply(seq_len(npoints(pts)),
                      function(i) intersect.owin(M, shift(Box, pts[i])))
</code>```

Then BoxList is a list of the individual sub-rasters.

Title: R sample a raster with square polygons

Body:
I would like to sample a big raster by creating In small raster 100x100 cells.
I don't know how to do that so any ideas are welcome

My actual lead :

library(raster)
library(spatstat)
library(polyCub)

r <- raster(ncol=1000,nrow=1000) # create empty raster
r[] <- 1:(1000*1000)             # Raster for testing
e <- extent(r)                   # get extend
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')

nc <- as.owin.SpatialPolygons(p) #polyCub
pts <- rpoint(50, win = nc)
plot(pts)

Now I need to generate 100x100 cell square around my 50 points and I would like to crop r using those square and stack each small raster individually ...

Body:
If you want to use spatstat then you need to convert the raster object r into an object of class im supported by spatstat. You can do this conversion in the maptools package. Call this image object rim. Then you can do as follows

Box <- owin(c(-50,50) * rim$xstep, c(-50,50) * rim$ystep)
BoxesUnion <- MinkowskiSum(pts, Box)
W <- intersect.owin(as.mask(rim), BoxesUnion)

This would give you the subset of the raster that is covered by the squares.
If you want to keep the squares separate, do something like

M <- as.mask(rim)
BoxList <- solapply(seq_len(npoints(pts)),
                      function(i) intersect.owin(M, shift(Box, pts[i])))

Then BoxList is a list of the individual sub-rasters.


问:
Firebase authentication registration Error occured
I'am try to register a user in my android app with using Google Firebase authentication option, but i am getting error and my Toast handle my error in this code line Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();

I think my SHA-1 and firebase connection was linked right. Firebase console image attached below

I'm here add my source code and also xml file.

```<code>package com.example.anu.activityone;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class RegistrationActivity extends AppCompatActivity {

private EditText txtEmail, txtPassword;
private Button btnRegister;

private FirebaseAuth mAuth;
/*
    public abstract class FirebaseAuth extends Object
    The entry point of the Firebase Authentication SDK.
 */
private FirebaseAuth.AuthStateListener FirebaseAuthStateListener;
/*  FirebaseAuth.AuthStateListener  is a interface,
    that Listener called when there is a change in the authentication state.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);

    // method called when user logged in or logged out
    mAuth = FirebaseAuth.getInstance();
    FirebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if(user != null){
                Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
    };

    txtEmail = (EditText)findViewById(R.id.email);
    txtPassword = (EditText)findViewById(R.id.password);
    btnRegister = (Button)findViewById(R.id.register);

    // Register a new user
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String email = txtEmail.getText().toString();
            final String password = txtPassword.getText().toString();
            /*
                Support User Registration
                With password-based authentication, new users must register themselves by providing
                a unique email address and a password. To add this functionality to your app,
                you can use the createUserWithEmailAndPassword() method of the FirebaseAuth class.
                As its name suggests, the method expects an email address and a password as its arguments.
             */
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
                /*
                    public interface OnCompleteListener
                    Listener called when a Task completes.
                 */
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            /*
                To be able to determine the result of the createUserWithEmailAndPassword() method,
                you must add an OnCompleteListener to it using the addOnCompleteListener() method.
             */
        }
    });
}
// To start Firebase authentication
@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(FirebaseAuthStateListener);
}
// To stop Firebase authentication when app pause
@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(FirebaseAuthStateListener);
}
}
</code>```

XML file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anu.activityone.RegistrationActivity"
android:orientation="vertical">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="email"
    android:id="@+id/email"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:id="@+id/password"/>

<Button
    android:id="@+id/register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Registration" />
</LinearLayout>
</code>```

答:
Try this code:

```<code>Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
</code>```

for getting complete information why login is failed and then update your question with Error occured

Body:
I'am try to register a user in my android app with using Google Firebase authentication option, but i am getting error and my Toast handle my error in this code line Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();

I think my SHA-1 and firebase connection was linked right. Firebase console image attached below

I'm here add my source code and also xml file.

package com.example.anu.activityone;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class RegistrationActivity extends AppCompatActivity {

private EditText txtEmail, txtPassword;
private Button btnRegister;

private FirebaseAuth mAuth;
/*
    public abstract class FirebaseAuth extends Object
    The entry point of the Firebase Authentication SDK.
 */
private FirebaseAuth.AuthStateListener FirebaseAuthStateListener;
/*  FirebaseAuth.AuthStateListener  is a interface,
    that Listener called when there is a change in the authentication state.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);

    // method called when user logged in or logged out
    mAuth = FirebaseAuth.getInstance();
    FirebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if(user != null){
                Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
    };

    txtEmail = (EditText)findViewById(R.id.email);
    txtPassword = (EditText)findViewById(R.id.password);
    btnRegister = (Button)findViewById(R.id.register);

    // Register a new user
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final String email = txtEmail.getText().toString();
            final String password = txtPassword.getText().toString();
            /*
                Support User Registration
                With password-based authentication, new users must register themselves by providing
                a unique email address and a password. To add this functionality to your app,
                you can use the createUserWithEmailAndPassword() method of the FirebaseAuth class.
                As its name suggests, the method expects an email address and a password as its arguments.
             */
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
                /*
                    public interface OnCompleteListener
                    Listener called when a Task completes.
                 */
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(RegistrationActivity.this, "Sign Up Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            /*
                To be able to determine the result of the createUserWithEmailAndPassword() method,
                you must add an OnCompleteListener to it using the addOnCompleteListener() method.
             */
        }
    });
}
// To start Firebase authentication
@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(FirebaseAuthStateListener);
}
// To stop Firebase authentication when app pause
@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(FirebaseAuthStateListener);
}
}

XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anu.activityone.RegistrationActivity"
android:orientation="vertical">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="email"
    android:id="@+id/email"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:id="@+id/password"/>

<Button
    android:id="@+id/register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Registration" />
</LinearLayout>

Body:
Try this code:

Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();

for getting complete information why login is failed and then update your question with Error occured