问:
ngShow expression is evaluated too early
I have a angular component and controller that look like this:

```<code>export class MyController{

    static $inject = [MyService.serviceId];

    public elements: Array<string>;
    public errorReceived : boolean;

    private elementsService: MyService;

    constructor(private $elementsService: MyService) {
        this.errorReceived = false;
        this.elementsService= $elementsService;
    }

    public $onInit = () => {
        this.elements =  this.getElements();
        console.log("tiles: " + this.elements);
    }

    private getElements(): Array<string> {
        let result: Array<string> = [];
        this.elementsService.getElements().then((response) => {
            result = response.data;
            console.log(result);
        }).catch(() => {
            this.errorReceived = true;
        });
        console.log(result);
        return result;
    }
}

export class MyComponent implements ng.IComponentOptions {
    static  componentId = 'myId';

    controller = MyController;
    controllerAs = 'vm';

    templateUrl = $partial => $partial.getPath('site.html');
}
</code>```

MyService implementation looks like this:

```<code>export class MyService {

    static serviceId = 'myService';

    private http: ng.IHttpService;

    constructor(private $http: ng.IHttpService) {
        this.http = $http;
    }

    public getElements(): ng.IPromise<{}> {
        return this.http.get('./rest/elements');
    }

}
</code>```

The problem that I face is that the array elements contains an empty array after the call of onInit(). However, later, I see that data was received since the success function in getELements() is called and the elements are written to the console.

elements I used in my template to decide whether a specific element should be shown:

```<code><div>
    <elements ng-show="vm.elements.indexOf('A') != -1"></elements>
</div>
</code>```

The problem now is that vm.elements first contains an empty array, and only later, the array is filled with the actual value. But then this expression in the template has already been evaluated. How can I change that?

答:
Your current implementation doesn't make sense. You need to understand how promises and asynchronous constructs work in this language in order to achieve your goal. Fortunately this isn't too hard.

The problem with your current implementation is that your init method immediately returns an empty array. It doesn't return the result of the service call so the property in your controller is simply bound again to an empty array which is not what you want.

Consider the following instead:

```<code>export class MyController {
   elements: string[] = [];

   $onInit = () => {
     this.getElements()
       .then(elements => {
         this.elements = elements;
       });
  };

  getElements() {
    return this.elementsService
      .getElements()
      .then(response => response.data)
      .catch(() => {
        this.errorReceived = true;
      });
   }
}
</code>```

You can make this more readable by leveraging async/await

```<code>export class MyController {
   elements: string[] = [];

   $onInit = async () => {
     this.elements = await this.getElements();
   };

   async getElements() {
     try {
       const {data} = await this.elementsService.getElements();
       return data;
     }
     catch {
       this.errorReceived = true;
     }
   }
}
</code>```

Notice how the above enables the use of standard try/catch syntax. This is one of the many advantages of async/await.

One more thing worth noting is that your data services should unwrap the response, the data property, and return that so that your controller is not concerned with the semantics of the HTTP service.

Body:
I have a angular component and controller that look like this:

export class MyController{

    static $inject = [MyService.serviceId];

    public elements: Array<string>;
    public errorReceived : boolean;

    private elementsService: MyService;

    constructor(private $elementsService: MyService) {
        this.errorReceived = false;
        this.elementsService= $elementsService;
    }

    public $onInit = () => {
        this.elements =  this.getElements();
        console.log("tiles: " + this.elements);
    }

    private getElements(): Array<string> {
        let result: Array<string> = [];
        this.elementsService.getElements().then((response) => {
            result = response.data;
            console.log(result);
        }).catch(() => {
            this.errorReceived = true;
        });
        console.log(result);
        return result;
    }
}

export class MyComponent implements ng.IComponentOptions {
    static  componentId = 'myId';

    controller = MyController;
    controllerAs = 'vm';

    templateUrl = $partial => $partial.getPath('site.html');
}

MyService implementation looks like this:

export class MyService {

    static serviceId = 'myService';

    private http: ng.IHttpService;

    constructor(private $http: ng.IHttpService) {
        this.http = $http;
    }

    public getElements(): ng.IPromise<{}> {
        return this.http.get('./rest/elements');
    }

}

The problem that I face is that the array elements contains an empty array after the call of onInit(). However, later, I see that data was received since the success function in getELements() is called and the elements are written to the console.

elements I used in my template to decide whether a specific element should be shown:

    <elements ng-show="vm.elements.indexOf('A') != -1"></elements>

The problem now is that vm.elements first contains an empty array, and only later, the array is filled with the actual value. But then this expression in the template has already been evaluated. How can I change that?

Body:
Your current implementation doesn't make sense. You need to understand how promises and asynchronous constructs work in this language in order to achieve your goal. Fortunately this isn't too hard.

The problem with your current implementation is that your init method immediately returns an empty array. It doesn't return the result of the service call so the property in your controller is simply bound again to an empty array which is not what you want.

Consider the following instead:

export class MyController {
   elements: string[] = [];

   $onInit = () => {
     this.getElements()
       .then(elements => {
         this.elements = elements;
       });
  };

  getElements() {
    return this.elementsService
      .getElements()
      .then(response => response.data)
      .catch(() => {
        this.errorReceived = true;
      });
   }
}

You can make this more readable by leveraging async/await

export class MyController {
   elements: string[] = [];

   $onInit = async () => {
     this.elements = await this.getElements();
   };

   async getElements() {
     try {
       const {data} = await this.elementsService.getElements();
       return data;
     }
     catch {
       this.errorReceived = true;
     }
   }
}

Notice how the above enables the use of standard try/catch syntax. This is one of the many advantages of async/await.

One more thing worth noting is that your data services should unwrap the response, the data property, and return that so that your controller is not concerned with the semantics of the HTTP service.


来源: stackexchange

问:
Double pointer addresses
I created and allocated a double pointer like this:

```<code> int **a;
 a = (int**)malloc(10 * sizeof(int *));
 for (int i = 0; i < 10; i++)
     *(a+i) = (int *)malloc(10 * sizeof(int));
</code>```

And then I initialized it for example like this:

```<code>for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        **a = 1;
         (*a)++;
    }
    a++;
 }
</code>```

My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.

答:
Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:</p>

```<code> int rows = 10, cols = 10
 int **a;
 // don't cast the return value of malloc
 a = malloc(rows * sizeof(*a));
 for (int i = 0; i < rows; i++)
     a[i] = malloc(cols * sizeof(**a));

...

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        a[i][j] = 1;
    }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Double pointer addresses

Body:
I created and allocated a double pointer like this:

 int **a;
 a = (int**)malloc(10 * sizeof(int *));
 for (int i = 0; i < 10; i++)
     *(a+i) = (int *)malloc(10 * sizeof(int));

And then I initialized it for example like this:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        **a = 1;
         (*a)++;
    }
    a++;
 }

My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.

Body:
Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:

 int rows = 10, cols = 10
 int **a;
 // don't cast the return value of malloc
 a = malloc(rows * sizeof(*a));
 for (int i = 0; i < rows; i++)
     a[i] = malloc(cols * sizeof(**a));

...

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        a[i][j] = 1;
    }
 }

ContentLicense: CC BY-SA 3.0


问:
In Java, do methods that don't use static or class variables need to be synchronized?
Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?</p>

答:
Does methods that only use local variables inside, do not suffer any threading issues ?

True in a very simplistic sense, but lets be clear - I think this is only true if:

such a method uses only local variables that are primitives or references to mutable instances that cannot otherwise be accessed outside the method by any other means.

such a method invokes only methods that are thread-safe.

Some ways these rules could be violated:

A local variable could be initialized to point to an object that is also accessible outside the method.  For example, a local variable could point to a singleton (Foo bar = Foo.getSingleton()).

A local instance held by a local variable could "leak" if the instance is passed as a argument to an external method that keeps a reference to the instance.

A class with no instance variables and with only a single method with no local variables could still call the static method of another class that is not thread-safe.


问:
How do I use RxJS to process hundreds of requests without crashing?

I need to process 400+ employee objects which involves calling an observable service method for each one.

I need to know when all employees have been processed, and, I need to find a way of doing this which does not cause my client or server to be overloaded with simultaneous requests - that's what's happening at the moment.

I want to gather the results of each employee's processing into to an array from which I can further work with the data (I'm creating an export file).

I have been trying RxJS concat and forkjoin but I still seem to have 400+ tasks all firing off at the same time.

I read this page about concat which suggests that the processing is handled one-at-a-time, (like a queue at an ATM) but I'm not convinced - again my browser hung and the number of network requests suggested all-at-the-same-time to me.

If I could get the code to process one employee at a time and finish before handling the next employee in the list, that would be just fine.

```<code>processEmployees(): AsyncSubject<boolean> {
    let employeesProcessed: AsyncSubject<boolean> = new AsyncSubject<boolean>();
    let listOfProcessesToRun = [];

    this.employeeProfilesList.forEach(
        (employeeProfile: EmployeeProfile) => {
            listOfProcessesToRun.push(
                this.annualLeaveCalculationService.startProcess(employeeProfile, this.yearToProcess).delay(2000)
            );
        }
    )

    Observable.concat(listOfProcessesToRun)
        .finally(() => {
        })
        .subscribe(
        (calculationResults: AnnualLeaveCalculationResults) => {
            this.calculationResults.push(calculationResults);
            employeesProcessed.complete();
        },
        error => {
        });

    return employeesProcessed;
}
</code>```

I have tried using Observable.forkjoin to process an array of observables, but I believe that the requests are handled in parallel, and that resulted in my machine hanging due to there being some 400 employees to process.

I have considered a nested solution, e.g.

```<code>processemployee(X) {
    doServiceCall(this.employees[x])
    .subscribe( response => {
            processemployee(++x); // with a check to detect number of loops
        }
    );
}
</code>```

but I'm not sure that's a great pattern.

答:
I recently step into a sort of similar problem, if I understand correctly this one.

I had thousands of requests to process in parallel. The number was too high and the whole thing collapsed.

I was pointed then to use a combination of bufferCount() and concatMap() operators to achieve what I wanted.

bufferCount() divide the original stream in chunks, all containing
the same number of elements

concatMap() elaborates the first chunk (in parallel) via a function
passed as argument - the function returns an Observable - when the
Observable completes, then the second chunk is taken and so on

Maybe this approach can help.

Body:
I need to process 400+ employee objects which involves calling an observable service method for each one.

I need to know when all employees have been processed, and, I need to find a way of doing this which does not cause my client or server to be overloaded with simultaneous requests - that's what's happening at the moment.

I want to gather the results of each employee's processing into to an array from which I can further work with the data (I'm creating an export file).

I have been trying RxJS concat and forkjoin but I still seem to have 400+ tasks all firing off at the same time.

I read this page about concat which suggests that the processing is handled one-at-a-time, (like a queue at an ATM) but I'm not convinced - again my browser hung and the number of network requests suggested all-at-the-same-time to me.

If I could get the code to process one employee at a time and finish before handling the next employee in the list, that would be just fine.

processEmployees(): AsyncSubject<boolean> {
    let employeesProcessed: AsyncSubject<boolean> = new AsyncSubject<boolean>();
    let listOfProcessesToRun = [];

    this.employeeProfilesList.forEach(
        (employeeProfile: EmployeeProfile) => {
            listOfProcessesToRun.push(
                this.annualLeaveCalculationService.startProcess(employeeProfile, this.yearToProcess).delay(2000)
            );
        }
    )

    Observable.concat(listOfProcessesToRun)
        .finally(() => {
        })
        .subscribe(
        (calculationResults: AnnualLeaveCalculationResults) => {
            this.calculationResults.push(calculationResults);
            employeesProcessed.complete();
        },
        error => {
        });

    return employeesProcessed;
}

I have tried using Observable.forkjoin to process an array of observables, but I believe that the requests are handled in parallel, and that resulted in my machine hanging due to there being some 400 employees to process.

I have considered a nested solution, e.g.

processemployee(X) {
    doServiceCall(this.employees[x])
    .subscribe( response => {
            processemployee(++x); // with a check to detect number of loops
        }
    );
}

but I'm not sure that's a great pattern.


问:
body::after pseudo element issue
In my css. . .

```<code>body {
    visibility:hidden;
}

body::after {
    visibility:visible;
    background-color:yellow;
}
</code>```

The ::after pseudo has no effect.  Am I making an error that I don't see, or is something wrong with the implementation in Firefox, Chrome?

答:
See this fiddle and play around with it to see what attributes are necessary:

body {
  visibility: hidden;
}

body::after {
  visibility: visible;
  display: block;
  width: 50px;
  height: 50px;
  content: '';
  background-color: #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
</body></code>```

Title: body::after pseudo element issue

Body:
In my css. . .

body {
    visibility:hidden;
}

body::after {
    visibility:visible;
    background-color:yellow;
}

The ::after pseudo has no effect.  Am I making an error that I don't see, or is something wrong with the implementation in Firefox, Chrome?

Body:
See this fiddle and play around with it to see what attributes are necessary:

body {
  visibility: hidden;
}

body::after {
  visibility: visible;
  display: block;
  width: 50px;
  height: 50px;
  content: '';
  background-color: #000;
}

<body>
</body>


问:
ifelse() and conditionally pasting column names across a data frame
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

```<code>     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )
</code>```

desired outcome (dfgoal):

```<code> dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )
</code>```

current code:

```<code>sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))
</code>```

答:
You are doing a few things wrong in the sapply. First in the ifelse it should be "y" not y because it is not a variable, second the paste0 should be replace with paste and collaps = ",",third sapply(df won't work properly because sapply will run over the columns and not the rows as you want.

This is how i did it:

```<code>overall = sapply(1:nrow(df), function(x) ifelse(length(colnames(df)[which(df[x,] == "y")])!=0,paste(colnames(df)[which(df[x,] == "y")], collapse = ","),"n"))
cbind(df,new_colum)
</code>```

Body:
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )

desired outcome (dfgoal):

 dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )

current code:

sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))

Body:
You are doing a few things wrong in the sapply. First in the ifelse it should be "y" not y because it is not a variable, second the paste0 should be replace with paste and collaps = ",",third sapply(df won't work properly because sapply will run over the columns and not the rows as you want.

This is how i did it:

overall = sapply(1:nrow(df), function(x) ifelse(length(colnames(df)[which(df[x,] == "y")])!=0,paste(colnames(df)[which(df[x,] == "y")], collapse = ","),"n"))
cbind(df,new_colum)


问:
Map shift-tab in vim to inverse tab in Vim
I've done some searching and found a wealth of information on binding keys in vim, but I can't find out, for sure, how to map shift-tab. Or what command I need to map it to for it to "tab backwards".

This is what I have at the moment:

```<code>map <S-tab> <S-,><S-,>
</code>```

Possibly Relevant Information:
I'm running Debian with Terminal 2.22.3. with VIM - Vi IMproved 7.1

答:
Vim already has built-in key commands for insert mode to shift the current line left or right one &shiftwidth. They are (in insert mode):

Ctrl-t : shift right (mnemonic "tab")

Ctrl-d : shift left (mnemonic "de-tab")

If you still want to use shift-tab, this is how you do it:

```<code>" for command mode
nnoremap <S-Tab> <<
" for insert mode
inoremap <S-Tab> <C-d>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've done some searching and found a wealth of information on binding keys in vim, but I can't find out, for sure, how to map shift-tab. Or what command I need to map it to for it to "tab backwards".

This is what I have at the moment:

map <S-tab> <S-,><S-,>

Possibly Relevant Information:
I'm running Debian with Terminal 2.22.3. with VIM - Vi IMproved 7.1

Body:
Vim already has built-in key commands for insert mode to shift the current line left or right one &shiftwidth. They are (in insert mode):

Ctrl-t : shift right (mnemonic "tab")

Ctrl-d : shift left (mnemonic "de-tab")

If you still want to use shift-tab, this is how you do it:

" for command mode
nnoremap <S-Tab> <<
" for insert mode
inoremap <S-Tab> <C-d>


问:
not generic Error in Java HashMap
I am getting the below error for HashMap in the Java code.

Error - "The type HashMap is not generic; it cannot be parameterized with arguments <>"

```<code>package com.example.map;

import java.util.Map;
import java.util.HashMap;

public class HashMap {

    public static void main(String[] args) {
        // compilation error here                vvvvvvv
        Map<Integer, String> mapHttpErrors = new HashMap<>();

        mapHttpErrors.put(200, "OK");
        mapHttpErrors.put(303, "See Other");
        mapHttpErrors.put(404, "Not Found");
        mapHttpErrors.put(500, "Internal Server Error");

        System.out.println(mapHttpErrors);

    }

}
</code>```

答:
You have named your own class HashMap as well.

When you write new HashMap the compiler thinks you're referring to your own class which indeed does not specify any generic parameters.

You can (and in fact: should) either change the name of your class to something else or explicitly refer to java.util.HashMap in your code:

```<code>Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();
</code>```

Title: not generic Error in Java HashMap

Body:
I am getting the below error for HashMap in the Java code.

Error - "The type HashMap is not generic; it cannot be parameterized with arguments <>"

package com.example.map;

import java.util.Map;
import java.util.HashMap;

public class HashMap {

    public static void main(String[] args) {
        // compilation error here                vvvvvvv
        Map<Integer, String> mapHttpErrors = new HashMap<>();

        mapHttpErrors.put(200, "OK");
        mapHttpErrors.put(303, "See Other");
        mapHttpErrors.put(404, "Not Found");
        mapHttpErrors.put(500, "Internal Server Error");

        System.out.println(mapHttpErrors);

    }

}

Body:
You have named your own class HashMap as well.

When you write new HashMap the compiler thinks you're referring to your own class which indeed does not specify any generic parameters.

You can (and in fact: should) either change the name of your class to something else or explicitly refer to java.util.HashMap in your code:

Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();


问:
Using a string as variable
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.

```<code>for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])
</code>```

I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.

Thanks in advance

答:
You are trying to do this:

```<code>test1 = something
test2 = something else

for i in range(1,2):
    print('test' + str(i))
</code>```

however, that won't work because strings cannot be used as variable names.  You can cheat somewhat by using locals(), which creates a dictionary of local variables:

```<code>test1 = something
test2 = something else

for i in range(1,2):
    print(locals()['test' + str(i)])
</code>```

but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.

```<code>d = {'test1': something,
     'test2': something else}

for i in range(1,2):
    print(d['test' + str(i)])

# or even better
tests = [something, something else]
for test in tests:
    print(test)

# even better, what you're trying to do is this:
for i, test in enumerate(tests):
    period_writer.writerow([i+1, max(test)])
</code>```

This makes it much clearer that the variables belong together and will run faster to boot.

Title: Using a string as variable

Body:
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.

for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])

I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.

Thanks in advance

Body:
You are trying to do this:

test1 = something
test2 = something else

for i in range(1,2):
    print('test' + str(i))

however, that won't work because strings cannot be used as variable names.  You can cheat somewhat by using locals(), which creates a dictionary of local variables:

test1 = something
test2 = something else

for i in range(1,2):
    print(locals()['test' + str(i)])

but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.

d = {'test1': something,
     'test2': something else}

for i in range(1,2):
    print(d['test' + str(i)])

# or even better
tests = [something, something else]
for test in tests:
    print(test)

# even better, what you're trying to do is this:
for i, test in enumerate(tests):
    period_writer.writerow([i+1, max(test)])

This makes it much clearer that the variables belong together and will run faster to boot.


问:
Plot Discrete Distribution using np.linspace()
I'm trying to plot a simple discrete distribution using matplotlib:

If -1<=x<0, p=0.3;

If 0<=x<1, p=0.5;

If 1<=x<=2, p=0.2.

How can I start from x = np.linspace(-1, 2)?

What I tried so far is:

```<code>def mapDiscProb(x):
    if np.any(x < 0):
        return 0.3 + x * 0
    elif np.any(x >= 1):
        return 0.2 + x * 0
    else:
        return 0.5 + x * 0

x = np.linspace(-1, 2)
y = mapDiscProb(x4)

ax.plot(x, y, clip_on = False)
</code>```

And the outcome is just a whole line at 0.3 from -1 to 2 as if the     elif and     else are not excuted.

My expected output is three disconnected horizontal lines, as is standard for a discrete pmf.

答:
If you just want to do it for that example, this should work

```<code>import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(-1,2)
plt.plot(x[x < 0], 0.3 + x[x < 0]*0, color='blue')
plt.plot(x[(x >= 0) & (x <= 1)], 0.5 + x[(x>=0) & (x<=1)]*0, color='blue')
plt.plot(x[x > 1],0.2 + x[x > 1]*0, color='blue')
plt.show()
</code>```

masking is my way to go when it comes to discrete functions.

Body:
I'm trying to plot a simple discrete distribution using matplotlib:

If -1<=x<0, p=0.3;

If 0<=x<1, p=0.5;

If 1<=x<=2, p=0.2.

How can I start from x = np.linspace(-1, 2)?

What I tried so far is:

def mapDiscProb(x):
    if np.any(x < 0):
        return 0.3 + x * 0
    elif np.any(x >= 1):
        return 0.2 + x * 0
    else:
        return 0.5 + x * 0

x = np.linspace(-1, 2)
y = mapDiscProb(x4)

ax.plot(x, y, clip_on = False)

And the outcome is just a whole line at 0.3 from -1 to 2 as if the     elif and     else are not excuted.

My expected output is three disconnected horizontal lines, as is standard for a discrete pmf.

Body:
If you just want to do it for that example, this should work

import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(-1,2)
plt.plot(x[x < 0], 0.3 + x[x < 0]*0, color='blue')
plt.plot(x[(x >= 0) & (x <= 1)], 0.5 + x[(x>=0) & (x<=1)]*0, color='blue')
plt.plot(x[x > 1],0.2 + x[x > 1]*0, color='blue')
plt.show()

masking is my way to go when it comes to discrete functions.


问:
Sending notifications to your Friends in Pinax, Django
Currently, I am sending notifications to all Users in the database. How can I get the list of all my friends, so then notifications would be sent to all my friends?</p>

```<code>if new and notification:
    notification.send(User.objects.all().exclude(id=self.owner.id),
                "listing_new",
                {'listing':self, },
            )
</code>```

答:
You can try:</p>

```<code>from friends.models import Friendship
if new and notification:
    notification.send(Friendship.objects.friends_for_user(self.owner.id), "listing_new", {'listing':self, }, )
</code>```

Body:
Currently, I am sending notifications to all Users in the database. How can I get the list of all my friends, so then notifications would be sent to all my friends?

if new and notification:
    notification.send(User.objects.all().exclude(id=self.owner.id),
                "listing_new",
                {'listing':self, },
            )

Body:
You can try:

from friends.models import Friendship
if new and notification:
    notification.send(Friendship.objects.friends_for_user(self.owner.id), "listing_new", {'listing':self, }, )


答:
In a one-liner:

```<code>dfgoal <- cbind.data.frame(
    df,
    overall = apply(df, 1, function(x)
        paste(colnames(df[-1])[x[2:length(x)] == "y"], collapse = ", ")))
dfgoal;
#  student maths English geography history art Spanish physics chemistry
#1       1     y       n         y       n   n       n       n         n
#2       2     n       y         n       n   n       n       n         n
#3       3     n       n         n       n   n       n       n         n
#4       4     n       n         n       n   n       n       n         n
#5       5     n       n         n       n   n       n       y         y
#             overall
#1   maths, geography
#2            English
#3
#4
#5 physics, chemistry
</code>```

If you also want to replace the empty strings with "n", you can do

```<code>levels(dfgoal$overall)[levels(dfgoal$overall) == ""] <- "n";
</code>```

Title: ifelse() and conditionally pasting column names across a data frame

Body:
In a one-liner:

dfgoal <- cbind.data.frame(
    df,
    overall = apply(df, 1, function(x)
        paste(colnames(df[-1])[x[2:length(x)] == "y"], collapse = ", ")))
dfgoal;
#  student maths English geography history art Spanish physics chemistry
#1       1     y       n         y       n   n       n       n         n
#2       2     n       y         n       n   n       n       n         n
#3       3     n       n         n       n   n       n       n         n
#4       4     n       n         n       n   n       n       n         n
#5       5     n       n         n       n   n       n       y         y
#             overall
#1   maths, geography
#2            English
#3
#4
#5 physics, chemistry

If you also want to replace the empty strings with "n", you can do

levels(dfgoal$overall)[levels(dfgoal$overall) == ""] <- "n";


问:
Delete regex matches within loop and continue with updated string version
I have a string that I want to run through four wordlists, one with four-grams, one with tri-grams, one with bigrams and one with single terms. To avoid that a word of the single term wordlist gets counted twice when it also forms part of a bigram or trigrams for example, I start with counting for four-grams, then want to update the string in terms of removing the matches to only check the remaining part of the string for matches of trigrams, bigrams and single terms, respectively. I have used the following code and illustrate it here just starting with fourgrams and then trigrams:

```<code>financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
def clean_text1(pattern_fourgrams, new_strn):
    for r in pattern_fourgrams:
        new_strn = re.sub(r, '', new_strn)
    return new_strn

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
def clean_text2(pattern_trigrams, new_strn1):
    for r in pattern_trigrams:
        new_strn1 = re.sub(r, '', new_strn1)
    return new_strn1

print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)
</code>```

For fourgrams there is not match, so new_strn will be similar to strn. However, there is one match with trigrams ("chief financial officer"), however, I do not succees in deleteing the match from new_strn1. Instead, I again yield the full string, namely strn (or new_strn which is the same).

Could someone help me find the mistake here?

答:
(As a complement to Tilak Putta's answer)

Note that you are searching the string twice: once when counting the occurrences of the ngrams with .count() and once more when you remove the matches using re.sub().

You can increase performance by counting and removing at the same time.

This can be done using re.subn. This function takes the same parameters as re.sub but returns a tuple containing the cleaned string as well as the number of matches.

Example:

```<code>for i in pattern_fourgrams:
    new_strn, n = re.subn(r, '', new_strn)
    financial_fourgrams_count += n
</code>```

Note that this assumes the n-grams are pairwaise different (for fixed n), i.e. they shouldn't have a common word, since subn will delete that word the firs time it sees it and thus won't be able to find occurence of other ngrams containing that particular word.

Body:
I have a string that I want to run through four wordlists, one with four-grams, one with tri-grams, one with bigrams and one with single terms. To avoid that a word of the single term wordlist gets counted twice when it also forms part of a bigram or trigrams for example, I start with counting for four-grams, then want to update the string in terms of removing the matches to only check the remaining part of the string for matches of trigrams, bigrams and single terms, respectively. I have used the following code and illustrate it here just starting with fourgrams and then trigrams:

financial_trigrams_count=0
financial_fourgrams_count=0

strn="thank you, john, and good morning, everyone. with me today is tim, our chief financial officer."

pattern_fourgrams=["value to the business", "car and truck sales"]
pattern_trigrams=["cash flow statement", "chief financial officer"]

for i in pattern_fourgrams:
    financial_fourgrams_count=financial_fourgrams_count+strn.count(i)

new_strn=strn
def clean_text1(pattern_fourgrams, new_strn):
    for r in pattern_fourgrams:
        new_strn = re.sub(r, '', new_strn)
    return new_strn

for i in pattern_trigrams:
    financial_trigrams_count=financial_trigrams_count+new_strn.count(i)

new_strn1=new_strn
def clean_text2(pattern_trigrams, new_strn1):
    for r in pattern_trigrams:
        new_strn1 = re.sub(r, '', new_strn1)
    return new_strn1

print(financial_fourgrams_count)
print(financial_trigrams_count)
word_count_wostop=len(strn.split())
print(word_count_wostop)

For fourgrams there is not match, so new_strn will be similar to strn. However, there is one match with trigrams ("chief financial officer"), however, I do not succees in deleteing the match from new_strn1. Instead, I again yield the full string, namely strn (or new_strn which is the same).

Could someone help me find the mistake here?

Body:
(As a complement to Tilak Putta's answer)

Note that you are searching the string twice: once when counting the occurrences of the ngrams with .count() and once more when you remove the matches using re.sub().

You can increase performance by counting and removing at the same time.

This can be done using re.subn. This function takes the same parameters as re.sub but returns a tuple containing the cleaned string as well as the number of matches.

Example:

for i in pattern_fourgrams:
    new_strn, n = re.subn(r, '', new_strn)
    financial_fourgrams_count += n

Note that this assumes the n-grams are pairwaise different (for fixed n), i.e. they shouldn't have a common word, since subn will delete that word the firs time it sees it and thus won't be able to find occurence of other ngrams containing that particular word.


问:
Lambda expressions in JSP files will not compile
I've tried most of the suggestions mentioned on stackoverflow but haven't come across a solution yet. The error I'm being presented with is the following.

```<code>An error occurred at line: 379 in the jsp file: /application-new-project_process.jsp
Lambda expressions are allowed only at source level 1.8 or above
</code>```

I'm using IntelliJ IDEA 2016.2 and have applied these settings.

Project Structure → Project, Project SDK to 1.8 (java version "1.8.0_102")

Project Structure → Project, Project Language Level to 8.0 - Lambdas, type annotations etc.

Settings → Build, Execution, Deployment → Compiler → Java Compiler, Project bytecode version to 1.8

Settings → Build, Execution, Deployment → Compiler → Java Compiler, Target bytecode version to 1.8

I'm using Tomcat v8.0.36 and have the following for JSP servlets.

```<code><servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>compiler</param-name>
        <param-value>modern</param-value>
    </init-param>
    <init-param>
        <param-name>compilerSourceVM</param-name>
        <param-value>1.8</param-value>
    </init-param>
    <init-param>
        <param-name>compilerTargetVM</param-name>
        <param-value>1.8</param-value>
    </init-param>
    <init-param>
        <param-name>suppressSmap</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
</code>```

Any suggestions will be greatly appreciated!

答:
An updated answer for those using Spring Boot and Tomcat. Since there is no XML configuration file for Tomcat in Spring Boot/MVC, I adapted code linked from these spring docs to create a customizer bean in my base Application class. Fixes problems caused by using Java 8 syntax in JSPs in both  IntelliJ and Gradle CLI.

If you use Spring 1.x, add a EmbeddedServletContainerCustomizer bean:

```<code>@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return (ConfigurableEmbeddedServletContainer container) -> {
        TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
        JspServlet servlet = tomcat.getJspServlet();
        Map<String, String> jspServletInitParams = servlet.getInitParameters();
        jspServletInitParams.put("compilerSourceVM", "1.8");
        jspServletInitParams.put("compilerTargetVM", "1.8");
        servlet.setInitParameters(jspServletInitParams);
    };
}
</code>```

If you use Spring 2.x, add a WebServerFactoryCustomizer bean:

```<code>@Bean
public WebServerFactoryCustomizer containerCustomizer() {
    return (WebServerFactoryCustomizer<TomcatServletWebServerFactory>) factory -> {
        Map<String, String> jspServletInitParams = factory.getInitParameters();
        jspServletInitParams.put("compilerSourceVM", "1.8");
        jspServletInitParams.put("compilerTargetVM", "1.8");
        factory.getJsp().setInitParameters(jspServletInitParams);
    };
}
</code>```

Body:
I've tried most of the suggestions mentioned on stackoverflow but haven't come across a solution yet. The error I'm being presented with is the following.

An error occurred at line: 379 in the jsp file: /application-new-project_process.jsp
Lambda expressions are allowed only at source level 1.8 or above

I'm using IntelliJ IDEA 2016.2 and have applied these settings.

Project Structure → Project, Project SDK to 1.8 (java version "1.8.0_102")

Project Structure → Project, Project Language Level to 8.0 - Lambdas, type annotations etc.

Settings → Build, Execution, Deployment → Compiler → Java Compiler, Project bytecode version to 1.8

Settings → Build, Execution, Deployment → Compiler → Java Compiler, Target bytecode version to 1.8

I'm using Tomcat v8.0.36 and have the following for JSP servlets.

<servlet>
    <servlet-name>jsp</servlet-name>
    <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
        <param-name>fork</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>xpoweredBy</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>compiler</param-name>
        <param-value>modern</param-value>
    </init-param>
    <init-param>
        <param-name>compilerSourceVM</param-name>
        <param-value>1.8</param-value>
    </init-param>
    <init-param>
        <param-name>compilerTargetVM</param-name>
        <param-value>1.8</param-value>
    </init-param>
    <init-param>
        <param-name>suppressSmap</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>

Any suggestions will be greatly appreciated!

Body:
An updated answer for those using Spring Boot and Tomcat. Since there is no XML configuration file for Tomcat in Spring Boot/MVC, I adapted code linked from these spring docs to create a customizer bean in my base Application class. Fixes problems caused by using Java 8 syntax in JSPs in both  IntelliJ and Gradle CLI.

If you use Spring 1.x, add a EmbeddedServletContainerCustomizer bean:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return (ConfigurableEmbeddedServletContainer container) -> {
        TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
        JspServlet servlet = tomcat.getJspServlet();
        Map<String, String> jspServletInitParams = servlet.getInitParameters();
        jspServletInitParams.put("compilerSourceVM", "1.8");
        jspServletInitParams.put("compilerTargetVM", "1.8");
        servlet.setInitParameters(jspServletInitParams);
    };
}

If you use Spring 2.x, add a WebServerFactoryCustomizer bean:

@Bean
public WebServerFactoryCustomizer containerCustomizer() {
    return (WebServerFactoryCustomizer<TomcatServletWebServerFactory>) factory -> {
        Map<String, String> jspServletInitParams = factory.getInitParameters();
        jspServletInitParams.put("compilerSourceVM", "1.8");
        jspServletInitParams.put("compilerTargetVM", "1.8");
        factory.getJsp().setInitParameters(jspServletInitParams);
    };
}


问:
Authenticate client id and client secret on Spring oauth/token request with LDAP

I'm investigating how the client id and client secret can be authenticated with LDAP.

Note: this Kotlin code...

```<code>@Configuration
@EnableAuthorizationServer
class OAuth2AuthorizationServerConfig() : AuthorizationServerConfigurerAdapter() {
</code>```

I'm relatively new to Spring and it seems that this is not something I should be trying to? However, it seems like a useful option. Why? Because it allows me to delegate the client secret management to an LDAP directory and, effectively, allow my ops team to change the secret (in some managed way of coure). With this my application does not need to know the secret. This seems pretty neat?

The oauth end point is basic auth - this seems to be what Spring gives me with the  @EnableAuthorizationServer annotation. Requests to the http://somehost/oauth/token specify grant_type:client_credentials.

I created code to get an arbitrary token (sandbox)...and what I'd like is to just specify the client and scopes that apply to that client and not specify the secret...

```<code>@Throws(Exception::class)
override fun configure(
        clients: ClientDetailsServiceConfigurer
) {
    // Inlining will create a store per credential entry
    val serviceBuilder = clients.inMemory()
    serviceBuilder.withClient("user").secret("test").scopes("XXX")
}
</code>```

I have tried loads of different ideas to add an LDAP Authentication Provider to the managed set of providers in the ProviderManager and thus far have failed. If I debug into the authenticate method at run time I only always have the AnonymousAuthenticationProvider and DaoAuthenticationProvider

The following probably shows my inexperience but here's one example and please read past the probable crazyness - just trying to see if I can inject an LDAPAuthenticationProvider...

```<code>@Autowired
lateinit var providerMan: AuthenticationManager

@Throws(Exception::class)
override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
    (providerMan as ProviderManager).providers.add(0,
            LdapAuthenticationProvider(
                    PasswordComparisonAuthenticator(PasswordPolicyAwareContextSource("ldap://something"))
            )
    )
}
</code>```

Question is therefore fairly simple...
Is there a way to add an LdapAuthenticationProvider such that I can use LDAP to authenticate the client id and client secret?

答: To have client ids and secrets in LDAP, you need an LDAP-based ClientDetailsService implementation, and that does not exist in Spring Security OAuth. Maybe it would be feasible to build that implementation as a bridge to the LDAPAuthenticationProvider, but I am not sure that would be a good idea. In any case, you'd have to build the implementation yourself.

Body:
I'm investigating how the client id and client secret can be authenticated with LDAP.

Note: this Kotlin code...

@Configuration
@EnableAuthorizationServer
class OAuth2AuthorizationServerConfig() : AuthorizationServerConfigurerAdapter() {

I'm relatively new to Spring and it seems that this is not something I should be trying to? However, it seems like a useful option. Why? Because it allows me to delegate the client secret management to an LDAP directory and, effectively, allow my ops team to change the secret (in some managed way of coure). With this my application does not need to know the secret. This seems pretty neat?

The oauth end point is basic auth - this seems to be what Spring gives me with the  @EnableAuthorizationServer annotation. Requests to the http://somehost/oauth/token specify grant_type:client_credentials.

I created code to get an arbitrary token (sandbox)...and what I'd like is to just specify the client and scopes that apply to that client and not specify the secret...

@Throws(Exception::class)
override fun configure(
        clients: ClientDetailsServiceConfigurer
) {
    // Inlining will create a store per credential entry
    val serviceBuilder = clients.inMemory()
    serviceBuilder.withClient("user").secret("test").scopes("XXX")
}

I have tried loads of different ideas to add an LDAP Authentication Provider to the managed set of providers in the ProviderManager and thus far have failed. If I debug into the authenticate method at run time I only always have the AnonymousAuthenticationProvider and DaoAuthenticationProvider

The following probably shows my inexperience but here's one example and please read past the probable crazyness - just trying to see if I can inject an LDAPAuthenticationProvider...

@Autowired
lateinit var providerMan: AuthenticationManager

@Throws(Exception::class)
override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
    (providerMan as ProviderManager).providers.add(0,
            LdapAuthenticationProvider(
                    PasswordComparisonAuthenticator(PasswordPolicyAwareContextSource("ldap://something"))
            )
    )
}

Question is therefore fairly simple...
Is there a way to add an LdapAuthenticationProvider such that I can use LDAP to authenticate the client id and client secret?


答: Return a from a function, save it as a class member, it is just like any other variable. If you want to save the contents of the arrays then do that (but that is not what I could call saving a double pointer -- by the way the usual description is "pointer-to-pointer").</p>

Title: Double pointer addresses

Body:
I created and allocated a double pointer like this:

 int **a;
 a = (int**)malloc(10 * sizeof(int *));
 for (int i = 0; i < 10; i++)
     *(a+i) = (int *)malloc(10 * sizeof(int));

And then I initialized it for example like this:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        **a = 1;
         (*a)++;
    }
    a++;
 }

My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.


问:
How to Setup a Scheme environment to use with Simply Scheme book?
I am working through the book simply scheme (Harvey, Wright). I want to setup an environment that works well with the code in the book and is easy going for beginners.</p>

答:
Easiest in graphical environment:

I suggest you download and install DrRacket. Then when you have opened it install the simply-scheme package like this:

In the File menu choose Package Manager

In the initial tab you put simply-scheme in Package Source and press [Install]

Close the Package Manager window.

If you open Racket documentation in the Help menu it opens a local page and you will have the documentation for the newly installed language under "other language". Search for Simply and you'll find it. As a test it suggests you have this in the definitions window with Determine language from source in the select in the bottom left.

#lang simply-scheme

(se (butlast (bf "this"))
    "world")
; ==> (hi "world")
```

To start a program you press [Run |>]. When run you can do interactions in the same window as the REPL output or you can just add to definitions and run more times.

The IDE highlights your parentheses, ident your code according to convention such that you can realize your errors by pressing CTRL+i after heavy pasting. There is a debugger where you can step through your code and even a macroexpander. Christmas came early!

Alternatives

From looking at the text it seems you can use just about any R5RS implementation with Simply Scheme and just have the load statements and files that come with the book. If graphical IDE is no your cup of tea there are plenty of implementations that work under a shell (racket base included) and you can even use Emacs with many of them if that is your editor.

Body:
Easiest in graphical environment:

I suggest you download and install DrRacket. Then when you have opened it install the simply-scheme package like this:

In the File menu choose Package Manager

In the initial tab you put simply-scheme in Package Source and press [Install]

Close the Package Manager window.

If you open Racket documentation in the Help menu it opens a local page and you will have the documentation for the newly installed language under "other language". Search for Simply and you'll find it. As a test it suggests you have this in the definitions window with Determine language from source in the select in the bottom left.

#lang simply-scheme

(se (butlast (bf "this"))
    "world")
; ==> (hi "world")

To start a program you press [Run |>]. When run you can do interactions in the same window as the REPL output or you can just add to definitions and run more times.

The IDE highlights your parentheses, ident your code according to convention such that you can realize your errors by pressing CTRL+i after heavy pasting. There is a debugger where you can step through your code and even a macroexpander. Christmas came early!

Alternatives

From looking at the text it seems you can use just about any R5RS implementation with Simply Scheme and just have the load statements and files that come with the book. If graphical IDE is no your cup of tea there are plenty of implementations that work under a shell (racket base included) and you can even use Emacs with many of them if that is your editor.


问:
How to sample accelerometer data in the background or on the sleep mode
I have a program which will sample accelerometer data all the time and do some analysis. But I find that when pressing the power button or in the sleep mode, the system will not sample data after a period of time. Does anybody know how to let accelerometer run in the background to collect data?

Thanks a lot!!!

答:
You'll need to set a PARTIAL_WAKE_LOCK which will keep the CPU running and still allow the screen to go off.  Of course, the battery will run down faster.

http://developer.android.com/reference/android/os/PowerManager.html#PARTIAL_WAKE_LOCK


问:
Trying to write `map` using `foldr`
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

```<code>map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs
</code>```

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

答:
foldr is a very general recursive list processing function, because of how it mirrors the structure of the list type it self:

```<code>data [a]        -- a list is either
  = a : [a]     -- a head element, plus a tail list
  | []          -- or an empty list

foldr :: (a -> b -> b)    -- given a handler for a head element and the
                          --   result of processing the tail
      -> b                -- and a "handler" for an empty list
      -> [a]              -- foldr turns a list
      -> b                -- into a single result
</code>```

That might need a bit more unpacking than I could fit in inline comments.

We all know a list has two cases, either a cons cell : containing a single element and the rest of the list, or an empty list containing no information.

Well, the first two parameters to foldr are exactly instructions for how to handle each of these two cases. The a -> b -> b function parameter is the handler for the cons : case. When foldr encounters a cons cell like x : xs it will call the handler with x as the first argument, which fits type a. The second argument it passes to the handler is not the rest of the list xs, but the result of foldr processing xs - remembering that foldr ultimately turns a list into a b, that fits the second parameter of the a -> b -> b type.

The "handler" for the empty list case is much simpler; since an empty list contains no more information, we don't need a function that can transform the information inside an empty list into a b, we can just use a b value as the result immediately.

Because of this mirrored structure, a lot of recursive functions can be implemented by calling foldr with appropriate arguments. The exam question is certainly asking you to make use of this and implement map in terms of foldr without using recursion; the recursion inside foldr is enough.

So your answer must look like this:

```<code>map f xs = foldr _ _ xs
</code>```

You don't need to use multiple cases to handle an empty list or a cons cell; we handle those cases by the two arguments we give to foldr. The empty list case is obvious, since map f [] == [], so lets go ahead and fill in foldr's "empty list handler":

```<code>map f xs = foldr _ [] xs
</code>```

The : case is handled by the first argument. Remember what we said above; that is supposed to be a function taking an element of the list and the result of processing the tail of the list. And remembering that we're configuring this foldr to do the job of map, the "result of processing the tail of the list" is going to be the equivalent of having already mapped f over the tail of the list. So all we need to do is write a function that can take an element of the original list, apply f to it, and glue it onto the front of the already-mapped list. So:

```<code>map f xs = foldr applyCons [] xs
  where applyCons elem mappedRest = f elem : mappedRest

-- or

map f xs = foldr (\x xs' -> f x : xs') [] xs
</code>```

I would expect something like either of those to get full marks on an exam question.

Just for a little follow up though, lets see how the "short and weird" version you quoted map f = foldr ((:) . f) [] is actually basically the same as the above, just with a few fairly mechanical simplifications applied. Starting from here:

```<code>map f xs = foldr (\x xs' -> f x : xs') [] xs
</code>```

We can see that both sides of that definition are just <something> xs; that is, xs is the last argument on both sides of the = and isn't otehrwised used anywhere else. So we can drop it from both sides (this process is known as "eta-reduction" in unnecessarily fancy jargon), leaving us with:

```<code>map f = foldr (\x xs' -> f x : xs') []
</code>```

Then we can use : inside the lambda in its prefix form instead of as an operator:

```<code>map f = foldr (\x xs' -> (:) (f x) xs') []
</code>```

Which reveals that in the lambda function xs' is also the last thing in the list of parameters and the last argument on the right hand side, so we can drop that too:

```<code>map f = foldr (\x -> (:) (f x)) []
</code>```

And then you may or may not remember (but should be able to figure out if you remember how it works) that the definition of the composition . operator is:

```<code>f . g = \x -> f (g x)
</code>```

Or in our case:

```<code>(:) . f = \x -> (:) (f x)
</code>```

The right hand side of that is exactly the lambda we were working with, so we can replace it with the left hand side:

```<code>map f = foldr ((:) . f) []
</code>```

Which is our weird and short version.

The reason I said it was "basically the same" as the longer versions you might have found more readable, is that I could rewrite the long version into the short version without thinking at all about map or foldr, or the purpose of any of this code at all. I "merely" applied some knowledge I had about functions in general (and the . operator in particular) to make some changes that always result in equivalent code, without needing any knowledge of what the code is doing. In an exam situation you almost certainly won't be expected to produce the shortest expressions (unless it was an exam for an advanced course, perhaps). And even in real programming "short" isn't a virtue in and of itself (the virtue is "simpler and clearer", which sometimes means shorter), so stopping at the longer non-weird version is fine if that is clearer to you.

Title: Trying to write `map` using `foldr`

Body:
I had an exam where I was forced to create the function map using foldr
I know by now there is a wirde and short way to do it which is map f = foldr ((:) . f) [].
My shot was

map' :: (a->b) -> [a] ->[b]
map' f [] = []
map' f [x] = foldr f x [] : []
map' f (x:xs) (foldr f x []) ++ map' f xs

my problem is that f need to be of type a->b->b and it is a->b.
How can i force it to work? how can i change f to fit this implemention?

Body:
foldr is a very general recursive list processing function, because of how it mirrors the structure of the list type it self:

data [a]        -- a list is either
  = a : [a]     -- a head element, plus a tail list
  | []          -- or an empty list

foldr :: (a -> b -> b)    -- given a handler for a head element and the
                          --   result of processing the tail
      -> b                -- and a "handler" for an empty list
      -> [a]              -- foldr turns a list
      -> b                -- into a single result

That might need a bit more unpacking than I could fit in inline comments.

We all know a list has two cases, either a cons cell : containing a single element and the rest of the list, or an empty list containing no information.

Well, the first two parameters to foldr are exactly instructions for how to handle each of these two cases. The a -> b -> b function parameter is the handler for the cons : case. When foldr encounters a cons cell like x : xs it will call the handler with x as the first argument, which fits type a. The second argument it passes to the handler is not the rest of the list xs, but the result of foldr processing xs - remembering that foldr ultimately turns a list into a b, that fits the second parameter of the a -> b -> b type.

The "handler" for the empty list case is much simpler; since an empty list contains no more information, we don't need a function that can transform the information inside an empty list into a b, we can just use a b value as the result immediately.

Because of this mirrored structure, a lot of recursive functions can be implemented by calling foldr with appropriate arguments. The exam question is certainly asking you to make use of this and implement map in terms of foldr without using recursion; the recursion inside foldr is enough.

So your answer must look like this:

map f xs = foldr _ _ xs

You don't need to use multiple cases to handle an empty list or a cons cell; we handle those cases by the two arguments we give to foldr. The empty list case is obvious, since map f [] == [], so lets go ahead and fill in foldr's "empty list handler":

map f xs = foldr _ [] xs

The : case is handled by the first argument. Remember what we said above; that is supposed to be a function taking an element of the list and the result of processing the tail of the list. And remembering that we're configuring this foldr to do the job of map, the "result of processing the tail of the list" is going to be the equivalent of having already mapped f over the tail of the list. So all we need to do is write a function that can take an element of the original list, apply f to it, and glue it onto the front of the already-mapped list. So:

map f xs = foldr applyCons [] xs
  where applyCons elem mappedRest = f elem : mappedRest

-- or

map f xs = foldr (\x xs' -> f x : xs') [] xs

I would expect something like either of those to get full marks on an exam question.

Just for a little follow up though, lets see how the "short and weird" version you quoted map f = foldr ((:) . f) [] is actually basically the same as the above, just with a few fairly mechanical simplifications applied. Starting from here:

map f xs = foldr (\x xs' -> f x : xs') [] xs

We can see that both sides of that definition are just <something> xs; that is, xs is the last argument on both sides of the = and isn't otehrwised used anywhere else. So we can drop it from both sides (this process is known as "eta-reduction" in unnecessarily fancy jargon), leaving us with:

map f = foldr (\x xs' -> f x : xs') []

Then we can use : inside the lambda in its prefix form instead of as an operator:

map f = foldr (\x xs' -> (:) (f x) xs') []

Which reveals that in the lambda function xs' is also the last thing in the list of parameters and the last argument on the right hand side, so we can drop that too:

map f = foldr (\x -> (:) (f x)) []

And then you may or may not remember (but should be able to figure out if you remember how it works) that the definition of the composition . operator is:

f . g = \x -> f (g x)

Or in our case:

(:) . f = \x -> (:) (f x)

The right hand side of that is exactly the lambda we were working with, so we can replace it with the left hand side:

map f = foldr ((:) . f) []

Which is our weird and short version.

The reason I said it was "basically the same" as the longer versions you might have found more readable, is that I could rewrite the long version into the short version without thinking at all about map or foldr, or the purpose of any of this code at all. I "merely" applied some knowledge I had about functions in general (and the . operator in particular) to make some changes that always result in equivalent code, without needing any knowledge of what the code is doing. In an exam situation you almost certainly won't be expected to produce the shortest expressions (unless it was an exam for an advanced course, perhaps). And even in real programming "short" isn't a virtue in and of itself (the virtue is "simpler and clearer", which sometimes means shorter), so stopping at the longer non-weird version is fine if that is clearer to you.


问:
Create a singleton class with react native
I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post

```<code>export default class Credentials {

    static myInstance = null;

    _userID = "";

    static getInstance() {
        if (myInstance == null) {
            myInstance = new Credentials();
        }

        return myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}
</code>```

when I call Credentials.getInstance() I get a warning

Can't find variable myInstance

答:
I think the most clean and easy solution would be the "ES6 singleton pattern" (not sure if there is an official name for this pattern).

You export the instance as default and everywhere you import it you get the same instance. This relies on the fact that module require is cached.

You would create your class and export the like so:

```<code>class Credentials {

    constructor() {
        this._userID = "";
    }

    get userID() {
        return this._userID;
    }

    set userID(userID) {
        this._userID = userID;
    }

}

export default new Credentials();
</code>```

Wherever you import it you get the same instance:

```<code>import credentials from './credentials';
</code>```

Body:
I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post

export default class Credentials {

    static myInstance = null;

    _userID = "";

    static getInstance() {
        if (myInstance == null) {
            myInstance = new Credentials();
        }

        return myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}

when I call Credentials.getInstance() I get a warning

Can't find variable myInstance

Body:
I think the most clean and easy solution would be the "ES6 singleton pattern" (not sure if there is an official name for this pattern).

You export the instance as default and everywhere you import it you get the same instance. This relies on the fact that module require is cached.

You would create your class and export the like so:

class Credentials {

    constructor() {
        this._userID = "";
    }

    get userID() {
        return this._userID;
    }

    set userID(userID) {
        this._userID = userID;
    }

}

export default new Credentials();

Wherever you import it you get the same instance:

import credentials from './credentials';


问:
additional options in Chrome headless print-to-pdf
I need help one more time. I am trying to print a page to pdf using headless feature of the chrome. However, header and footer is present in the pdf. I found that this option as been implemented in Devtools.

https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

However, i can't find how can i use these options in CLI. Also is it possible to invoke the Devtools from selenium?

Additionally how can i invoke Page.PrintToPDF in Dev tools. I tried to run the command in Console. It is showing Page is undefined.

答:
Add this CSS to the page your creating into a PDF to remove Chrome Headless's implemented Header and Footer.

CSS:

```<code>@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}
</code>```

You should format your command like below to create the PDF:

```<code>"C:\PATH\TO\CHROME\EXECUTABLE\FILE", "--headless","--disable-gpu","--print-to-pdf=" + directory path to where you want the file to go followed by the desired file name/fileName.pdf,"--no-margins", "the path to the file you want turned into a pdf"
</code>```

Example 1:

```<code>C:\chrome-win/chrome --headless --disable-gpu --print-to-pdf=C:\user\fileName.pdf --no-margins C:\Projects\index.html
</code>```

Example 2:

You can also test this functionality by navigating in your command line to the folder containing Chrome executable file, and running this command:

```<code>chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/
</code>```

Body:
Add this CSS to the page your creating into a PDF to remove Chrome Headless's implemented Header and Footer.

CSS:

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

You should format your command like below to create the PDF:

"C:\PATH\TO\CHROME\EXECUTABLE\FILE", "--headless","--disable-gpu","--print-to-pdf=" + directory path to where you want the file to go followed by the desired file name/fileName.pdf,"--no-margins", "the path to the file you want turned into a pdf"

Example 1:

C:\chrome-win/chrome --headless --disable-gpu --print-to-pdf=C:\user\fileName.pdf --no-margins C:\Projects\index.html

Example 2:

You can also test this functionality by navigating in your command line to the folder containing Chrome executable file, and running this command:

chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/


问:
Access flask.g inside greenlet
I'm using Flask + gevent and want to access the flask.g application global inside the target function of a greenlet.
 I'm using the copy_current_request_context decorator and have a situation pretty similar to example given in the docs:

```<code>import gevent
from flask import copy_current_request_context, g

@app.route('/')
def index():
    g.user_data = 'foobar'
    g.more_user_data = 'baz'

    @copy_current_request_context
    def do_some_work():
        some_func(g.user_data, g.more_user_data)
        ...

    gevent.spawn(do_some_work)
    return 'Regular response'
</code>```

However, I get the following error:

```<code>AttributeError: '_AppCtxGlobals' object has no attribute 'user_data'
</code>```

I think a new application context is pushed when the request context is copied? I set a trace in the Flask code here and that seems to be the case. So the error isn't all that surprising because the flask.g object is application context scoped as of 0.10 (see http://flask.pocoo.org/docs/0.12/api/#flask.Flask.app_ctx_globals_class).

Obviously, I can just pass the user data into the target function as arguments:

```<code>import gevent
from flask import g

@app.route('/')
def index():
    g.user_data = 'foobar'
    g.more_user_data = 'baz'

    def do_some_work(user_data, more_user_data):
        some_func(user_data, more_user_data)
        ...

    gevent.spawn(do_some_work, g.user_data, g.more_user_data)
    return 'Regular response'
</code>```

And this works just fine, but I was hoping to use flask.g if possible.

答:
flask.g is bound with the app context, not on request context, as the doc says:

Starting with Flask 0.10 this is stored on the application context and no longer on the request context ...

copy_current_request_context() only copy request context, but give you a new app context. You could create one to pass current app context with closure:

```<code>def copy_current_app_context(f):
    from flask.globals import _app_ctx_stack
    appctx = _app_ctx_stack.top
    def _(*args, **kwargs):
        with appctx:
            return f(*args, **kwargs)
    return _
</code>```

However, I prefer pass data to greenlet explicitly via arguments, which is cleaner.

Title: Access flask.g inside greenlet

Body:
I'm using Flask + gevent and want to access the flask.g application global inside the target function of a greenlet.
 I'm using the copy_current_request_context decorator and have a situation pretty similar to example given in the docs:

import gevent
from flask import copy_current_request_context, g

@app.route('/')
def index():
    g.user_data = 'foobar'
    g.more_user_data = 'baz'

    @copy_current_request_context
    def do_some_work():
        some_func(g.user_data, g.more_user_data)
        ...

    gevent.spawn(do_some_work)
    return 'Regular response'

However, I get the following error:

AttributeError: '_AppCtxGlobals' object has no attribute 'user_data'

I think a new application context is pushed when the request context is copied? I set a trace in the Flask code here and that seems to be the case. So the error isn't all that surprising because the flask.g object is application context scoped as of 0.10 (see http://flask.pocoo.org/docs/0.12/api/#flask.Flask.app_ctx_globals_class).

Obviously, I can just pass the user data into the target function as arguments:

import gevent
from flask import g

@app.route('/')
def index():
    g.user_data = 'foobar'
    g.more_user_data = 'baz'

    def do_some_work(user_data, more_user_data):
        some_func(user_data, more_user_data)
        ...

    gevent.spawn(do_some_work, g.user_data, g.more_user_data)
    return 'Regular response'

And this works just fine, but I was hoping to use flask.g if possible.

Body:
flask.g is bound with the app context, not on request context, as the doc says:

Starting with Flask 0.10 this is stored on the application context and no longer on the request context ...

copy_current_request_context() only copy request context, but give you a new app context. You could create one to pass current app context with closure:

def copy_current_app_context(f):
    from flask.globals import _app_ctx_stack
    appctx = _app_ctx_stack.top
    def _(*args, **kwargs):
        with appctx:
            return f(*args, **kwargs)
    return _

However, I prefer pass data to greenlet explicitly via arguments, which is cleaner.


问:
Copying Many2many field values to another Many2many field
I need to copy many2many field content to another class' many2many field.

 @api.multi
 def tester(self):
    context = self._context.copy()
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }
```

<p>My XML code:</p>

<pre class="lang-xml prettyprint-override"><code>  <button name="tester" string="Evaluer" type="object" class="oe_highlight" />
</code>```

But it returns the nom_risque and for the rubrique_ids only the last one.

答:
Hi try out the following and please try to understand my comments, too :-)

@api.multi
# even if it's trying out something, give it an understandable name
def tester(self):
    # seems to be a singleton call, so restrict it with self.ensure_one()
    # no need to copy the context here, just pass it in the end
    context = self._context.copy()
    # odoo's recordsets has some cool functions, e.g. mapped()
    # but that's only usefull on other scenarios
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    # you will call this new record later so don't forget to 'save' it
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        # that's just plain wrong, read the __doc__ on models.BaseModel.write()
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        # here is the mistake: take the id of your created record above
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }
```

<p>And now the hopefully working example:</p>

<pre class="lang-py prettyprint-override"><code>@api.multi
def create_test_record(self):
    self.ensure_one()
    test = self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [(6, 0, self.risque.rubrique_ids.ids)]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context
    }
</code>```

Body:
I need to copy many2many field content to another class' many2many field.

 @api.multi
 def tester(self):
    context = self._context.copy()
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

My XML code:

  <button name="tester" string="Evaluer" type="object" class="oe_highlight" />

But it returns the nom_risque and for the rubrique_ids only the last one.

Body:
Hi try out the following and please try to understand my comments, too :-)

@api.multi
# even if it's trying out something, give it an understandable name
def tester(self):
    # seems to be a singleton call, so restrict it with self.ensure_one()
    # no need to copy the context here, just pass it in the end
    context = self._context.copy()
    # odoo's recordsets has some cool functions, e.g. mapped()
    # but that's only usefull on other scenarios
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    # you will call this new record later so don't forget to 'save' it
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        # that's just plain wrong, read the __doc__ on models.BaseModel.write()
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        # here is the mistake: take the id of your created record above
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

And now the hopefully working example:

@api.multi
def create_test_record(self):
    self.ensure_one()
    test = self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [(6, 0, self.risque.rubrique_ids.ids)]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context
    }


问:
How to forward an HTTP request to external URL? WildFly 8.1, standalone deployment
I need to forward all requests to an web application to an external URL.
The webapp is deployed from a WAR file, running on WildFly 8.1, deployed as a standalone module. </p>

<p>What do I need to change in the standalone.xml ?
Tried creating new default-server configuration, but it is still trying to hit the application.
The log file has 'New missing/unsatisfied dependencies' error, service jboss.naming.context.java.app.myApp (missing) dependents:... </p>

答:
You can try to configure Undertow as reverse proxy. See e.g: http://www.mastertheboss.com/jboss-server/wildfly-8/configuring-a-reverse-proxy-with-undertow

```<code><subsystem xmlns="urn:jboss:domain:undertow:1.1">
   <handlers>
    . . . .
    <reverse-proxy name="myproxy">
         <host name="http://192.168.0.2/myapp-develop"/>
    </reverse-proxy>
    </handlers>
</subsystem>
</code>```

and

```<code><host name="default-host" alias="localhost">
    . . .
   <location name="/myapp-stable" handler="myproxy"/>
</host>
</code>```

Body:
I need to forward all requests to an web application to an external URL.
The webapp is deployed from a WAR file, running on WildFly 8.1, deployed as a standalone module.

What do I need to change in the standalone.xml ?
Tried creating new default-server configuration, but it is still trying to hit the application.
The log file has 'New missing/unsatisfied dependencies' error, service jboss.naming.context.java.app.myApp (missing) dependents:...

Body:
You can try to configure Undertow as reverse proxy. See e.g: http://www.mastertheboss.com/jboss-server/wildfly-8/configuring-a-reverse-proxy-with-undertow

<subsystem xmlns="urn:jboss:domain:undertow:1.1">
   <handlers>
    . . . .
    <reverse-proxy name="myproxy">
         <host name="http://192.168.0.2/myapp-develop"/>
    </reverse-proxy>
    </handlers>
</subsystem>

and

<host name="default-host" alias="localhost">
    . . .
   <location name="/myapp-stable" handler="myproxy"/>
</host>


问:
XPath trying to get the third position
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

```<code><publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>
</code>```

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

答:
In addition to what others have said, note that //authors[1] selects every authors element that is the first authors child of its parent, while (//authors)[1] selects the first authors element in the entire document, which is I think what you want.

(You talked of getting the "whole row". I have no idea what a "row" is in an XML context. If you want to communicate clearly, the first rule is to learn the technical vocabulary...)

Title: XPath trying to get the third position

Body:
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

<publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.


问:
AWS EC2 Windows UserData script not running
I have a windows batch script that runs locally and also runs on the EC2 when I run it manually. However, when I try to launch an ec2 via the CLI and I feed in the script in the user-data parameter it does not run.

This is the script:

```<code>for /l %%x in (20171101,1,20171102) do (
start "S3Copy" C:\Progra~1\Amazon\AWSCLI\aws s3 cp
s3://bucket1/%%x s3://bucket2/%%x --recursive
)

echo waiting
:loop
timeout 1 >nul
tasklist /v |find "S3Copy" >nul && goto :loop
echo all of them are finished

shutdown.exe /s /t 00
</code>```

When I pass it into UserData I surround it with:

[script] [/script] (angle brackets)

Yet it does not run like this.

As I have stated, I can log into the same Ec2 that was launched and I can run the script manually and works as expected.

I will say, when I log in manually I use a specific user, when I launch from cli, it uses a specific Key file, which could use a different user, but the .aws config is set up for all users on that AMI.

What might be missing here?

答:
Are you using an IAM Role or an IAM User? More secure to use a role and it will potentially solve your problem: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

Also, take a look at this - there are a few more nuances for Windows as opposed to Linux: http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-windows-user-data.html

Body:
I have a windows batch script that runs locally and also runs on the EC2 when I run it manually. However, when I try to launch an ec2 via the CLI and I feed in the script in the user-data parameter it does not run.

This is the script:

for /l %%x in (20171101,1,20171102) do (
start "S3Copy" C:\Progra~1\Amazon\AWSCLI\aws s3 cp
s3://bucket1/%%x s3://bucket2/%%x --recursive
)

echo waiting
:loop
timeout 1 >nul
tasklist /v |find "S3Copy" >nul && goto :loop
echo all of them are finished

shutdown.exe /s /t 00

When I pass it into UserData I surround it with:

[script] [/script] (angle brackets)

Yet it does not run like this.

As I have stated, I can log into the same Ec2 that was launched and I can run the script manually and works as expected.

I will say, when I log in manually I use a specific user, when I launch from cli, it uses a specific Key file, which could use a different user, but the .aws config is set up for all users on that AMI.

What might be missing here?


问:
How does instructions like I/O work in user mode?
I am curious because I am reading this OS book which mentions

"User programs always run in user mode, which permits only a subset of the instructions [...]. Generally, all instructions involving I/O and memory protection are disallowed in user mode.
To obtain services from the OS, a user program must make a system call, which traps into the kernel and invokes the OS."

If I/O is not allowed generally in user mode, but let's say I have a program in C++ or Java which asks for input, or let's say something else like a search bar in any program. Whenever I select the search bar (meaning I will write something) then a TRAP instruction is called to invoke the OS (since the OS runs in kernel) to be able to have access to I/O, that is, the keyboard? I am not sure if I follow correctly or what am I getting wrong.

The I/O is not allowed in user mode, but you use Input for applications in the OS, or even with the OS itself there are keyboard commands. If you can use keyboard commands that means the OS is ready for I/O at any time. Then the original statement about I/O instructions being disallowed in user mode.

I am sorry for my ignorance but I am just a little bit confused with these terms and difference between user and kernel. I know the OS runs in kernel mode, and the applications run in the OS, so in the end the applications do have access to I/O.

答:
Don't application need to have the OS deal with there I/O for them?
Meaning, only the OS has the authority to do those type of things...

Am I wrong?