问:
Count IF Function Equivalent
I have four columns: A Team, B Team, C Team, D Team.

Each row entry can contain either a Yes or No in each of the columns. For example like so:

```<code>A Team    B Team    C Team    D Team
------------------------------------
Yes       Yes       No        No
</code>```

I'm looking to create an additional column NumberofTeams that sums wherever there is a yes. So in this case it would return 2 - indicating that 2 teams are involved.

I was going to attempt it via a CASE function, but believe this would have to cover every single permutation?

```<code>select
    *,
    NumberofTeams = select case
                              when [A Team] = 'Yes' and [B Team] = 'Yes'
                                 then 2
                              when [A Team] = 'Yes' and [C Team] = 'Yes'
                                 then 2
</code>```

and so on.

If there's a 'cleaner' way?

答:
If the only choices are 'Yes' and 'No' then you can take a shortcut. Since they differ in length by 1 you can add the lengths of the strings and subtract the length of the shorter string for each column. More simply, concatenate the strings and take the overall length and subtract enough to account for no's:

```<code>declare @Samples as Table ( ATeam VarChar(3), BTeam VarChar(3), CTeam VarChar(3), DTeam VarChar(3) );
insert into @Samples values ( 'No', 'No', 'No', 'No' ), ( 'Yes', 'No', 'Yes', 'No' ), ( 'Yes', 'Yes', 'Yes', 'Yes' );

select *, Len( ATeam + BTeam + CTeam + DTeam ) - 8 as NumberOfTeams
  from @Samples;
</code>```

Title: Count IF Function Equivalent

Body:
I have four columns: A Team, B Team, C Team, D Team.

Each row entry can contain either a Yes or No in each of the columns. For example like so:

A Team    B Team    C Team    D Team
------------------------------------
Yes       Yes       No        No

I'm looking to create an additional column NumberofTeams that sums wherever there is a yes. So in this case it would return 2 - indicating that 2 teams are involved.

I was going to attempt it via a CASE function, but believe this would have to cover every single permutation?

select
    *,
    NumberofTeams = select case
                              when [A Team] = 'Yes' and [B Team] = 'Yes'
                                 then 2
                              when [A Team] = 'Yes' and [C Team] = 'Yes'
                                 then 2

and so on.

If there's a 'cleaner' way?

Body:
If the only choices are 'Yes' and 'No' then you can take a shortcut. Since they differ in length by 1 you can add the lengths of the strings and subtract the length of the shorter string for each column. More simply, concatenate the strings and take the overall length and subtract enough to account for no's:

declare @Samples as Table ( ATeam VarChar(3), BTeam VarChar(3), CTeam VarChar(3), DTeam VarChar(3) );
insert into @Samples values ( 'No', 'No', 'No', 'No' ), ( 'Yes', 'No', 'Yes', 'No' ), ( 'Yes', 'Yes', 'Yes', 'Yes' );

select *, Len( ATeam + BTeam + CTeam + DTeam ) - 8 as NumberOfTeams
  from @Samples;


来源: stackexchange

问:
Scope in higher order functions in Java 8 lambda syntax of Combinator Pattern
I'm trying to understand the syntax in the create method of the following example:

```<code>import java.math.BigDecimal;
import java.util.function.Consumer;
import java.util.function.Function;

@FunctionalInterface
interface Before<T, R> extends Function<Consumer<T>, Function<Function<T, R>, Function<T, R>>> {

    static <T, R> Before<T, R> create() {
        return before -> function -> argument -> {
            before.accept(argument);
            return function.apply(argument);
        };
    }

    static <T, R> Function<T, R> decorate(Consumer<T> before, Function<T, R> function) {
        return Before.<T, R>create().apply(before).apply(function);
    }
}

public class BeforeExample {

    void demo() {
        System.out.println("----------------------------------");
        System.out.println("Starting BEFORE combinator demo...");
        System.out.println("----------------------------------");

        Function<BigDecimal, String> addTax = this::addTax;

        Consumer<BigDecimal> before = this::before;

        Function<BigDecimal, String> addTaxDecorated = Before.decorate(before, addTax);

        BigDecimal argument = new BigDecimal("100");
        String result = addTaxDecorated.apply(argument);

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private void before(BigDecimal argument) {
        System.out.println("BEFORE: Argument is " + argument);
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to our poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }
}
</code>```

Can someone please explain:

what is going on in the return before -> function -> argument -> {...} block and how the variables before, function and argument become known without seemingly being passed into create's signature, as well as

what the multiple -> signify.

Thank you.

答:
what is going on in the return before -> function -> argument -> {...}
  block and how the variables before, function and argument become known
  without seemingly being passed in

The following piece of code can help you understand the block and the usage of variables within:

```<code>static <T, R> Before<T, R> create() {
    return new Before<T, R>() {
        @Override
        public Function<Function<T, R>, Function<T, R>> apply(Consumer<T> before) {
            return new Function<Function<T, R>, Function<T, R>>() {
                @Override
                public Function<T, R> apply(Function<T, R> function) {
                    return new Function<T, R>() {
                        @Override
                        public R apply(T argument) {
                            before.accept(argument);
                            return function.apply(argument);
                        }
                    };
                }
            };
        }
    };
}
</code>```

what the multiple -> signify.

The lambda representation for each of those functional interfaces combined to represent the implementation of create method.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to understand the syntax in the create method of the following example:

import java.math.BigDecimal;
import java.util.function.Consumer;
import java.util.function.Function;

@FunctionalInterface
interface Before<T, R> extends Function<Consumer<T>, Function<Function<T, R>, Function<T, R>>> {

    static <T, R> Before<T, R> create() {
        return before -> function -> argument -> {
            before.accept(argument);
            return function.apply(argument);
        };
    }

    static <T, R> Function<T, R> decorate(Consumer<T> before, Function<T, R> function) {
        return Before.<T, R>create().apply(before).apply(function);
    }
}

public class BeforeExample {

    void demo() {
        System.out.println("----------------------------------");
        System.out.println("Starting BEFORE combinator demo...");
        System.out.println("----------------------------------");

        Function<BigDecimal, String> addTax = this::addTax;

        Consumer<BigDecimal> before = this::before;

        Function<BigDecimal, String> addTaxDecorated = Before.decorate(before, addTax);

        BigDecimal argument = new BigDecimal("100");
        String result = addTaxDecorated.apply(argument);

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private void before(BigDecimal argument) {
        System.out.println("BEFORE: Argument is " + argument);
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to our poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }
}

Can someone please explain:

what is going on in the return before -> function -> argument -> {...} block and how the variables before, function and argument become known without seemingly being passed into create's signature, as well as

what the multiple -> signify.

Thank you.

Body:
what is going on in the return before -> function -> argument -> {...}
  block and how the variables before, function and argument become known
  without seemingly being passed in

The following piece of code can help you understand the block and the usage of variables within:

static <T, R> Before<T, R> create() {
    return new Before<T, R>() {
        @Override
        public Function<Function<T, R>, Function<T, R>> apply(Consumer<T> before) {
            return new Function<Function<T, R>, Function<T, R>>() {
                @Override
                public Function<T, R> apply(Function<T, R> function) {
                    return new Function<T, R>() {
                        @Override
                        public R apply(T argument) {
                            before.accept(argument);
                            return function.apply(argument);
                        }
                    };
                }
            };
        }
    };
}

what the multiple -> signify.

The lambda representation for each of those functional interfaces combined to represent the implementation of create method.


问:
Download remote file into memory via pure batch
In my batch script, I am trying to download and execute a powershell script remotely. Here is the url:

```<code>https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1
</code>```

I want to download the file into memory (without touching disk), for several reasons:

It bypasses AV detection

It bypasses Powershell executionpolicy, so there's no need for the powershell -nop -ep bypass that causes AV detection

Won't throw unneccessary syntax errors

You can directly use functions defined inside the .ps1 script

Obviously i can use certutil:

```<code>certutil -urlcache -split -f <url>
</code>```

but I don't want the file to hit disk, which can cause AV detection.

The same thing can be done with easily using other languages, like PowerShell:

```<code>(New-Object Net.WebClient).DownloadString($url)
</code>```

OR

```<code>(New-Object IO.StreamReader([Net.HttpWebRequest]::Create($url).GetResponse().GetResponseStream())).ReadToEnd()
</code>```

I know batch isn't the best language to do this, but is it possible? (I want pure batch)

答: To my knowledge, no. Batch reads a file by accessing it via read perms. This means that it would not use the right protocol to access a file on a web server without batch allowing it to be read via FTP.</p>

Body:
In my batch script, I am trying to download and execute a powershell script remotely. Here is the url:

https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1

I want to download the file into memory (without touching disk), for several reasons:

It bypasses AV detection

It bypasses Powershell executionpolicy, so there's no need for the powershell -nop -ep bypass that causes AV detection

Won't throw unneccessary syntax errors

You can directly use functions defined inside the .ps1 script

Obviously i can use certutil:

certutil -urlcache -split -f <url>

but I don't want the file to hit disk, which can cause AV detection.

The same thing can be done with easily using other languages, like PowerShell:

(New-Object Net.WebClient).DownloadString($url)

OR

(New-Object IO.StreamReader([Net.HttpWebRequest]::Create($url).GetResponse().GetResponseStream())).ReadToEnd()

I know batch isn't the best language to do this, but is it possible? (I want pure batch)


问:
is this json file? and if yes, how can I read it back to java?

Possible Duplicate:

  A better Java JSON library?

Hi,

I have a json file like this:

```<code>workloads = [
  {
    total: 5,
    attributes:
    {
      taskA:1,
      taskB:2
    }
  }
]
</code>```

Thanks in advance

答: There are plenty of links on the JSON site: http://json.org/java/</p>

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  A better Java JSON library?

Hi,

I have a json file like this:

workloads = [
  {
    total: 5,
    attributes:
    {
      taskA:1,
      taskB:2
    }
  }
]

Thanks in advance


问:
Split Pandas Dataframe into Multiple Excel Sheets Based on Index Value in Dataframe
I have this dataset:

That has the column 'Product' with values 'Gas', 'Oil', and 'Water'. I want to write this dataframe to a single excel workbook with three worksheets with the 'Gas', 'Oil', and 'Water' data in those three worksheets.

I have tried:

and keep getting a type error. Any assistance is appreciated.

答:
IIUC,

you can group by product and assign this as the sheet name, whilst assigning the data into the sheet based on the aggregation.

```<code>writer = pd.ExcelWriter('Report.xlsx')

for group, data in result2.groupby('Product'):
    data.to_excel(writer,group)
writer.save()

</code>```

Body:
IIUC,

you can group by product and assign this as the sheet name, whilst assigning the data into the sheet based on the aggregation.

writer = pd.ExcelWriter('Report.xlsx')

for group, data in result2.groupby('Product'):
    data.to_excel(writer,group)
writer.save()


问:
$elemMatch for filtering out referenced($ref) array objects in mongodb is not working
I have 2 collections student_details and subject_details where each student can have multiple subjects which I am storing in student_details collection as reference array.

Now I need to fetch Student details along with the filtered subjects where subject_details.status=ACTIVE.

How can I achieve this using $elemMatch for $ref objects.
I was using something like below but it is not returning any records.

db.getCollection('student_details').find( { subjects: { $elemMatch: { $ref: "subject_details", status: 'ACTIVE' }}})

```<code>student_details
================
{
    "_id" : "STD-1",
    "name" : "XYZ",
    "subjects" : [
        {
            "$ref" : "subject_details",
            "$id" : "SUB-1"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-2"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-3"
        }
    ]
}

subject_details
===============
{
    "_id" : "SUB-1",
    "name" : "MATHEMATICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-2",
    "name" : "PHYSICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-3",
    "name" : "CHEMISTRY",
    "status" : "INACTIVE"
}

</code>```

答:
because they are in 2 collections you need $lookUp to bring them together...   before that I believe you need to $unwind the Subjects array...  kind of aircode here so this isn't so much an answer as general advice...  the aggregation pipeline is  used to do these in stages...

am assuming you are abbreviating for the post...cause if Subject Details is really just 3 fields your schema is better served in the NoSQL world to just put that info with Student Details and use 1 collection rather than a normalized relational approach

Body:
I have 2 collections student_details and subject_details where each student can have multiple subjects which I am storing in student_details collection as reference array.

Now I need to fetch Student details along with the filtered subjects where subject_details.status=ACTIVE.

How can I achieve this using $elemMatch for $ref objects.
I was using something like below but it is not returning any records.

db.getCollection('student_details').find( { subjects: { $elemMatch: { $ref: "subject_details", status: 'ACTIVE' }}})

student_details
================
{
    "_id" : "STD-1",
    "name" : "XYZ",
    "subjects" : [
        {
            "$ref" : "subject_details",
            "$id" : "SUB-1"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-2"
        },
        {
            "$ref" : "subject_details",
            "$id" : "SUB-3"
        }
    ]
}

subject_details
===============
{
    "_id" : "SUB-1",
    "name" : "MATHEMATICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-2",
    "name" : "PHYSICS",
    "status" : "ACTIVE"
}

{
    "_id" : "SUB-3",
    "name" : "CHEMISTRY",
    "status" : "INACTIVE"
}


问:
Can't seem to input any integer values when running the app? It just shows result "grade c"
The salary scheme for a company is given as follows:

Salary range for grade A: $700 - $899

Salary range for grade B: $600 - $799

Salary range for grade C: $500 - $649

A person whose salary is between $600 and $649 is in grade C if his merit points are below 10, otherwise he is in grade B. A person whose salary is between $700 and $799 is in grade B if his merit points are below 20, otherwise, he is in grade A. Write a program to read in a person’s salary and his merit points, and displays his grade.

```<code>package trydontquit1;
import java.util.*;

public class tryagain {
    public int salary;
    public int merits;

    public class employee {
        employee (int inputsalary, int inputmerits){
            salary = inputsalary;
            merits = inputmerits;
        }

        //grade the input in regard to salary and merits point
        void grade() {
            int c = 0, b = 0, a = 0;
            c = salary - 600;
            b = salary - 700;
            a = salary - 800;
            if (c <= 49 && merits < 10)
                System.out.println("Grade = C");
            else if (b <= 99 && merits < 20)
                System.out.println("Grade = B");
            else if (b > 99)
                System.out.println("Grade = A");
        }
    }
    //to instantiate an object and to grade employee
    public static void main(String[] args) {
        int x=0, y=0;
        System.out.println("Grading of employee");
        tryagain tryagain = new tryagain();
        employee sc = tryagain.new employee(x,y);
        System.out.println("Please enter salary\n");
        Scanner i = new Scanner(System.in);
        System.out.println("Please enter merits\n");
        Scanner j = new Scanner(System.in);
        sc.grade();
    }
}
</code>```

答:
Seems you are not reading the inputs. You need to change the flow of the code inside main method. please check below code:

```<code>public static void main(String[] args) {
    int x = 0, y = 0;
    System.out.println("Grading of employee");
    tryagain tryagain = new tryagain();
    Scanner i = new Scanner(System.in);
    System.out.println("Please enter salary\n");
    x = i.nextInt();
    System.out.println("Please enter merits\n");
    y = i.nextInt();
    employee sc = tryagain.new employee(x, y);
    sc.grade();
}
</code>```

Body:
The salary scheme for a company is given as follows:

Salary range for grade A: $700 - $899

Salary range for grade B: $600 - $799

Salary range for grade C: $500 - $649

A person whose salary is between $600 and $649 is in grade C if his merit points are below 10, otherwise he is in grade B. A person whose salary is between $700 and $799 is in grade B if his merit points are below 20, otherwise, he is in grade A. Write a program to read in a person’s salary and his merit points, and displays his grade.

package trydontquit1;
import java.util.*;

public class tryagain {
    public int salary;
    public int merits;

    public class employee {
        employee (int inputsalary, int inputmerits){
            salary = inputsalary;
            merits = inputmerits;
        }

        //grade the input in regard to salary and merits point
        void grade() {
            int c = 0, b = 0, a = 0;
            c = salary - 600;
            b = salary - 700;
            a = salary - 800;
            if (c <= 49 && merits < 10)
                System.out.println("Grade = C");
            else if (b <= 99 && merits < 20)
                System.out.println("Grade = B");
            else if (b > 99)
                System.out.println("Grade = A");
        }
    }
    //to instantiate an object and to grade employee
    public static void main(String[] args) {
        int x=0, y=0;
        System.out.println("Grading of employee");
        tryagain tryagain = new tryagain();
        employee sc = tryagain.new employee(x,y);
        System.out.println("Please enter salary\n");
        Scanner i = new Scanner(System.in);
        System.out.println("Please enter merits\n");
        Scanner j = new Scanner(System.in);
        sc.grade();
    }
}

Body:
Seems you are not reading the inputs. You need to change the flow of the code inside main method. please check below code:

public static void main(String[] args) {
    int x = 0, y = 0;
    System.out.println("Grading of employee");
    tryagain tryagain = new tryagain();
    Scanner i = new Scanner(System.in);
    System.out.println("Please enter salary\n");
    x = i.nextInt();
    System.out.println("Please enter merits\n");
    y = i.nextInt();
    employee sc = tryagain.new employee(x, y);
    sc.grade();
}


问:
Knitr cannot find img files in /static/ folder
I have a hugo-academic website (methods101.com) that has been working well for last year.

I just went to edit some pages and I've started getting a new error.

The code that seems to be creating the problems is the knitr::include_graphics() function.

This is an example of the text that produces an error:

```<code>{r, echo=FALSE, out.width=600,
fig.cap="Newspaper article in Word document, next to same article on internet.",
fig.align='center'}

knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png")
</code>```

This is the error message:

```<code>Rendering content/docs/SOC224_qual_analysis_eg.Rmd
Quitting from lines 80-81 (SOC224_qual_analysis_eg.Rmd)
Error in knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png") :
  Cannot find the file(s): "/img/soc224_qual_analysis_eg_figure_1.png"
Calls: local ... withCallingHandlers -> withVisible -> eval -> eval -> <Anonymous>
Execution halted
<simpleError in render_page(f): Failed to render 'content/docs/SOC224_qual_analysis_eg.Rmd'>
</code>```

I get the same problem on different computers, and after fresh re-installing/downloading the website contents.

The image file is definitely inside the folder:

/static/img/

答:
We managed to solve this problem by rolling back to the earlier version of Knitr.

This was the code we used:

```<code>remove.packages("knitr")
packageurl <- "https://cran.r-project.org/src/contrib/Archive/knitr/knitr_1.27.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
</code>```

We had no problems on 5th Feb, but noticed the new version of knitr came out on 6th Feb, and so thought this could be causing the problems.

We don't get the problems with the old version of knitr.

Not sure what the underlying cause is.

Body:
I have a hugo-academic website (methods101.com) that has been working well for last year.

I just went to edit some pages and I've started getting a new error.

The code that seems to be creating the problems is the knitr::include_graphics() function.

This is an example of the text that produces an error:

{r, echo=FALSE, out.width=600,
fig.cap="Newspaper article in Word document, next to same article on internet.",
fig.align='center'}

knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png")

This is the error message:

Rendering content/docs/SOC224_qual_analysis_eg.Rmd
Quitting from lines 80-81 (SOC224_qual_analysis_eg.Rmd)
Error in knitr::include_graphics("/img/soc224_qual_analysis_eg_figure_1.png") :
  Cannot find the file(s): "/img/soc224_qual_analysis_eg_figure_1.png"
Calls: local ... withCallingHandlers -> withVisible -> eval -> eval -> <Anonymous>
Execution halted
<simpleError in render_page(f): Failed to render 'content/docs/SOC224_qual_analysis_eg.Rmd'>

I get the same problem on different computers, and after fresh re-installing/downloading the website contents.

The image file is definitely inside the folder:

/static/img/

Body:
We managed to solve this problem by rolling back to the earlier version of Knitr.

This was the code we used:

remove.packages("knitr")
packageurl <- "https://cran.r-project.org/src/contrib/Archive/knitr/knitr_1.27.tar.gz"
install.packages(packageurl, repos=NULL, type="source")

We had no problems on 5th Feb, but noticed the new version of knitr came out on 6th Feb, and so thought this could be causing the problems.

We don't get the problems with the old version of knitr.

Not sure what the underlying cause is.


问:
Add / Remove to Array using Hooks (useState)
I am trying to create a Bingo Game in React-Native. Each button in the Bingo Grid is a TouchableOpacity with an integer ID. My idea was to have the button being pressed either added to an array or removed from an array, depending on whether or not it was selected for the bingo game (using color of the button).

As of right now, when I open the app and click a button once (marking it as selected), console logs an empty array. When I click it again (deselecting it), the console logs the ID of that button. This happens separately with all the buttons when I click on them rather than collectively all referring to one array.

My code now:

```<code>const sol1 = ['1', '5', '21', '25'];

const [color, setColor] = useState('white');
const [marked, setMarked] = useState([]);
const addButton = (tapID) => setMarked(marked => [...marked, tapID]);
const removeButton = (tapID) => {
    let name = tapID;
    setMarked(marked.filter((tapID)=>(tapID !== name)))
};

const checkWin = () => {
    if (marked.length === null) {
        console.log("nothing");
    } else {
        var containsAll = sol1.every(i => marked.includes(i));
        if (containsAll  === true){
            console.log("win");
        }
        console.log("WOAH");
    }
}

const markPlay = () => {
    if (color === 'white'){
        setColor('#b8b8ab');
        addButton(tapID);
        console.log(marked);
        checkWin()
    } else {
        setColor('white');
        removeButton(tapID);
        console.log(marked);
        checkWin()
    }
}
</code>```

This is what the output looks like when I select all 4 corners then deselect them.

```<code> LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  ["1"]
 LOG  WOAH
 LOG  ["5"]
 LOG  WOAH
 LOG  ["21"]
 LOG  WOAH
 LOG  ["25"]
 LOG  WOAH
</code>```

Instead, I want it to just show one array that fills with ["1","5","21","25"], and then notifies of a win.

Any help/guidance is much appreciated!

答:
Updating the state variables is not done right-away which means when you call the addButton to add a mark in your marked array it is not done right away, hence you see this empty array on next console.log.

You need to bind this condition check (checkWin) inside a useEffect which will have its dependency on your array marked.

Something like this..

```<code>useEffect(() => {
    console.log(marked);
    checkWin()
}, [marked])

const markPlay = () => {
    if (color === 'white'){
        setColor('#b8b8ab');
        addButton(tapID);
    } else {
        setColor('white');
        removeButton(tapID);
    }
}

</code>```

Body:
I am trying to create a Bingo Game in React-Native. Each button in the Bingo Grid is a TouchableOpacity with an integer ID. My idea was to have the button being pressed either added to an array or removed from an array, depending on whether or not it was selected for the bingo game (using color of the button).

As of right now, when I open the app and click a button once (marking it as selected), console logs an empty array. When I click it again (deselecting it), the console logs the ID of that button. This happens separately with all the buttons when I click on them rather than collectively all referring to one array.

My code now:

const sol1 = ['1', '5', '21', '25'];

const [color, setColor] = useState('white');
const [marked, setMarked] = useState([]);
const addButton = (tapID) => setMarked(marked => [...marked, tapID]);
const removeButton = (tapID) => {
    let name = tapID;
    setMarked(marked.filter((tapID)=>(tapID !== name)))
};

const checkWin = () => {
    if (marked.length === null) {
        console.log("nothing");
    } else {
        var containsAll = sol1.every(i => marked.includes(i));
        if (containsAll  === true){
            console.log("win");
        }
        console.log("WOAH");
    }
}

const markPlay = () => {
    if (color === 'white'){
        setColor('#b8b8ab');
        addButton(tapID);
        console.log(marked);
        checkWin()
    } else {
        setColor('white');
        removeButton(tapID);
        console.log(marked);
        checkWin()
    }
}

This is what the output looks like when I select all 4 corners then deselect them.

 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  []
 LOG  WOAH
 LOG  ["1"]
 LOG  WOAH
 LOG  ["5"]
 LOG  WOAH
 LOG  ["21"]
 LOG  WOAH
 LOG  ["25"]
 LOG  WOAH

Instead, I want it to just show one array that fills with ["1","5","21","25"], and then notifies of a win.

Any help/guidance is much appreciated!

Body:
Updating the state variables is not done right-away which means when you call the addButton to add a mark in your marked array it is not done right away, hence you see this empty array on next console.log.

You need to bind this condition check (checkWin) inside a useEffect which will have its dependency on your array marked.

Something like this..

useEffect(() => {
    console.log(marked);
    checkWin()
}, [marked])

const markPlay = () => {
    if (color === 'white'){
        setColor('#b8b8ab');
        addButton(tapID);
    } else {
        setColor('white');
        removeButton(tapID);
    }
}


问:
Import a Nest.js app as a simple Express middleware
I've a Nestjs app (a Rest API) that I would like to import in another node module, as a simple Express middleware (not a Nest middleware). Actually I'm still not able to make it working.

// main.ts
// => The main file of my Nest app, this one is working properly.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

```

<pre class="lang-js prettyprint-override"><code>// app.middleware.ts

import {Injectable, NestMiddleware} from '@nestjs/common';
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {ExpressAdapter} from '@nestjs/platform-express';
import express, {Request, Response} from 'express';

const bootstrap = async () => {
  const expressApp = express();
  const adapter = new ExpressAdapter(expressApp);
  const app = await NestFactory.create(AppModule, adapter);
  await app.init();
  return app;
};

@Injectable()
export class AppMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    return bootstrap();
  }
}
</code>```

// express-app.ts
// => Here I'm trying to load my app through a simple Express middleware, but it doesn't works.

import express from 'express';
import { AppMiddleware } from './app.middleware';

const app = express();
const PORT = process.env.PORT || 3000;

app.use((req, res, next) => {
  const app = new AppMiddleware().use(req, res, next);
  app.then(next);
});

app.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});
```

<p>When running my app from <code>main.ts</code> it's working properly (all the routes are working and I'm getting the correct data). However when I try to run the app through <code>express-app.ts</code>, all the routes seems working (they are displayed in the terminal), but instead of returning a JSON object, in any case I'm getting this error:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    ```[object Object]```
</body>

</html>
</code>```

Nest component versions:

```<code>- @nestjs/common: "^6.10.14"
- @nestjs/core: "^6.10.14"
- @nestjs/platform-express: "^6.10.14"
- express: "^4.16.4"
</code>```

答:
While I don't condone the use of Nest as a middleware itself, it is possible. Using a basic set up from a nest new express-server -p npm to create the new NestJS application, and setting up a small express server with src/server.ts I was able to get the following code working.

app.middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';

const bootstrap = async (express: Express.Application) => {
  const app = await NestFactory.create(AppModule, new ExpressAdapter(express));
  await app.init();
  return app;
}

@Injectable()
export class AppMiddleware implements NestMiddleware {

  constructor(private expressInstance: Express.Application) {}

  use(req: any, res: any, next: () => void) {
    console.log('In Nest middleware');
    return bootstrap(this.expressInstance);
  }
}
```

<h3>app.controller.ts</h3>

<pre class="lang-js prettyprint-override"><code>import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
</code>```

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}
```

<h3>app.module.ts</h3>

<pre class="lang-js prettyprint-override"><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
</code>```

server.ts

import * as express from 'express';

import { AppMiddleware } from './app.middleware';

const app = express();

app.use((req, res, next) => {
  const nest = new AppMiddleware(app).use(req, res, next);
  nest.then(() => {
    next();
  }).catch(err => {
    console.log(JSON.stringify(err));
    next();
  });
});

app.listen(3000, () => {
  console.log('Listening on port 3000');
});
```

<h3>Build command</h3>

<pre class="lang-sh prettyprint-override"><code>npm run build
# mapped to nest build
</code>```

Start command

node dist/server.js
```

<h3>Test command</h3>

<pre class="lang-sh prettyprint-override"><code>▶ curl http://localhost:3000
Hello World!
</code>```

Console Log

Listening on port 3000
In Nest middleware
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestFactory] Starting Nest application...
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [InstanceLoader] AppModule dependencies initialized +15ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RoutesResolver] AppController {/}: +3ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestApplication] Nest application successfully started +2ms
```

Keep in mind a few things:

1) with this approach, unless you cache your Nest server, you will build a new Nest server on each request, which will only slow your project down more as you grow with the Nest side of things.

2) You could instead pass your existing express server to the ExpressAdapter as you are partially doing in your existing code and start the server from the Nest app.listen() function instead. Just make sure to remove any error handling middleware as it will start to conflict with how Nest handles responses. You should instead move those functions to ExceptionFilters.

3) One of the errors in your app.middleware is that you are creating not only a new Nest instance on each call, but a new express instance too, which could really be confusing the node server.

4) The error that was coming in as [Object object] in case you were wondering, was a standard Express error Cannot GET /. Dunno why it was serialized strangely, but a JSON.stringify() in the catch helped resolve it.

Overall, I would not recommend this approach but it is possible to do.

Body:
I've a Nestjs app (a Rest API) that I would like to import in another node module, as a simple Express middleware (not a Nest middleware). Actually I'm still not able to make it working.

// main.ts
// => The main file of my Nest app, this one is working properly.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

// app.middleware.ts

import {Injectable, NestMiddleware} from '@nestjs/common';
import {NestFactory} from '@nestjs/core';
import {AppModule} from './app.module';
import {ExpressAdapter} from '@nestjs/platform-express';
import express, {Request, Response} from 'express';

const bootstrap = async () => {
  const expressApp = express();
  const adapter = new ExpressAdapter(expressApp);
  const app = await NestFactory.create(AppModule, adapter);
  await app.init();
  return app;
};

@Injectable()
export class AppMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    return bootstrap();
  }
}

// express-app.ts
// => Here I'm trying to load my app through a simple Express middleware, but it doesn't works.

import express from 'express';
import { AppMiddleware } from './app.middleware';

const app = express();
const PORT = process.env.PORT || 3000;

app.use((req, res, next) => {
  const app = new AppMiddleware().use(req, res, next);
  app.then(next);
});

app.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});

When running my app from main.ts it's working properly (all the routes are working and I'm getting the correct data). However when I try to run the app through express-app.ts, all the routes seems working (they are displayed in the terminal), but instead of returning a JSON object, in any case I'm getting this error:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Error</title>

[object Object]

Nest component versions:

- @nestjs/common: "^6.10.14"
- @nestjs/core: "^6.10.14"
- @nestjs/platform-express: "^6.10.14"
- express: "^4.16.4"

Body:
While I don't condone the use of Nest as a middleware itself, it is possible. Using a basic set up from a nest new express-server -p npm to create the new NestJS application, and setting up a small express server with src/server.ts I was able to get the following code working.

app.middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';

const bootstrap = async (express: Express.Application) => {
  const app = await NestFactory.create(AppModule, new ExpressAdapter(express));
  await app.init();
  return app;
}

@Injectable()
export class AppMiddleware implements NestMiddleware {

  constructor(private expressInstance: Express.Application) {}

  use(req: any, res: any, next: () => void) {
    console.log('In Nest middleware');
    return bootstrap(this.expressInstance);
  }
}

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

server.ts

import * as express from 'express';

import { AppMiddleware } from './app.middleware';

const app = express();

app.use((req, res, next) => {
  const nest = new AppMiddleware(app).use(req, res, next);
  nest.then(() => {
    next();
  }).catch(err => {
    console.log(JSON.stringify(err));
    next();
  });
});

app.listen(3000, () => {
  console.log('Listening on port 3000');
});

Build command

npm run build
# mapped to nest build

Start command

node dist/server.js

Test command

▶ curl http://localhost:3000
Hello World!

Console Log

Listening on port 3000
In Nest middleware
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestFactory] Starting Nest application...
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [InstanceLoader] AppModule dependencies initialized +15ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RoutesResolver] AppController {/}: +3ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 24235   - 02/18/2020, 8:05:44 PM   [NestApplication] Nest application successfully started +2ms

Keep in mind a few things:

1) with this approach, unless you cache your Nest server, you will build a new Nest server on each request, which will only slow your project down more as you grow with the Nest side of things.

2) You could instead pass your existing express server to the ExpressAdapter as you are partially doing in your existing code and start the server from the Nest app.listen() function instead. Just make sure to remove any error handling middleware as it will start to conflict with how Nest handles responses. You should instead move those functions to ExceptionFilters.

3) One of the errors in your app.middleware is that you are creating not only a new Nest instance on each call, but a new express instance too, which could really be confusing the node server.

4) The error that was coming in as [Object object] in case you were wondering, was a standard Express error Cannot GET /. Dunno why it was serialized strangely, but a JSON.stringify() in the catch helped resolve it.

Overall, I would not recommend this approach but it is possible to do.


问:
How can one move folders and files across sites and document libraries in SharePoint and maintain their version histories?
I'm trying to move folders across sites within the same SharePoint 2007 installation. A crucial requirement is maintaining the version history.

One approach I've tried is creating a new document library in the origin site and moving the folders into that, then moving the document library to the destination site. I've done the file move using cut-and-paste in Explorer view.

Unfortunately, it mangles the version histories of the files - each version in the history of a file ends up with the same date (and who knows where the date comes from - it's not in the original history of the file), though the Modified By and other metadata is fine.

I've used the following to move the document libraries:

SP Content Deployment Wizard 1.1 by Chris O'Brien (site)

STSADM.exe using Gary Lapointe's extensions (site), the following commands in particular: gl-exportlist, gl-importlist, gl-copylist.

Unfortunately, these tools don't work at a folder level.

My next move is to look at programming a solution, something I've been avoiding because I'm new to SharePoint and know nothing about programming for it.

Can anyone help me? Specifically, I'd welcome:

Any advice on how to perform the move without programming a custom solution

Any suggestions of tools that can do this, free or not (all I've looked at so far is AvePoint's DocAve, which can only manage content at a site-level, so it can't help me)

Any tips, articles, code, etc. that could help me develop a custom solution.

Thanks very much.

答: A nice PowerShell script using the CopyTo() method on the spListItem object should be a good place to start.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Kasper


问:
Call to undefined method Infusionsoft\Api\Rest\ContactService::addWithDupCheck()
This was working all this while with no issues and updates.

$user_id = $infusionsoft->contacts->addWithDupCheck($contact, 'Email');

Now all of a sudden it isn't

PHP Fatal error:  Uncaught Error: Call to undefined method
  Infusionsoft\Api\Rest\ContactService::addWithDupCheck() in
  /home/user/public_html/infusionsoft/addContact.cli.php:29

```<code>~/public_html/infusionsoft$ cat composer.json
{
    "require": {
        "infusionsoft/php-sdk": "^1.0"
    }
}
</code>```

答:
InfusionSoft has replaced their older XML-RPC API with REST. REST is now default. So I had to do :

$user_id = $infusionsoft->contacts('xml')->addWithDupCheck($contact, 'Email');

Body:
This was working all this while with no issues and updates.

$user_id = $infusionsoft->contacts->addWithDupCheck($contact, 'Email');

Now all of a sudden it isn't

PHP Fatal error:  Uncaught Error: Call to undefined method
  Infusionsoft\Api\Rest\ContactService::addWithDupCheck() in
  /home/user/public_html/infusionsoft/addContact.cli.php:29

~/public_html/infusionsoft$ cat composer.json
{
    "require": {
        "infusionsoft/php-sdk": "^1.0"
    }
}


问:
How to create a keyword with an optional argument that defaults to None in Robot Framework?
How do I create a custom keyword in Robot Framework that takes an optional argument so that I can call that keyword either with or without argument? e.g. that argument should default to None.

答:
Very basic example using built-in variable ${NONE}:

```<code>*** Test Cases ***
Call Keyword Without Argument
    Log Name

Call Keyword With Argument
    Log Name    Steve

*** Keywords ***
Log Name
    [Arguments]    ${name}=${NONE}
    Log    Your name is '${name}'
</code>```

Note: Consider that according to Robot Framework documentation ${NONE} and ${NULL} are synonyms

https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#boolean-and-none-null-variables

Body:
Very basic example using built-in variable ${NONE}:

*** Test Cases ***
Call Keyword Without Argument
    Log Name

Call Keyword With Argument
    Log Name    Steve

*** Keywords ***
Log Name
    [Arguments]    ${name}=${NONE}
    Log    Your name is '${name}'

Note: Consider that according to Robot Framework documentation ${NONE} and ${NULL} are synonyms

https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#boolean-and-none-null-variables


问:
Cannot complete ionic start command
I am trying to start a new project with ionic start myApp blank and selecting React. After I press enter, I see this output.

```<code>⠦ Downloading and extracting blank starter (100.00%)
events.js:174
throw er; // Unhandled ‘error’ event
^

Error: TAR_BAD_ARCHIVE: Unrecognized archive format
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/warn-mixin.js:19:40)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/unpack.js:188:18)
at Unpack.Parser.on._ (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:82:14)
at Unpack.emit (events.js:194:15)
at Unpack.[emit] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:286:12)
at Unpack.[maybeEnd] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:402:17)
at Unpack.[consumeChunk] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:434:21)
at Unpack.write (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:365:25)
at Unpack.end (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:479:14)
at IncomingMessage.onend (_stream_readable.js:651:10)
Emitted ‘error’ event at:
at Unpack.onerror (_stream_readable.js:713:12)
at Unpack.emit (events.js:189:13)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/warn-mixin.js:19:12)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/unpack.js:188:18)
[… lines matching original stack trace …]
at Unpack.write (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:365:25)
</code>```

I have uninstalled and reinstalled the @ionic/cli package. This behavior also applied to the Angular option as well and other template options. I am on macOS Catalina, 10.15.3. How can I resolve this?

答:
According to this issue with points to comment here try doing following

npm install -g ionic
```

then run ionic info

Title: Cannot complete ionic start command

Body:
I am trying to start a new project with ionic start myApp blank and selecting React. After I press enter, I see this output.

⠦ Downloading and extracting blank starter (100.00%)
events.js:174
throw er; // Unhandled ‘error’ event
^

Error: TAR_BAD_ARCHIVE: Unrecognized archive format
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/warn-mixin.js:19:40)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/unpack.js:188:18)
at Unpack.Parser.on._ (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:82:14)
at Unpack.emit (events.js:194:15)
at Unpack.[emit] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:286:12)
at Unpack.[maybeEnd] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:402:17)
at Unpack.[consumeChunk] (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:434:21)
at Unpack.write (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:365:25)
at Unpack.end (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:479:14)
at IncomingMessage.onend (_stream_readable.js:651:10)
Emitted ‘error’ event at:
at Unpack.onerror (_stream_readable.js:713:12)
at Unpack.emit (events.js:189:13)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/warn-mixin.js:19:12)
at Unpack.warn (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/unpack.js:188:18)
[… lines matching original stack trace …]
at Unpack.write (/usr/local/lib/node_modules/@ionic/cli/node_modules/tar/lib/parse.js:365:25)

I have uninstalled and reinstalled the @ionic/cli package. This behavior also applied to the Angular option as well and other template options. I am on macOS Catalina, 10.15.3. How can I resolve this?

Body:
According to this issue with points to comment here try doing following

npm install -g ionic

then run ionic info


问:
IE 11 failed to create file object from byte array in Angular
Can anybody tell me why IE11 is throwing error
In other browsers working only in IE getting error "object doesn't support this action"</p>

```<code>let file = new File([files], newFileName, { type: Constants.FILECONTENTTYPE, lastModified: Date.now() });
                let uploadDocument = new UploadDocument();
                uploadDocument.fileName = newFileName;
                uploadDocument.fileItem = file;
                this.fileList = [];
                this.mergedFileList.forEach(fileItem => {
                    this.fileList.push(fileItem);
                });
</code>```

答:
IE doesn't support File() constructor and lastModified.

In IE, you should create a Blob object then set some specific properties with the File Name, Last Modified Date and Type to the Blob. Files are Blobs plus meta properties.

```<code>var blob = new Blob([files], { type: Constants.FILECONTENTTYPE });
blob['fileName'] = newFileName;
blob['lastModifiedDate'] = Date.now();
</code>```

For more information, you could also refer to this thread.

Body:
Can anybody tell me why IE11 is throwing error
In other browsers working only in IE getting error "object doesn't support this action"

let file = new File([files], newFileName, { type: Constants.FILECONTENTTYPE, lastModified: Date.now() });
                let uploadDocument = new UploadDocument();
                uploadDocument.fileName = newFileName;
                uploadDocument.fileItem = file;
                this.fileList = [];
                this.mergedFileList.forEach(fileItem => {
                    this.fileList.push(fileItem);
                });

Body:
IE doesn't support File() constructor and lastModified.

In IE, you should create a Blob object then set some specific properties with the File Name, Last Modified Date and Type to the Blob. Files are Blobs plus meta properties.

var blob = new Blob([files], { type: Constants.FILECONTENTTYPE });
blob['fileName'] = newFileName;
blob['lastModifiedDate'] = Date.now();

For more information, you could also refer to this thread.


问:
ggmap and spatial data plotting issue
I am trying to update some old code that I inherited from before the Google API days to do a fairly simple (I think) plot.

By the time I get to the plot, my data consists of 50 triplets of latitude, longitude, and $K amount of investment at that location.

```<code>head(investData)
  amount latitude longitude
1 1404   42.45909 -71.27556
2 1      42.29076 -71.35368
3 25     42.34700 -71.10215
4 1      40.04492 -74.58916
5 15     43.16431 -75.51130
</code>```

at this point I use the following

```<code>register_google(key = "###myKey###")   #my actual key here

USAmap <- qmap("USA",zoom=4)

USAmap + geom_point(data=investData, aes(x=investData$longitude, y=investData$latitude,size=investData$amount))
</code>```

I've been fighting all ay with establishing accounts and enabling APIs with Google, so it's entirely possible I've simply failed to enable something I need to.  I have the geocoding, geolocation, and maps static APIs enabled.

I get the following output at the console

```<code>Source : https://maps.googleapis.com/maps/api/staticmap?center=USA&zoom=4&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx
Source : https://maps.googleapis.com/maps/api/geocode/json?address=USA&key=xxx
</code>```

But I get no plot.

if I simply run

```<code>qmap("USA", zoom=4)
</code>```

I get the map I expect.  But when I try to overlay the investment data I get zilch.  I'm told by the folks who handed this to me that it worked in 2017...

Any idea where I'm going wrong?

答:
If you are running your script via the source function or with the run command (from inside RStudio) you must explicitly call the print function on your ggplot commands.  For example:

```<code>print(USAmap + geom_point(data=investData, aes(x=longitude, y=latitude,size=amount)))
</code>```

As Camille mentioned, no need for the $ inside the aes

Title: ggmap and spatial data plotting issue

Body:
I am trying to update some old code that I inherited from before the Google API days to do a fairly simple (I think) plot.

By the time I get to the plot, my data consists of 50 triplets of latitude, longitude, and $K amount of investment at that location.

head(investData)
  amount latitude longitude
1 1404   42.45909 -71.27556
2 1      42.29076 -71.35368
3 25     42.34700 -71.10215
4 1      40.04492 -74.58916
5 15     43.16431 -75.51130

at this point I use the following

register_google(key = "###myKey###")   #my actual key here

USAmap <- qmap("USA",zoom=4)

USAmap + geom_point(data=investData, aes(x=investData$longitude, y=investData$latitude,size=investData$amount))

I've been fighting all ay with establishing accounts and enabling APIs with Google, so it's entirely possible I've simply failed to enable something I need to.  I have the geocoding, geolocation, and maps static APIs enabled.

I get the following output at the console

Source : https://maps.googleapis.com/maps/api/staticmap?center=USA&zoom=4&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx
Source : https://maps.googleapis.com/maps/api/geocode/json?address=USA&key=xxx

But I get no plot.

if I simply run

qmap("USA", zoom=4)

I get the map I expect.  But when I try to overlay the investment data I get zilch.  I'm told by the folks who handed this to me that it worked in 2017...

Any idea where I'm going wrong?

Body:
If you are running your script via the source function or with the run command (from inside RStudio) you must explicitly call the print function on your ggplot commands.  For example:

print(USAmap + geom_point(data=investData, aes(x=longitude, y=latitude,size=amount)))

As Camille mentioned, no need for the $ inside the aes


问:
cannot get the relationship data in laravel
this is my function

```<code>public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }
</code>```

newproject model

```<code>public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }
</code>```

it always getting the error

```<code>message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
</code>```

please help my to solve my problem please.

答:
I think it should be something like this,

```<code>public function user()
    {
        return $this->hasOne(User::class,'id' ,'user_id');
    }
</code>```

It means id of users table match with current model's user_id column. And if you have proper naming convention according to laravel then you don't need to pass this extra params.

Laravel hasOne relation

Hope it helps:)

Body:
this is my function

public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }

newproject model

public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }

it always getting the error

message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669

please help my to solve my problem please.

Body:
I think it should be something like this,

public function user()
    {
        return $this->hasOne(User::class,'id' ,'user_id');
    }

It means id of users table match with current model's user_id column. And if you have proper naming convention according to laravel then you don't need to pass this extra params.

Laravel hasOne relation

Hope it helps:)


问:
How do I shift-copy multiple rows from one DOORS module to another DOORS module?

Background

In DOORS, you can select multiple rows of a module by holding down shift, then clicking on multiple rows. The text will then highlight red to signify that you have the rows selected.  You can then either copy, or copy with hierarchy. However, you cannot then paste the resulting rows into another module.

Question

Is there a way to paste multiple selected rows from one DOORS module to another DOORS module?

答:
Yes, This is possible.
Use the inbuilt tool from DOORS to do this. TOOLS-->FUNCTIONS-->COPY OBJECTS
This tool is used from within your DOORS module that has the original objects.

Make sure you have your module open that you want to copy into.

The tool lets you select the target module, just make sure you have it open and have selected the position in the module you want the copied objects to be pasted.

Select the attributes you want to copy across. Use the Copy drop down menu to select how many objects your copying across, e.g. just  the selected ones, all the ones in the view, children, or entire module.

Linking - Your on your own, I haven't used this feature, in the copy tool.

Click OK / Apply.


问:
How to Get Total of Value stored in Object Array - Javascript
I'm trying to get the total price of values entered. It displays like this.

```<code>   Example:
   Name: Chair, Stock: 4, Price: 100
   Name: Chair, Stock: 3, Price: 50
   Name: Table, Stock: 4, Price: 100
</code>```

During the computation, different products should be computed separately and same product names should be computed as one - to be displayed in the  the  Like this.

```<code>chars in total: 550
table in total: 400
Total inventory price: 950
</code>```

I tried many times by calling or filtering, but it doesn't seem to work. Not really sure now what I should do first.
Can you help me?

Here is my html code

```<code>    <div>
        <h3>Part 2</h3>
        <form id="products" onsubmit="inventory(event)" action="#">
            <table>
                <tr>
                    <td>Name</td>
                    <td>: <input type="text" id="productName" required></td>
                </tr>
                <tr>
                    <td>Stocks</td>
                    <td>: <input type="text" id="productStock" required></td>
                </tr>
                <tr>
                    <td>Price</td>
                    <td>: <input type="text" id="prodPrice" required></td>
                </tr>
            </table>
            <input type="Submit" value="Add">
        </form>
        <h4>Product List</h4>
        <div id="inventoryList"></div>
        <input type="button" onclick="compute(event)" value="Calculate for local value for each product">
        <h4>Product Total Value</h4>
        <div id="inventorytotal"></div>
    </div>
</code>```

And here is my Javascript. I only have the code to add the product invetories. I still do not have the compute function yet. I delete my code as i am not sure now where to start.

```<code>var prodInventory = [];
function inventory(e){
    e.preventDefault();

    var products = {
        prodName: document.getElementById('productName').value,
        prodStock: document.getElementById('productStock').value,
        prodPrice: document.getElementById('prodPrice').value
    }

    prodInventory.push(products);
    var myJSON = JSON. stringify(products);
    document.forms[0].reset();

    //Display of Inventory List
    document.getElementById("inventoryList").innerHTML = "";
    for (let x in prodInventory) {
        document.getElementById("inventoryList").innerHTML += "name: " + prodInventory[x].prodName + " , " + "stocks : " +  prodInventory[x].prodStock + " , " + "price: " + prodInventory[x].prodPrice + "<br>";
        console.log(prodInventory)
    }
</code>```

答:
this will be your js code

```<code>var prodInventory = [];
    function inventory(){

        var products = {
            prodName: document.getElementById('productName').value,
            prodStock: document.getElementById('productStock').value,
            prodPrice: parseInt(document.getElementById('prodPrice').value)
        }

        prodInventory.push(products);
        var myJSON = JSON. stringify(products);
        document.forms[0].reset();

        //Display of Inventory List
        document.getElementById("inventoryList").innerHTML = "";
        for (let x in prodInventory) {
            document.getElementById("inventoryList").innerHTML += "name: " + prodInventory[x].prodName + " , " + "stocks : " +  prodInventory[x].prodStock + " , " + "price: " + prodInventory[x].prodPrice + "<br>";
            console.log(prodInventory)
        }

        return false;
    }

    function compute() {
        document.getElementById("inventorytotal").innerHTML = "";
        var sum = 0;
        for (let x in prodInventory) {
            sum += prodInventory[x].prodPrice;
            document.getElementById("inventorytotal").innerHTML = sum;
            console.log(prodInventory)
        }
    }
</code>```

and your HTML code

```<code><div>
                            <h3>Part 2</h3>
                            <form id="products" onsubmit="inventory()" action="#">
                                <table>
                                    <tr>
                                        <td>Name</td>
                                        <td>: <input type="text" id="productName" required></td>
                                    </tr>
                                    <tr>
                                        <td>Stocks</td>
                                        <td>: <input type="text" id="productStock" required></td>
                                    </tr>
                                    <tr>
                                        <td>Price</td>
                                        <td>: <input type="text" id="prodPrice" required></td>
                                    </tr>
                                </table>
                                <input type="Submit" value="Add">
                            </form>
                            <h4>Product List</h4>
                            <div id="inventoryList"></div>
                            <input type="button" onclick="compute()"
                                value="Calculate for local value for each product">
                            <h4>Product Total Value</h4>
                            <div id="inventorytotal"></div>
                        </div>
</code>```

First you need to convert the price value to integer because

```<code>document.getElement*("").value
</code>```

gives you string, but you have to add the values. In this case you nedd to convert the string to integer using

```<code>parseInt(string)
</code>```

or

```<code>Number(string)
</code>```

or

```<code>parseFloat(string)
</code>```

You just have to declare a "sum" variable and then add the values of arrayin for loop. This is how you can get the sum of all items

Body:
I'm trying to get the total price of values entered. It displays like this.

   Example:
   Name: Chair, Stock: 4, Price: 100
   Name: Chair, Stock: 3, Price: 50
   Name: Table, Stock: 4, Price: 100

During the computation, different products should be computed separately and same product names should be computed as one - to be displayed in the  the  Like this.

chars in total: 550
table in total: 400
Total inventory price: 950

I tried many times by calling or filtering, but it doesn't seem to work. Not really sure now what I should do first.
Can you help me?

Here is my html code

Part 2

        <form id="products" onsubmit="inventory(event)" action="#">

                    Name
                    : <input type="text" id="productName" required>

                    Stocks
                    : <input type="text" id="productStock" required>

                    Price
                    : <input type="text" id="prodPrice" required>

            <input type="Submit" value="Add">
        </form>

Product List

        <input type="button" onclick="compute(event)" value="Calculate for local value for each product">

Product Total Value

And here is my Javascript. I only have the code to add the product invetories. I still do not have the compute function yet. I delete my code as i am not sure now where to start.

var prodInventory = [];
function inventory(e){
    e.preventDefault();

    var products = {
        prodName: document.getElementById('productName').value,
        prodStock: document.getElementById('productStock').value,
        prodPrice: document.getElementById('prodPrice').value
    }

    prodInventory.push(products);
    var myJSON = JSON. stringify(products);
    document.forms[0].reset();

    //Display of Inventory List
    document.getElementById("inventoryList").innerHTML = "";
    for (let x in prodInventory) {
        document.getElementById("inventoryList").innerHTML += "name: " + prodInventory[x].prodName + " , " + "stocks : " +  prodInventory[x].prodStock + " , " + "price: " + prodInventory[x].prodPrice + "
";
        console.log(prodInventory)
    }

Body:
this will be your js code

var prodInventory = [];
    function inventory(){

        var products = {
            prodName: document.getElementById('productName').value,
            prodStock: document.getElementById('productStock').value,
            prodPrice: parseInt(document.getElementById('prodPrice').value)
        }

        prodInventory.push(products);
        var myJSON = JSON. stringify(products);
        document.forms[0].reset();

        //Display of Inventory List
        document.getElementById("inventoryList").innerHTML = "";
        for (let x in prodInventory) {
            document.getElementById("inventoryList").innerHTML += "name: " + prodInventory[x].prodName + " , " + "stocks : " +  prodInventory[x].prodStock + " , " + "price: " + prodInventory[x].prodPrice + "<br>";
            console.log(prodInventory)
        }

        return false;
    }

    function compute() {
        document.getElementById("inventorytotal").innerHTML = "";
        var sum = 0;
        for (let x in prodInventory) {
            sum += prodInventory[x].prodPrice;
            document.getElementById("inventorytotal").innerHTML = sum;
            console.log(prodInventory)
        }
    }

and your HTML code

<div>
                            <h3>Part 2</h3>
                            <form id="products" onsubmit="inventory()" action="#">
                                <table>
                                    <tr>
                                        <td>Name</td>
                                        <td>: <input type="text" id="productName" required></td>
                                    </tr>
                                    <tr>
                                        <td>Stocks</td>
                                        <td>: <input type="text" id="productStock" required></td>
                                    </tr>
                                    <tr>
                                        <td>Price</td>
                                        <td>: <input type="text" id="prodPrice" required></td>
                                    </tr>
                                </table>
                                <input type="Submit" value="Add">
                            </form>
                            <h4>Product List</h4>
                            <div id="inventoryList"></div>
                            <input type="button" onclick="compute()"
                                value="Calculate for local value for each product">
                            <h4>Product Total Value</h4>
                            <div id="inventorytotal"></div>
                        </div>

First you need to convert the price value to integer because

document.getElement*("").value

gives you string, but you have to add the values. In this case you nedd to convert the string to integer using

parseInt(string)

or

Number(string)

or

parseFloat(string)

You just have to declare a "sum" variable and then add the values of arrayin for loop. This is how you can get the sum of all items


问:
Function is only reading highest value swift
I am working on this project right now and the goal is to have three buttons, for three different difficulties, that segues to a new ViewController based on which button was pressed. No matter which button I press, it defaults to the hardest mode.

I was thinking that it would be possible to fix it if I was able to use the buttons as outlets but Xcode is only letting me use them as actions, which wouldn't help my case.

```<code>
import UIKit

class numberViewController: UIViewController {

    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var scrollView: UIScrollView!
    var difficulty = String()
    var buttonMessage: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        buttonAction()
        stackView.frame = CGRect(x: 0, y: 0, width: 400, height: 3500)
        scrollView.contentSize = CGSize(width: 400, height: 3500)
    }
    func checkDifficulty() -> Int{
        if difficulty == "easy" {
            return 15
        }
        else if difficulty == "medium"{
            return 45
        }
        else{
            return 105
        }
    }

    @objc func tooLow(sender: UIButton!){
        let alert = UIAlertController(title: "Try again!", message: "Too low!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func tooHigh(sender: UIButton!){
        let alert = UIAlertController(title: "Try again!", message: "Too high!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func justRight(sender: UIButton!){
        let alert = UIAlertController(title: "Congrats! You got it!", message: "Go back and try a harder level.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func buttonAction() {
        var number = Int.random(in: 1...checkDifficulty())
        let buttons = (1...checkDifficulty()).map({ (x) -> UIButton in
            let newButton = UIButton()
            newButton.setTitle("Button \(x)", for: .normal)
            newButton.frame = CGRect(x: 0, y: 0, width: 400, height: 25)
            newButton.backgroundColor = UIColor(displayP3Red: 0.3, green: 0.5, blue: 0.6, alpha: 1)
            if x < number {
                newButton.addTarget(self, action: #selector(tooLow), for: .touchUpInside)
            }
            else if x > number {
                newButton.addTarget(self, action: #selector(tooHigh), for: .touchUpInside)
            }
            else{
                newButton.addTarget(self, action: #selector(justRight), for: .touchUpInside)
            }
            return newButton
        })
        for button in buttons{
            stackView.addArrangedSubview(button)
            let constraint = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: buttons[0], attribute: .height, multiplier: 1, constant: 0)

            if button != buttons[0] {
                stackView.addConstraint(constraint)

            }

        }
    }
}
</code>```

Anything you could think of would help tremendously.

FIXED: Forgot to use prepare for segue to determine what difficulty the player wanted.

答:
Well, you are saying

```<code>var difficulty = String()
</code>```

So now difficulty is "", the empty string. And you never change it. So when the time comes to check its value:

```<code>func checkDifficulty() -> Int{
    if difficulty == "easy" {
        return 15
    }
    else if difficulty == "medium"{
        return 45
    }
    else{
        return 105
    }
}
</code>```

You get the final else case, because difficulty is still "". It is not "easy" or "medium" because you never set it to either of those.

Body:
I am working on this project right now and the goal is to have three buttons, for three different difficulties, that segues to a new ViewController based on which button was pressed. No matter which button I press, it defaults to the hardest mode.

I was thinking that it would be possible to fix it if I was able to use the buttons as outlets but Xcode is only letting me use them as actions, which wouldn't help my case.

import UIKit

class numberViewController: UIViewController {

    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var scrollView: UIScrollView!
    var difficulty = String()
    var buttonMessage: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        buttonAction()
        stackView.frame = CGRect(x: 0, y: 0, width: 400, height: 3500)
        scrollView.contentSize = CGSize(width: 400, height: 3500)
    }
    func checkDifficulty() -> Int{
        if difficulty == "easy" {
            return 15
        }
        else if difficulty == "medium"{
            return 45
        }
        else{
            return 105
        }
    }

    @objc func tooLow(sender: UIButton!){
        let alert = UIAlertController(title: "Try again!", message: "Too low!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func tooHigh(sender: UIButton!){
        let alert = UIAlertController(title: "Try again!", message: "Too high!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func justRight(sender: UIButton!){
        let alert = UIAlertController(title: "Congrats! You got it!", message: "Go back and try a harder level.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default))
        self.present(alert, animated: true, completion: {})
    }
    @objc func buttonAction() {
        var number = Int.random(in: 1...checkDifficulty())
        let buttons = (1...checkDifficulty()).map({ (x) -> UIButton in
            let newButton = UIButton()
            newButton.setTitle("Button \(x)", for: .normal)
            newButton.frame = CGRect(x: 0, y: 0, width: 400, height: 25)
            newButton.backgroundColor = UIColor(displayP3Red: 0.3, green: 0.5, blue: 0.6, alpha: 1)
            if x < number {
                newButton.addTarget(self, action: #selector(tooLow), for: .touchUpInside)
            }
            else if x > number {
                newButton.addTarget(self, action: #selector(tooHigh), for: .touchUpInside)
            }
            else{
                newButton.addTarget(self, action: #selector(justRight), for: .touchUpInside)
            }
            return newButton
        })
        for button in buttons{
            stackView.addArrangedSubview(button)
            let constraint = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: buttons[0], attribute: .height, multiplier: 1, constant: 0)

            if button != buttons[0] {
                stackView.addConstraint(constraint)

            }

        }
    }
}

Anything you could think of would help tremendously.

FIXED: Forgot to use prepare for segue to determine what difficulty the player wanted.

Body:
Well, you are saying

var difficulty = String()

So now difficulty is "", the empty string. And you never change it. So when the time comes to check its value:

func checkDifficulty() -> Int{
    if difficulty == "easy" {
        return 15
    }
    else if difficulty == "medium"{
        return 45
    }
    else{
        return 105
    }
}

You get the final else case, because difficulty is still "". It is not "easy" or "medium" because you never set it to either of those.


问:
Preventing Request Spamming
Scenario

A client application that features a map. The map is an interactive control that upon move/zoom will request tiles (as needed) from a tile server -- a GeoServer in this case. The tile server receives requests for tiles as the user moves around the interactive map. Let us imagine that there is no limit on how many requests the client can make.

Problem

When a user is moving fast, requests to the tile server pile up. The tile server gets bogged down and is not able to provide tiles in a timely fashion.

Additionally, the tile request queue is responded to in request order. So, the user could go from Florida to California and have to wait for Florida tiles to load before seeing any tiles in California.

Questions

How can we improve the perceived performance of the client?

What are some strategies to employ on the client-side to prevent a large amount of requests when panning fast? Zooming fast?

What are some strategies to employ on the server-side to determine if a request is no longer needed or should take lower priority?

Possible Solution

Place a custom proxy in front of the Tile Server such that tiles could be requested with a time-stamp -- later tiles always receiving priority. The proxy could also implement a feature allowing the client application to abandon a request.

Thank you in advance.

答:
I looked at various solutions on stopping image loading. But it seems no one has found a way to stop loading an image when browser has already started downloading it.

So, I can recommend alternative. Browser has a limit of 2 parallel downloads per domain. So, that means you need to load images of different locations from different subdomain so that browser can load multiple locations in parallel.

So, say california images are coming from:

california.yourwebsite.com/images

And florida images from:

florida.yourwebsite.com/images

Moreover, you can use different subdomain for different zoom level so that if images for a certain zoom level are still loading and user chages zoom level, browser can download the new zoom level images immediately.

zoom10.florida.yourwebsite.com/images

For this, you need to create a *.yourwebsite.com DNS mapping to your webserver(s) from your domain panel.

Does this answer your question?

Title: Preventing Request Spamming


问:
How can I use an array across multiple files?
i'm here to ask if I put a variable in my index.js file like this: var allowed = ['id1', 'id2']

Could I use that variable across multiple files (e.g. commands?)`

I tried that in my bot but the console returned the error "allowed" is not defined. Anybody got a solution?

答:
Put the array variable at the top most of your file before defining any functions to make it global (or put it outside all the functions). Global functions can be used by any functions within the javascript file and across multiple files. If a variable is declared within the function, it can only be used within that function.

Example:

```<code>var a;
function f1() {
// a can be used here
}

function f1() {
// a can be used here
}
</code>```

but

```<code>function f1() {
var b;
// b can only be used inside this function only
}
</code>```

Body:
Put the array variable at the top most of your file before defining any functions to make it global (or put it outside all the functions). Global functions can be used by any functions within the javascript file and across multiple files. If a variable is declared within the function, it can only be used within that function.

Example:

var a;
function f1() {
// a can be used here
}

function f1() {
// a can be used here
}

but

function f1() {
var b;
// b can only be used inside this function only
}


问:
python itertools product with steps
Currently, I have a NumPy array:

```<code>a = np.array([[1,2],[3,4],[5,6]])
</code>```

And I am doing the product operation in itertools, but I want to add a step function.
For example:

```<code>[ x for x in itertools.product(*a) ]
</code>```

Result in:

```<code>[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
</code>```

For the target output with step (1,1,2):

```<code>[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]
</code>```

I can't figure it out, here is the problem.

答:
You can use this code. I think your problem is solve.

import itertools

print(list(itertools.product(*[[1,2],[3,4],[5,6]]))[::2])

Title: python itertools product with steps

Body:
Currently, I have a NumPy array:

a = np.array([[1,2],[3,4],[5,6]])

And I am doing the product operation in itertools, but I want to add a step function.
For example:

[ x for x in itertools.product(*a) ]

Result in:

[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]

For the target output with step (1,1,2):

[(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)]

I can't figure it out, here is the problem.


问:
Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered
I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:

InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.

Repository:

```<code>public interface IBloggerRepository { ... }

public class BloggerRepository : IBloggerRepository { ... }
</code>```

Controller:

```<code>public class BlogController : Controller
{
    private readonly IBloggerRepository _repository;

    public BlogController(BloggerRepository repository)
    {
        _repository = repository;
    }

    public IActionResult Index() { ... }
}
</code>```

Startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddScoped<IBloggerRepository, BloggerRepository>();
}
</code>```

I'm not sure what I'm doing wrong. Any ideas?

答:
I had the same issue and found out that my code was using the injection before it was initialized.

```<code>services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();
</code>```

I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.

Body:
I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:

InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.

Repository:

public interface IBloggerRepository { ... }

public class BloggerRepository : IBloggerRepository { ... }

Controller:

public class BlogController : Controller
{
    private readonly IBloggerRepository _repository;

    public BlogController(BloggerRepository repository)
    {
        _repository = repository;
    }

    public IActionResult Index() { ... }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddScoped<IBloggerRepository, BloggerRepository>();
}

I'm not sure what I'm doing wrong. Any ideas?

Body:
I had the same issue and found out that my code was using the injection before it was initialized.

services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();

I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.


问:
Zoom Function For Chart.js
I have a chart that I want to use the github zoom feature for found here.

I am have wrote the code below which runs error free, but when I try to zoom in and out on my mouse wheel it does not work.

What code needs to be changed so I can zoom in and out using the mouse wheel?

See the below snippet

var ctx = document.getElementById('doughnut-chart').getContext('2d');

new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Day One", "Day Two", "Day Three", "Day Four", "Day Five"],
      datasets: [
        {
          label: "Agi",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", "#6bcd3e"],
          data: ["100", "200", "300", "400", "500" ]
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: "Title"
      }
    },
    pan: {
        enabled: true,
        mode: 'xy'
    },
    zoom: {
        enabled: true,
        mode: 'xy',
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.3"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css">
<canvas id="doughnut-chart" width="800" height="450"></canvas></code>```

EDIT

As suggested in the comments I added a plugin category and the code now reads like the below - but still zoom function is not working.

```<code>   <script type="text/javascript">
   var ctx = document.getElementById('doughnut-chart').getContext('2d');

   new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Day One", "Day Two", "Day Three", "Day Four", "Day Five"],
      datasets: [
        {
          label: "Test",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", "#6bcd3e"],
          data:  ["100", "200", "300", "400", "500" ] ,
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: "Test"
      },
      plugins: {
            zoom: {
                pan: {
                    enabled: true,
                    mode: 'x',
                    speed: 10,
                    threshold: 10
                },
                zoom: {
                    enabled: true,
                    mode: 'y'
                }
             }
          }
       }
    });
  </script>
</code>```

答:
Check this example.
Here is the javascript

```<code>var timeFormat = "MM/DD/YYYY HH:mm";
function randomScalingFactor() {
  return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
}
function randomColorFactor() {
  return Math.round(Math.random() * 255);
}
function randomColor(opacity) {
  return (
    "rgba(" +
    randomColorFactor() +
    "," +
    randomColorFactor() +
    "," +
    randomColorFactor() +
    "," +
    (opacity || ".3") +
    ")"
  );
}
function newDate(days) {
  return moment()
    .add(days, "d")
    .toDate();
}
function newDateString(days) {
  return moment()
    .add(days, "d")
    .format(timeFormat);
}
function newTimestamp(days) {
  return moment()
    .add(days, "d")
    .unix();
}
function resetZoom() {
  window.myLine.resetZoom();
}
var arr = Array.from({length: 3000}, () => Math.floor(Math.random() * 40));
var config = {
  type: "line",
  data: {
    labels: _.range(0,3000,1),
    datasets: [
      {
        label: "My dataset",
        data: arr,
        fill: false,
        borderDash: [5, 5]
      },
    ]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: "Chart.js HUGE data set"
    },
    scales: {
      xAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: "x"
          },
          ticks: {
            maxRotation: 0,
            autoSkip:true,
          }
        }
      ],
      yAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: "value"
          }
        }
      ]
    },
    pan: {
      enabled: true,
      mode: "x",
      speed: 10,
      threshold: 10
    },
    zoom: {
      enabled: true,
      drag: false,
      mode: "xy",
     speed: 0.01,
     // sensitivity: 0.1,
      limits: {
        max: 10,
        min: 0.5
      }
    }
  }
};
config.data.datasets.forEach(function(dataset) {
  dataset.borderColor = randomColor(0.4);
  dataset.backgroundColor = randomColor(0.5);
  dataset.pointBorderColor = randomColor(0.7);
  dataset.pointBackgroundColor = randomColor(0.5);
  dataset.pointBorderWidth = 1;
});
window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myLine = new Chart(ctx, config);
};
</code>```

check the working example here in codepen

Check another example here

javascript is below

```<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        // Container for pan options
        pan: {
            // Boolean to enable panning
            enabled: true,

            // Panning directions. Remove the appropriate direction to disable
            // Eg. 'y' would only allow panning in the y direction
            mode: 'x',

            speed: 1
        },

        // Container for zoom options
        zoom: {
            // Boolean to enable zooming
            enabled: true,
            // Zooming directions. Remove the appropriate direction to disable
            // Eg. 'y' would only allow zooming in the y direction
            mode: 'x',
        }
    }
});

$('#reset_zoom').click(function(){
    myChart.resetZoom();
    console.log(myChart);
});

$('#disable_zoom').click(function(){
    myChart.ctx.canvas.removeEventListener('wheel', myChart._wheelHandler);
});

$('#enable_zoom').click(function(){
    myChart.ctx.canvas.addEventListener('wheel', myChart._wheelHandler);
});
</code>```

check the working example here in jsfiddle

Title: Zoom Function For Chart.js

Body:
I have a chart that I want to use the github zoom feature for found here.

I am have wrote the code below which runs error free, but when I try to zoom in and out on my mouse wheel it does not work.

What code needs to be changed so I can zoom in and out using the mouse wheel?

See the below snippet

var ctx = document.getElementById('doughnut-chart').getContext('2d');

new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ["Day One", "Day Two", "Day Three", "Day Four", "Day Five"],
      datasets: [
        {
          label: "Agi",
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", "#6bcd3e"],
          data: ["100", "200", "300", "400", "500" ]
        }
      ]
    },
    options: {
      title: {
        display: true,
        text: "Title"
      }
    },
    pan: {
        enabled: true,
        mode: 'xy'
    },
    zoom: {
        enabled: true,
        mode: 'xy',
    }
});

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css">
<canvas id="doughnut-chart" width="800" height="450"></canvas>

EDIT

As suggested in the comments I added a plugin category and the code now reads like the below - but still zoom function is not working.

Body:
Check this example.
Here is the javascript

var timeFormat = "MM/DD/YYYY HH:mm";
function randomScalingFactor() {
  return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
}
function randomColorFactor() {
  return Math.round(Math.random() * 255);
}
function randomColor(opacity) {
  return (
    "rgba(" +
    randomColorFactor() +
    "," +
    randomColorFactor() +
    "," +
    randomColorFactor() +
    "," +
    (opacity || ".3") +
    ")"
  );
}
function newDate(days) {
  return moment()
    .add(days, "d")
    .toDate();
}
function newDateString(days) {
  return moment()
    .add(days, "d")
    .format(timeFormat);
}
function newTimestamp(days) {
  return moment()
    .add(days, "d")
    .unix();
}
function resetZoom() {
  window.myLine.resetZoom();
}
var arr = Array.from({length: 3000}, () => Math.floor(Math.random() * 40));
var config = {
  type: "line",
  data: {
    labels: _.range(0,3000,1),
    datasets: [
      {
        label: "My dataset",
        data: arr,
        fill: false,
        borderDash: [5, 5]
      },
    ]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: "Chart.js HUGE data set"
    },
    scales: {
      xAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: "x"
          },
          ticks: {
            maxRotation: 0,
            autoSkip:true,
          }
        }
      ],
      yAxes: [
        {
          scaleLabel: {
            display: true,
            labelString: "value"
          }
        }
      ]
    },
    pan: {
      enabled: true,
      mode: "x",
      speed: 10,
      threshold: 10
    },
    zoom: {
      enabled: true,
      drag: false,
      mode: "xy",
     speed: 0.01,
     // sensitivity: 0.1,
      limits: {
        max: 10,
        min: 0.5
      }
    }
  }
};
config.data.datasets.forEach(function(dataset) {
  dataset.borderColor = randomColor(0.4);
  dataset.backgroundColor = randomColor(0.5);
  dataset.pointBorderColor = randomColor(0.7);
  dataset.pointBackgroundColor = randomColor(0.5);
  dataset.pointBorderWidth = 1;
});
window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myLine = new Chart(ctx, config);
};

check the working example here in codepen

Check another example here

javascript is below

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        // Container for pan options
        pan: {
            // Boolean to enable panning
            enabled: true,

            // Panning directions. Remove the appropriate direction to disable
            // Eg. 'y' would only allow panning in the y direction
            mode: 'x',

            speed: 1
        },

        // Container for zoom options
        zoom: {
            // Boolean to enable zooming
            enabled: true,
            // Zooming directions. Remove the appropriate direction to disable
            // Eg. 'y' would only allow zooming in the y direction
            mode: 'x',
        }
    }
});

$('#reset_zoom').click(function(){
    myChart.resetZoom();
    console.log(myChart);
});

$('#disable_zoom').click(function(){
    myChart.ctx.canvas.removeEventListener('wheel', myChart._wheelHandler);
});

$('#enable_zoom').click(function(){
    myChart.ctx.canvas.addEventListener('wheel', myChart._wheelHandler);
});

check the working example here in jsfiddle